blob: 4ee0806235a5064ba5f7b248025099ca378ba6fe (
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
35
36
|
import { NextFunction, Request, Response } from "express";
import jwt from "jsonwebtoken";
import type { AuthorizedUser } from "../types/user.js";
async function authenticateUser(
req: Request,
res: Response,
next: NextFunction
) {
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith("Bearer ")) {
return res.status(401).json({
message: "User authentication failed.",
});
}
const token = authHeader.split(" ")[1];
try {
const authorizedUser = jwt.verify(
token,
process.env.JWT_SECRET!
) as AuthorizedUser;
req.user = authorizedUser;
next();
} catch (error) {
console.error("User authentication failed: ", error);
return res.status(403).json({
message: "User authentication failed.",
});
}
}
export default authenticateUser;
|