37 lines
1.4 KiB
TypeScript
37 lines
1.4 KiB
TypeScript
// server/utils/auth.ts
|
|
import type { H3Event } from 'h3';
|
|
|
|
if (!process.env.SESSION_PASSWORD) {
|
|
// Fail-fast if the session password is not configured
|
|
throw new Error('FATAL ERROR: SESSION_PASSWORD environment variable is not set. Session management will not work securely.');
|
|
}
|
|
|
|
/**
|
|
* Gets the user ID from the event context.
|
|
* The `server/middleware/auth.ts` middleware is responsible for populating `event.context.user`.
|
|
* Throws a 401 Unauthorized error if no user is found in the context.
|
|
* @param event The H3 event object.
|
|
* @returns The user's ID.
|
|
*/
|
|
export function getAuthenticatedUserId(event: H3Event): number {
|
|
const user = event.context.user;
|
|
if (!user || typeof user.id !== 'number') {
|
|
throw createError({ statusCode: 401, statusMessage: 'Unauthorized' });
|
|
}
|
|
return user.id;
|
|
}
|
|
|
|
|
|
/**
|
|
* @deprecated Use `getAuthenticatedUserId(event)` instead. This function relies on the old session-only check and is not compatible with anonymous sessions.
|
|
* A helper function to safely get the authenticated user's ID from the session.
|
|
* Throws a 401 Unauthorized error if the user is not authenticated.
|
|
*/
|
|
export async function getUserIdFromSession(event: H3Event): Promise<number> {
|
|
const user = event.context.user;
|
|
if (!user || typeof user.id !== 'number' || user.isAnonymous) {
|
|
throw createError({ statusCode: 401, statusMessage: 'Unauthorized' });
|
|
}
|
|
return user.id;
|
|
}
|