23 lines
814 B
TypeScript
23 lines
814 B
TypeScript
// server/utils/auth.ts
|
|
import { useSession } 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.');
|
|
}
|
|
|
|
/**
|
|
* 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: any): Promise<number> {
|
|
const session = await useSession(event, {
|
|
password: process.env.SESSION_PASSWORD, // No fallback here, rely on the fail-fast check
|
|
});
|
|
const userId = session.data?.user?.id;
|
|
if (!userId) {
|
|
throw createError({ statusCode: 401, statusMessage: 'Unauthorized' });
|
|
}
|
|
return userId;
|
|
}
|