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