try refactor auth

This commit is contained in:
overcuriousity
2025-07-24 00:26:01 +02:00
parent 0ac31484d5
commit 32fca8a06f
10 changed files with 236 additions and 135 deletions

View File

@@ -2,6 +2,8 @@
import { SignJWT, jwtVerify, type JWTPayload } from 'jose';
import { serialize, parse } from 'cookie';
import { config } from 'dotenv';
import type { AstroGlobal, APIRoute } from 'astro';
// Load environment variables
config();
@@ -196,4 +198,144 @@ export function logAuthEvent(event: string, details?: any) {
export function getUserEmail(userInfo: UserInfo): string {
return userInfo.email ||
`${userInfo.preferred_username || userInfo.sub || 'unknown'}@cc24.dev`;
}
// === CONSOLIDATION: Server-side Auth Helpers ===
export interface AuthContext {
authenticated: boolean;
session: SessionData | null;
userEmail: string;
userId: string;
}
/**
* Consolidated auth check for Astro pages
* Replaces repeated auth patterns in contribute pages
*/
export async function withAuth(Astro: AstroGlobal): Promise<AuthContext | Response> {
const authRequired = process.env.AUTHENTICATION_NECESSARY !== 'false';
// If auth not required, return mock context
if (!authRequired) {
return {
authenticated: true,
session: null,
userEmail: 'anonymous@example.com',
userId: 'anonymous'
};
}
// Check session
const sessionToken = getSessionFromRequest(Astro.request);
if (!sessionToken) {
const loginUrl = `/api/auth/login?returnTo=${encodeURIComponent(Astro.url.toString())}`;
return new Response(null, {
status: 302,
headers: { 'Location': loginUrl }
});
}
const session = await verifySession(sessionToken);
if (!session) {
const loginUrl = `/api/auth/login?returnTo=${encodeURIComponent(Astro.url.toString())}`;
return new Response(null, {
status: 302,
headers: { 'Location': loginUrl }
});
}
return {
authenticated: true,
session,
userEmail: session.email,
userId: session.userId
};
}
/**
* Consolidated auth check for API endpoints
* Replaces repeated auth patterns in API routes
*/
export async function withAPIAuth(request: Request): Promise<{ authenticated: boolean; userId: string; session?: SessionData }> {
const authRequired = process.env.AUTHENTICATION_NECESSARY !== 'false';
if (!authRequired) {
return {
authenticated: true,
userId: 'anonymous'
};
}
const sessionToken = getSessionFromRequest(request);
if (!sessionToken) {
return { authenticated: false, userId: '' };
}
const session = await verifySession(sessionToken);
if (!session) {
return { authenticated: false, userId: '' };
}
return {
authenticated: true,
userId: session.userId,
session
};
}
/**
* Helper to create consistent API auth error responses
*/
export function createAuthErrorResponse(message: string = 'Authentication required'): Response {
return new Response(JSON.stringify({ error: message }), {
status: 401,
headers: { 'Content-Type': 'application/json' }
});
}
async function checkClientAuth() {
try {
const response = await fetch('/api/auth/status');
const data = await response.json();
return {
authenticated: data.authenticated,
authRequired: data.authRequired,
expires: data.expires
};
} catch (error) {
console.error('Auth check failed:', error);
return {
authenticated: false,
authRequired: true
};
}
}
/**
* Redirect to login if not authenticated, otherwise execute callback
*/
export async function requireClientAuth(callback, returnUrl) {
const authStatus = await checkClientAuth();
if (authStatus.authRequired && !authStatus.authenticated) {
const targetUrl = returnUrl || window.location.href;
window.location.href = `/api/auth/login?returnTo=${encodeURIComponent(targetUrl)}`;
} else {
callback();
}
}
/**
* Show/hide element based on authentication
*/
export async function showIfAuthenticated(selector) {
const authStatus = await checkClientAuth();
const element = document.querySelector(selector);
if (element) {
element.style.display = (!authStatus.authRequired || authStatus.authenticated)
? 'inline-flex'
: 'none';
}
}

55
src/utils/client-auth.ts Normal file
View File

@@ -0,0 +1,55 @@
// src/scripts/client-auth.js - Client-side auth utilities
/**
* Consolidated client-side auth status check
*/
async function checkClientAuth() {
try {
const response = await fetch('/api/auth/status');
const data = await response.json();
return {
authenticated: data.authenticated,
authRequired: data.authRequired,
expires: data.expires
};
} catch (error) {
console.error('Auth check failed:', error);
return {
authenticated: false,
authRequired: true
};
}
}
/**
* Redirect to login if not authenticated, otherwise execute callback
*/
async function requireClientAuth(callback, returnUrl) {
const authStatus = await checkClientAuth();
if (authStatus.authRequired && !authStatus.authenticated) {
const targetUrl = returnUrl || window.location.href;
window.location.href = `/api/auth/login?returnTo=${encodeURIComponent(targetUrl)}`;
} else {
callback();
}
}
/**
* Show/hide element based on authentication
*/
async function showIfAuthenticated(selector) {
const authStatus = await checkClientAuth();
const element = document.querySelector(selector);
if (element) {
element.style.display = (!authStatus.authRequired || authStatus.authenticated)
? 'inline-flex'
: 'none';
}
}
// Make functions available globally
window.checkClientAuth = checkClientAuth;
window.requireClientAuth = requireClientAuth;
window.showIfAuthenticated = showIfAuthenticated;

View File

@@ -1,40 +0,0 @@
import type { AstroGlobal } from 'astro';
import { getSessionFromRequest, verifySession, type SessionData } from './auth.js';
export interface AuthContext {
authenticated: boolean;
session: SessionData | null;
}
// Check authentication status for server-side pages
export async function getAuthContext(Astro: AstroGlobal): Promise<AuthContext> {
try {
const sessionToken = getSessionFromRequest(Astro.request);
if (!sessionToken) {
return { authenticated: false, session: null };
}
const session = await verifySession(sessionToken);
return {
authenticated: session !== null,
session
};
} catch (error) {
console.error('Failed to get auth context:', error);
return { authenticated: false, session: null };
}
}
// Redirect to login if not authenticated
export function requireAuth(authContext: AuthContext, currentUrl: string): Response | null {
if (!authContext.authenticated) {
const loginUrl = `/api/auth/login?returnTo=${encodeURIComponent(currentUrl)}`;
return new Response(null, {
status: 302,
headers: { 'Location': loginUrl }
});
}
return null;
}