Refactor authentication and session management: remove debug logging and streamline session verification
This commit is contained in:
+7
-34
@@ -32,31 +32,19 @@ export async function encrypt(payload: SessionPayload) {
|
||||
|
||||
export async function decrypt(session: string | undefined = '') {
|
||||
try {
|
||||
if (!session) {
|
||||
console.log('Failed to verify session: No session provided');
|
||||
return null;
|
||||
}
|
||||
if (!session) return null;
|
||||
|
||||
const { payload } = await jwtVerify(session, encodedKey, {
|
||||
algorithms: ['HS256'],
|
||||
});
|
||||
|
||||
const sessionData = {
|
||||
return {
|
||||
userId: payload.userId as string,
|
||||
email: payload.email as string,
|
||||
role: payload.role as 'user' | 'admin',
|
||||
expiresAt: new Date(payload.expiresAt as number),
|
||||
};
|
||||
|
||||
// Check if session is expired
|
||||
if (sessionData.expiresAt < new Date()) {
|
||||
console.log('Failed to verify session: Session expired');
|
||||
return null;
|
||||
}
|
||||
|
||||
return sessionData;
|
||||
} catch (error) {
|
||||
console.log('Failed to verify session:', error instanceof Error ? error.message : 'Unknown error');
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -67,26 +55,13 @@ export async function createSession(payload: Omit<SessionPayload, 'expiresAt'>)
|
||||
|
||||
const cookieStore = await cookies();
|
||||
|
||||
// For Cloudflare tunnel: external is HTTPS, internal is HTTP
|
||||
// Use secure cookies when NEXTAUTH_URL is https (external URL)
|
||||
const isSecure = process.env.NEXTAUTH_URL?.startsWith('https') ?? false;
|
||||
|
||||
const cookieOptions = {
|
||||
cookieStore.set('session', session, {
|
||||
httpOnly: true,
|
||||
secure: isSecure,
|
||||
secure: process.env.NODE_ENV === 'production',
|
||||
expires: expiresAt,
|
||||
sameSite: isSecure ? 'none' : 'lax', // none required for secure cross-site
|
||||
sameSite: 'lax',
|
||||
path: '/',
|
||||
} as const;
|
||||
|
||||
console.log('CREATE_SESSION: Setting cookie with options:', cookieOptions);
|
||||
console.log('CREATE_SESSION: Environment:', {
|
||||
NODE_ENV: process.env.NODE_ENV,
|
||||
NEXTAUTH_URL: process.env.NEXTAUTH_URL,
|
||||
isSecure
|
||||
});
|
||||
|
||||
cookieStore.set('session', session, cookieOptions);
|
||||
}
|
||||
|
||||
export async function updateSession() {
|
||||
@@ -101,13 +76,11 @@ export async function updateSession() {
|
||||
const expires = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000);
|
||||
const newSession = await encrypt({ ...payload, expiresAt: expires });
|
||||
|
||||
const isSecure = process.env.NEXTAUTH_URL?.startsWith('https') ?? false;
|
||||
|
||||
cookieStore.set('session', newSession, {
|
||||
httpOnly: true,
|
||||
secure: isSecure,
|
||||
secure: process.env.NODE_ENV === 'production',
|
||||
expires: expires,
|
||||
sameSite: isSecure ? 'none' : 'lax',
|
||||
sameSite: 'lax',
|
||||
path: '/',
|
||||
});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user