port-nimara-client-portal/server/utils/auth.ts

51 lines
1.8 KiB
TypeScript
Raw Normal View History

/**
* Check if the request is authenticated via either:
* 1. x-tag header (for webhooks/external calls)
* 2. Keycloak session (for logged-in users)
*/
export const isAuthenticated = async (event: any): Promise<boolean> => {
// Check x-tag header authentication (existing method)
const xTagHeader = getRequestHeader(event, "x-tag");
if (xTagHeader && (xTagHeader === "094ut234" || xTagHeader === "pjnvü1230")) {
console.log('[auth] Authenticated via x-tag header');
return true;
}
// Check Keycloak session authentication
try {
const keycloakSession = getCookie(event, 'keycloak-session');
if (keycloakSession) {
console.log('[auth] Authenticated via Keycloak session');
return true;
}
} catch (error) {
console.log('[auth] Keycloak session check failed:', error);
}
console.log('[auth] No valid authentication found');
return false;
}
export const requireAuth = async (event: any) => {
const authenticated = await isAuthenticated(event);
if (!authenticated) {
console.log('[requireAuth] Authentication failed for:', event.node.req.url);
console.log('[requireAuth] Available headers:', Object.keys(event.node.req.headers));
console.log('[requireAuth] Available cookies:', Object.keys(event.node.req.headers.cookie ? parseCookies(event.node.req.headers.cookie) : {}));
throw createError({
statusCode: 401,
statusMessage: "Authentication required. Please provide x-tag header or valid session."
});
}
}
function parseCookies(cookieString: string): Record<string, string> {
return cookieString.split(';').reduce((cookies: Record<string, string>, cookie) => {
const [name, value] = cookie.trim().split('=');
if (name && value) {
cookies[name] = value;
}
return cookies;
}, {});
}