| 1 | import { HttpError, USER_ID_HEADER, z } from '@chatapp/common'; |
| 2 | import type { RequestHandler } from 'express'; |
| 3 | |
| 4 | const userIdSchema = z.string().uuid(); |
| 5 | |
| 6 | export const attachAuthenticatedUser: RequestHandler = (req, _res, next) => { |
| 7 | try { |
| 8 | const headerValue = req.header(USER_ID_HEADER); |
| 9 | const userId = userIdSchema.parse(headerValue); |
| 10 | req.user = { id: userId }; |
| 11 | next(); |
| 12 | } catch { |
| 13 | next(new HttpError(401, 'Invalid or missing user context')); |
| 14 | } |
| 15 | }; |