Refactor session management and enhance OAuth2 callback handling
- Updated session management functions to include cookie handling for session creation and destruction. - Introduced applySessionCookie and clearSessionCookie functions for better cookie management in responses. - Enhanced error logging in the OAuth2 callback to improve debugging. - Revised PHASE-TRACKING.md to reflect changes in session handling and OAuth2 integration.
This commit is contained in:
@@ -3,7 +3,7 @@ import { type NextRequest, NextResponse } from 'next/server';
|
||||
import { exchangeCodeForToken, fetchDiscordUser } from '@/lib/discord-oauth';
|
||||
import { env } from '@/lib/env';
|
||||
import { redis } from '@/lib/redis';
|
||||
import { createSession } from '@/lib/session';
|
||||
import { applySessionCookie, createSession } from '@/lib/session';
|
||||
|
||||
function oauthStateKey(state: string): string {
|
||||
return `webui:oauth:state:${state}`;
|
||||
@@ -36,6 +36,7 @@ export async function GET(request: NextRequest) {
|
||||
}
|
||||
await redis.del(stateKey);
|
||||
|
||||
let cookieValue: string;
|
||||
try {
|
||||
const token = await exchangeCodeForToken(code);
|
||||
const discordUser = await fetchDiscordUser(token.access_token);
|
||||
@@ -47,14 +48,19 @@ export async function GET(request: NextRequest) {
|
||||
avatar: discordUser.avatar ?? null
|
||||
};
|
||||
|
||||
await createSession({
|
||||
cookieValue = await createSession({
|
||||
user,
|
||||
accessToken: token.access_token,
|
||||
tokenExpiresAt: Date.now() + token.expires_in * 1000
|
||||
});
|
||||
} catch {
|
||||
} catch (error) {
|
||||
console.error('OAuth callback failed', error);
|
||||
return loginRedirect('oauth_failed');
|
||||
}
|
||||
|
||||
return NextResponse.redirect(new URL('/dashboard', env.WEBUI_URL));
|
||||
// Cookie must be set on the redirect response — cookies().set() alone is not
|
||||
// reliably attached when returning NextResponse.redirect() from a route handler.
|
||||
const response = NextResponse.redirect(new URL('/dashboard', env.WEBUI_URL));
|
||||
applySessionCookie(response, cookieValue);
|
||||
return response;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user