From 198f50238134fd43cc7384e91be55329ebbc4f67 Mon Sep 17 00:00:00 2001 From: Dominik Stumpf <122315398+dominik-stumpf@users.noreply.github.com> Date: Wed, 20 Nov 2024 16:10:19 +0100 Subject: [PATCH] chore: make cookie expiration same as jwt (#1554) * chore: make cookie expiration same as jwt * fix: update package-lock * chore: remove package-lock.json --------- Co-authored-by: BrickheadJohnny --- package.json | 1 + src/actions/auth.ts | 30 +++++++++++++++++------------- 2 files changed, 18 insertions(+), 13 deletions(-) diff --git a/package.json b/package.json index 7b12711d08..bf9f7fa1bf 100644 --- a/package.json +++ b/package.json @@ -31,6 +31,7 @@ "clsx": "^2.1.1", "foxact": "^0.2.41", "jotai": "^2.10.2", + "jwt-decode": "^4.0.0", "next": "15.0.3", "next-themes": "^0.4.3", "react": "19.0.0-rc-66855b96-20241106", diff --git a/src/actions/auth.ts b/src/actions/auth.ts index 5f03db573b..fdb8a4ae1d 100644 --- a/src/actions/auth.ts +++ b/src/actions/auth.ts @@ -2,6 +2,7 @@ import { GUILD_AUTH_COOKIE_NAME } from "@/config/constants"; import { env } from "@/lib/env"; +import { jwtDecode } from "jwt-decode"; import { cookies } from "next/headers"; import { redirect } from "next/navigation"; import { z } from "zod"; @@ -12,6 +13,12 @@ const authSchema = z.object({ userId: z.string().uuid(), }); +const tokenSchema = z.object({ + userId: z.string().uuid(), + exp: z.number().positive().int(), + iat: z.number().positive().int(), +}); + export const signIn = async ({ message, signature, @@ -38,26 +45,23 @@ export const signIn = async ({ requestInit, ); + let json: unknown; if (signInRes.status === 401) { const registerRes = await fetch( `${env.NEXT_PUBLIC_API}/auth/siwe/register`, requestInit, ); - const json = await registerRes.json(); - - const registerData = authSchema.parse(json); - cookieStore.set(GUILD_AUTH_COOKIE_NAME, registerData.token); - - return registerData; + json = await registerRes.json(); + } else { + json = await signInRes.json(); } + const authData = authSchema.parse(json); + const { exp } = tokenSchema.parse(jwtDecode(authData.token)); - const json = await signInRes.json(); - - const signInData = authSchema.parse(json); - - cookieStore.set(GUILD_AUTH_COOKIE_NAME, signInData.token); - - return signInData; + cookieStore.set(GUILD_AUTH_COOKIE_NAME, authData.token, { + expires: new Date(exp * 1000), + }); + return authData; }; export const signOut = async (redirectTo?: string) => {