blob: ee102182b6d0c96c0185b0f95b91235763e3fcf3 (
plain)
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
33
34
|
import { Request, Response, NextFunction } from "express";
import jwt from "jsonwebtoken";
const authenticate = () => (req: Request, res: Response, next: NextFunction) => {
const authHeader = req.headers.authorization;
const token = authHeader && authHeader.split(" ")[1];
if (!token) res.status(401).json({ error: "Unauthorized" });
// @ts-ignore
jwt.verify(token as string, process.env.ACCESS_TOKEN_SECRET, (err, claims) => {
if (err) {
// @ts-ignore
switch (err.message) {
case "jwt expired":
res.status(401).json({ error: "Token Expired" });
break;
case "invalid signature":
res.status(401).json({ error: "Invalid Credentials" });
break;
default:
res.status(500).json({ error: "Internal Server Error" });
console.error(err)
break;
}
} else {
// @ts-ignore
req.userId = claims.userId;
next();
}
});
}
export default authenticate;
|