Refactor authentication and session management: remove debug logging and streamline session verification

This commit is contained in:
2025-10-08 23:00:44 +01:00
parent 72410be343
commit 429649191b
3 changed files with 7 additions and 53 deletions
-8
View File
@@ -35,14 +35,6 @@ export async function POST(request: NextRequest) {
role: user[0].role as 'user' | 'admin',
});
// Debug: Check if cookie was actually set
console.log('LOGIN: Session created for user:', user[0].email);
console.log('LOGIN: Request headers:', {
host: request.headers.get('host'),
'x-forwarded-proto': request.headers.get('x-forwarded-proto'),
'user-agent': request.headers.get('user-agent')
});
// Log the login activity
await logActivity({
userId: user[0].id,
+7 -34
View File
@@ -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: '/',
});
}
-11
View File
@@ -15,17 +15,6 @@ export default async function middleware(req: NextRequest) {
const isAuthRoute = authRoutes.includes(path);
const cookie = req.cookies.get('session')?.value;
// Debug logging for production
if (!cookie && (isProtectedRoute || isAuthRoute)) {
console.log(`No session cookie found for ${path}, headers:`, {
host: req.headers.get('host'),
'x-forwarded-proto': req.headers.get('x-forwarded-proto'),
'x-forwarded-host': req.headers.get('x-forwarded-host'),
cookies: req.headers.get('cookie')
});
}
const session = await decrypt(cookie);
// Redirect to login if accessing protected route without session