Spaces:
Build error
Build error
| import type { FastifyRequest, FastifyReply, FastifyInstance } from 'fastify'; | |
| import { getSessionUser } from './session.js'; | |
| import { userRepository } from '@core/storage/repositories/users.js'; | |
| declare module 'fastify' { | |
| interface FastifyRequest { | |
| user?: { | |
| id: string; | |
| username: string; | |
| isAdmin: boolean; | |
| isBanned: boolean; | |
| }; | |
| sessionId?: string; | |
| } | |
| } | |
| export async function authMiddleware(request: FastifyRequest, reply: FastifyReply): Promise<void> { | |
| const sessionId = request.cookies?.session_id; | |
| if (!sessionId) return; | |
| request.sessionId = sessionId; | |
| const user = await getSessionUser(sessionId); | |
| if (user) { | |
| request.user = user; | |
| } | |
| } | |
| export async function requireAuth(request: FastifyRequest, reply: FastifyReply): Promise<void> { | |
| if (!request.user) { | |
| return reply.status(401).send({ error: 'Authentication required' }); | |
| } | |
| } | |
| export async function requireAdmin(request: FastifyRequest, reply: FastifyReply): Promise<void> { | |
| if (!request.user) { | |
| return reply.status(401).send({ error: 'Authentication required' }); | |
| } | |
| if (!request.user.isAdmin) { | |
| return reply.status(403).send({ error: 'Admin access required' }); | |
| } | |
| } | |
| export async function optionalAuth(request: FastifyRequest, reply: FastifyReply): Promise<void> { | |
| const sessionId = request.cookies?.session_id; | |
| if (!sessionId) return; | |
| request.sessionId = sessionId; | |
| const user = await getSessionUser(sessionId); | |
| if (user) { | |
| request.user = user; | |
| } | |
| } | |
| export async function checkBanned(request: FastifyRequest, reply: FastifyReply): Promise<void> { | |
| if (request.user?.isBanned) { | |
| const user = await userRepository.findById(request.user.id); | |
| return reply.status(403).send({ | |
| error: 'Account banned', | |
| reason: user?.banReason, | |
| }); | |
| } | |
| } | |
| export function setupAuthHooks(app: FastifyInstance): void { | |
| app.addHook('preHandler', authMiddleware); | |
| } |