add new data 2025 05 12

This commit is contained in:
Fanrouver
2025-12-05 10:33:40 +07:00
parent 642be0f9df
commit 10ef054de6
6 changed files with 75 additions and 48 deletions

No files matched your search

+16 -15
View File
@@ -1,4 +1,12 @@
// server/api/auth/keycloak-callback.ts - FIX APPLIED
// server/api/auth/keycloak-callback.ts - EXTENDED SESSION FIX
// Add this at the top of the file (after imports)
const SESSION_DURATION = 24 * 60 * 60; // 7 days in seconds (customize as needed)
// Or use one of these alternatives:
// const SESSION_DURATION = 24 * 60 * 60; // 1 day
// const SESSION_DURATION = 30 * 24 * 60 * 60; // 30 days
// const SESSION_DURATION = 12 * 60 * 60; // 12 hours
export default defineEventHandler(async (event) => {
try {
const config = useRuntimeConfig();
@@ -28,8 +36,8 @@ export default defineEventHandler(async (event) => {
if (!state || state !== storedState) {
console.error('❌ Invalid state parameter - possible CSRF attack');
console.error('   Expected:', storedState);
console.error('   Received:', state);
console.error(' Expected:', storedState);
console.error(' Received:', state);
const errorMsg = encodeURIComponent('Security validation failed. Please try logging in again.');
return sendRedirect(event, `/LoginPage?error=${errorMsg}`);
@@ -46,7 +54,6 @@ export default defineEventHandler(async (event) => {
const tokenUrl = `${config.keycloakIssuer}/protocol/openid-connect/token`;
const redirectUri = `${config.public.authUrl}/api/auth/keycloak-callback`;
// ... (Token exchange logic remains the same) ...
const tokenPayload = new URLSearchParams({
grant_type: 'authorization_code',
client_id: config.keycloakClientId,
@@ -72,7 +79,6 @@ export default defineEventHandler(async (event) => {
const tokens = await tokenResponse.json();
// ... (Token decoding and sessionData creation remains the same) ...
let idTokenPayload;
try {
idTokenPayload = JSON.parse(
@@ -96,33 +102,28 @@ export default defineEventHandler(async (event) => {
accessToken: tokens.access_token,
idToken: tokens.id_token,
refreshToken: tokens.refresh_token,
expiresAt: Date.now() + (tokens.expires_in * 1000),
// CHANGED: Use custom session duration instead of Keycloak's token expiry
expiresAt: Date.now() + (SESSION_DURATION * 1000),
createdAt: Date.now(),
};
// ----------------------------------------------------
// 👇 CRITICAL FIX FOR DEPLOYED HTTPS ENVIRONMENTS 👇
// ----------------------------------------------------
// Check if the request was originally HTTPS (via proxy)
const isSecure = process.env.NODE_ENV === 'production' ||
event.node.req.headers['x-forwarded-proto'] === 'https';
console.log('🔗 Setting session cookie with secure flag:', isSecure);
console.log('⏱️ Session duration:', SESSION_DURATION, 'seconds');
setCookie(event, 'user_session', JSON.stringify(sessionData), {
httpOnly: true,
// CRITICAL: Must be TRUE when operating over HTTPS (deployed)
secure: isSecure,
// Ensures cookie is sent on cross-site redirects (Keycloak -> Your App)
sameSite: 'lax',
maxAge: tokens.expires_in,
// CHANGED: Use custom session duration (7 days default)
maxAge: SESSION_DURATION,
path: '/',
});
console.log('✅ Session cookie created successfully');
// Note: The following line will still log false because the cookie
// is in the response header, not the request header yet. This is expected.
const testCookie = getCookie(event, 'user_session');
console.log('🧪 Cookie test - can read back in this handler (Expected False):', !!testCookie);