require-auth.ts52 lines, 1.2 KB
| 1 | import { HttpError, type AuthenticatedUser } from '@chatapp/common'; |
| 2 | import jwt from 'jsonwebtoken'; |
| 3 | |
| 4 | import type { RequestHandler } from 'express'; |
| 5 | |
| 6 | import { env } from '@/config/env'; |
| 7 | |
| 8 | interface AccessTokenClaims { |
| 9 | sub: string; |
| 10 | email?: string; |
| 11 | } |
| 12 | |
| 13 | const parseAuthorizationHeader = (value: string | undefined): string => { |
| 14 | if (!value) { |
| 15 | throw new HttpError(401, 'Unauthorized'); |
| 16 | } |
| 17 | |
| 18 | const [scheme, token] = value.split(' '); |
| 19 | |
| 20 | if (scheme.toLowerCase() !== 'bearer' || !token) { |
| 21 | throw new HttpError(401, 'Unauthorized'); |
| 22 | } |
| 23 | |
| 24 | return token; |
| 25 | }; |
| 26 | |
| 27 | const toAuthenticatedUser = (claims: AccessTokenClaims): AuthenticatedUser => { |
| 28 | if (!claims.sub) { |
| 29 | throw new HttpError(401, 'Unauthorized'); |
| 30 | } |
| 31 | |
| 32 | return { |
| 33 | id: claims.sub, |
| 34 | email: claims.email, |
| 35 | }; |
| 36 | }; |
| 37 | |
| 38 | export const requireAuth: RequestHandler = (req, _res, next) => { |
| 39 | try { |
| 40 | const token = parseAuthorizationHeader(req.headers.authorization); |
| 41 | const claims = jwt.verify(token, env.JWT_SECRET) as AccessTokenClaims; |
| 42 | req.user = toAuthenticatedUser(claims); |
| 43 | next(); |
| 44 | } catch (error) { |
| 45 | if (error instanceof HttpError) { |
| 46 | next(error); |
| 47 | return; |
| 48 | } |
| 49 | |
| 50 | next(new HttpError(401, 'Unauthorized')); |
| 51 | } |
| 52 | }; |