habits.andr33v.ru/server/middleware/auth.ts

43 lines
1.4 KiB
TypeScript

// server/middleware/auth.ts
import { defineEventHandler, useSession } from 'h3';
import prisma from '../utils/prisma';
/**
* Global server middleware to populate `event.context.user` for every incoming request.
*
* It safely checks for a session and fetches the user from the database if a
* valid session ID is found. It does NOT block requests or throw errors if the
* user is not authenticated, as authorization is handled within API endpoints themselves.
*/
export default defineEventHandler(async (event) => {
// This middleware should not run on static assets or internal requests.
const path = event.path || '';
if (path.startsWith('/_nuxt') || path.startsWith('/__nuxt_error')) {
return;
}
// Safely get the session
const session = await useSession(event, {
password: process.env.SESSION_PASSWORD!,
});
const userId = session.data?.user?.id;
// If a userId is found in the session, fetch the user and attach it to the context.
if (userId) {
try {
const user = await prisma.user.findUnique({
where: { id: userId },
});
if (user) {
event.context.user = user;
}
} catch (error) {
// If there's an error fetching the user (e.g., DB connection issue),
// we log it but don't block the request. The user will be treated as unauthenticated.
console.error('Error fetching user in auth middleware:', error);
}
}
});