Auth0 working!
This commit is contained in:
24
web/lib/auth0.js
Normal file
24
web/lib/auth0.js
Normal file
@@ -0,0 +1,24 @@
|
||||
import { initAuth0 } from "@auth0/nextjs-auth0";
|
||||
|
||||
export default initAuth0({
|
||||
secret: process.env.SESSION_COOKIE_SECRET,
|
||||
issuerBaseURL: process.env.NEXT_PUBLIC_AUTH0_DOMAIN,
|
||||
baseURL: process.env.NEXT_PUBLIC_BASE_URL,
|
||||
clientID: process.env.NEXT_PUBLIC_AUTH0_CLIENT_ID,
|
||||
clientSecret: process.env.AUTH0_CLIENT_SECRET,
|
||||
routes: {
|
||||
callback:
|
||||
process.env.NEXT_PUBLIC_REDIRECT_URI ||
|
||||
"http://localhost:3000/api/callback",
|
||||
postLogoutRedirect:
|
||||
process.env.NEXT_PUBLIC_POST_LOGOUT_REDIRECT_URI ||
|
||||
"http://localhost:3000",
|
||||
},
|
||||
authorizationParams: {
|
||||
response_type: "code",
|
||||
scope: process.env.NEXT_PUBLIC_AUTH0_SCOPE,
|
||||
},
|
||||
session: {
|
||||
absoluteDuration: process.env.SESSION_COOKIE_LIFETIME,
|
||||
},
|
||||
});
|
||||
73
web/lib/user.js
Normal file
73
web/lib/user.js
Normal file
@@ -0,0 +1,73 @@
|
||||
import { useState, useEffect } from "react";
|
||||
|
||||
export async function fetchUser(cookie = "") {
|
||||
if (typeof window !== "undefined" && window.__user) {
|
||||
return window.__user;
|
||||
}
|
||||
|
||||
const res = await fetch(
|
||||
"/api/me",
|
||||
cookie
|
||||
? {
|
||||
headers: {
|
||||
cookie,
|
||||
},
|
||||
}
|
||||
: {}
|
||||
);
|
||||
|
||||
if (!res.ok) {
|
||||
delete window.__user;
|
||||
return null;
|
||||
}
|
||||
|
||||
const json = await res.json();
|
||||
if (typeof window !== "undefined") {
|
||||
window.__user = json;
|
||||
}
|
||||
return json;
|
||||
}
|
||||
|
||||
export function useFetchUser({ required } = {}) {
|
||||
const [loading, setLoading] = useState(
|
||||
() => !(typeof window !== "undefined" && window.__user)
|
||||
);
|
||||
const [user, setUser] = useState(() => {
|
||||
if (typeof window === "undefined") {
|
||||
return null;
|
||||
}
|
||||
|
||||
return window.__user || null;
|
||||
});
|
||||
|
||||
useEffect(
|
||||
() => {
|
||||
if (!loading && user) {
|
||||
return;
|
||||
}
|
||||
setLoading(true);
|
||||
let isMounted = true;
|
||||
|
||||
fetchUser().then((user) => {
|
||||
// Only set the user if the component is still mounted
|
||||
if (isMounted) {
|
||||
// When the user is not logged in but login is required
|
||||
if (required && !user) {
|
||||
window.location.href = "/api/login";
|
||||
return;
|
||||
}
|
||||
setUser(user);
|
||||
setLoading(false);
|
||||
}
|
||||
});
|
||||
|
||||
return () => {
|
||||
isMounted = false;
|
||||
};
|
||||
},
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
[]
|
||||
);
|
||||
|
||||
return { user, loading };
|
||||
}
|
||||
Reference in New Issue
Block a user