| 1 | import type { FastifyRequest, FastifyReply } from "fastify"; |
| 2 | |
| 3 | /** |
| 4 | * Auth middleware — verifies JWT and attaches user to request |
| 5 | */ |
| 6 | export async function authenticate( |
| 7 | request: FastifyRequest, |
| 8 | reply: FastifyReply |
| 9 | ) { |
| 10 | try { |
| 11 | await request.jwtVerify(); |
| 12 | } catch { |
| 13 | reply.code(401).send({ error: "Unauthorized" }); |
| 14 | } |
| 15 | } |
| 16 | |
| 17 | /** |
| 18 | * Optional auth — attaches user if present, but doesn't reject |
| 19 | */ |
| 20 | export async function optionalAuth( |
| 21 | request: FastifyRequest, |
| 22 | _reply: FastifyReply |
| 23 | ) { |
| 24 | try { |
| 25 | await request.jwtVerify(); |
| 26 | } catch { |
| 27 | // Not authenticated, but that's OK for public routes |
| 28 | } |
| 29 | } |
| 30 | |