Skip to content

Commit

Permalink
refactor: Update login code and session handling
Browse files Browse the repository at this point in the history
  • Loading branch information
A91y committed Oct 24, 2024
1 parent 3c1b210 commit 5375804
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 4 deletions.
39 changes: 36 additions & 3 deletions src/components/Login/Login.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,6 @@ const Login = () => {
accessToken?: string | null;
isVerifiedEmail?: boolean | true;
}

const sessionUser = useMemo(
() => session?.user as SessionUser | null,
[session]
Expand Down Expand Up @@ -80,17 +79,42 @@ const Login = () => {
console.error("Error parsing cookie session:", error);
Cookies.remove("session");
router.push("/");
dispatch(
setUser({
name: "",
email: "",
photo: "",
githubId: "",
login: "",
accessToken: "",
status: "loading",
isVerifiedEmail: true,
})
);
}
} else {
dispatch(
setUser({
name: "",
email: "",
photo: "",
githubId: "",
login: "",
accessToken: "",
status: "loading",
isVerifiedEmail: true,
})
);
router.push("/");
}
};

useLayoutEffect(() => {
if (sessionUser) {
store.dispatch(decrement());
const sessionExpiryDate = new Date(session?.expires || "");
Cookies.set("session", JSON.stringify(sessionUser), {
expires: 8 / 24,
expires: sessionExpiryDate,
});
dispatch(
setUser({
Expand All @@ -112,7 +136,7 @@ const Login = () => {
} else {
handleSessionFromCookies();
}
}, [sessionUser, pathname, router, dispatch]);
}, [session, pathname, router, dispatch]);

useEffect(() => {
if (status === "unauthenticated") {
Expand All @@ -132,6 +156,7 @@ const Login = () => {
router.push("/");
}
}, [router, dispatch, status]);

const logout = async () => {
await signOut({ redirect: false });
dispatch(
Expand All @@ -150,6 +175,14 @@ const Login = () => {
router.push("/");
};

useEffect(() => {
if (!Cookies.get("session")) handleSessionFromCookies();
}, [pathname]);

useEffect(() => {
console.log(session);
}, [session, pathname]);

const userLogin = () => {
signIn("github");
};
Expand Down
12 changes: 11 additions & 1 deletion src/config/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,11 @@ export const authOptions: NextAuthOptions = {
},
async session({ session, token }: { session: any; token: any }) {
session.accessToken = token.accessToken;
session.user = { ...session.user, ...token.profile };
session.user = {
...session.user,
...token.profile,
accessToken: token.accessToken,
};
await initializeUser(session.user.id, session.user.email);
const userDbData = bigintToString(
await getDbUser(BigInt(session.user.id))
Expand All @@ -56,6 +60,12 @@ export const authOptions: NextAuthOptions = {
return session;
},
},
jwt: {
maxAge: 10, // 8 hours in seconds
},
session: {
maxAge: 10, // 8 hours in seconds
},
};

async function getEmail(authToken: string) {
Expand Down

0 comments on commit 5375804

Please sign in to comment.