-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauthentication.ts
More file actions
32 lines (25 loc) · 895 Bytes
/
authentication.ts
File metadata and controls
32 lines (25 loc) · 895 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import jwt from 'jsonwebtoken';
import type { NextFunction, Request, Response } from 'express';
import type { AuthJwtPayload } from '../types/express/index.js';
import { UnauthorizedError } from '../utils/AppError.js';
export const requireAuth = (
req: Request,
_res: Response,
next: NextFunction,
) => {
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith('Bearer ')) {
throw new UnauthorizedError('No token provided or wrong format.');
}
const token = authHeader.split(' ')[1];
if (!token) {
throw new UnauthorizedError('No token provided.');
}
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET!, (err, decodedToken) => {
if (err || !decodedToken || typeof decodedToken === 'string') {
throw new UnauthorizedError('Invalid token.');
}
req.user = decodedToken as AuthJwtPayload;
});
return next();
};