From 6b1bde7a5d23590fccc0d995dfe8fcee0bdc0edb Mon Sep 17 00:00:00 2001 From: dqnid Date: Tue, 3 Sep 2024 22:38:25 +0200 Subject: [PATCH] feat(auth): session closed after token expires --- front/src/middleware.ts | 24 ++++++++++++++++++- .../src/modules/auth/configs/auth.options.ts | 3 +-- front/src/modules/auth/types/next-auth.d.ts | 1 + 3 files changed, 25 insertions(+), 3 deletions(-) diff --git a/front/src/middleware.ts b/front/src/middleware.ts index 859e5bd..59365a2 100644 --- a/front/src/middleware.ts +++ b/front/src/middleware.ts @@ -5,7 +5,9 @@ export default withAuth({ pages: authOptions.pages, callbacks: { authorized({ req, token }) { - if (token) return true; + if (token && token.apiSession.exp * 1000 > Date.now()) { + return true; + } const pathname = req.nextUrl.pathname; return ( pathname.startsWith("/_next/") || @@ -15,3 +17,23 @@ export default withAuth({ }, }, }); + +const value = { + token: { + name: "dqnid", + picture: "https://picsum.photos/200/300", + sub: "dqnid", + user: { + id: "dqnid", + roles: ["user", "manager", "admin"], + image: "https://picsum.photos/200/300", + name: "dqnid", + }, + apiSession: { + exp: 1725398177, + }, + iat: 1725394577, + exp: 1727986577, + jti: "3203d3c7-dc27-4599-b37e-16737b3a6674", + }, +}; diff --git a/front/src/modules/auth/configs/auth.options.ts b/front/src/modules/auth/configs/auth.options.ts index 4a1fbf4..cf0033f 100644 --- a/front/src/modules/auth/configs/auth.options.ts +++ b/front/src/modules/auth/configs/auth.options.ts @@ -55,12 +55,11 @@ export const authOptions: AuthOptions = { image: token_payload.picture, name: token_payload.username, apiSession: { + exp: token_payload.exp, accessToken: response_body.access_token, }, }; - console.log("__loged:", user); - return user; }, }), diff --git a/front/src/modules/auth/types/next-auth.d.ts b/front/src/modules/auth/types/next-auth.d.ts index 7e8d5fb..d5687fc 100644 --- a/front/src/modules/auth/types/next-auth.d.ts +++ b/front/src/modules/auth/types/next-auth.d.ts @@ -4,6 +4,7 @@ import { JWT, DefaultJWT } from "next-auth/jwt"; declare module "next-auth" { type Role = "user" | "manager" | "admin"; interface ApiSession { + exp?: number; accessToken: string; refreshToken?: string; }