forked from TomDoesTech/Testing-Express-REST-API
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdeserializeUser.ts
More file actions
45 lines (34 loc) · 989 Bytes
/
Copy pathdeserializeUser.ts
File metadata and controls
45 lines (34 loc) · 989 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
33
34
35
36
37
38
39
40
41
42
43
44
45
import { get } from "lodash";
import { Request, Response, NextFunction } from "express";
import { verifyJwt } from "../utils/jwt.utils";
import { reIssueAccessToken } from "../service/session.service";
const deserializeUser = async (
req: Request,
res: Response,
next: NextFunction
) => {
const accessToken = get(req, "headers.authorization", "").replace(
/^Bearer\s/,
""
);
const refreshToken = get(req, "headers.x-refresh");
if (!accessToken) {
return next();
}
const { decoded, expired } = verifyJwt(accessToken);
if (decoded) {
res.locals.user = decoded;
return next();
}
if (expired && refreshToken) {
const newAccessToken = await reIssueAccessToken({ refreshToken });
if (newAccessToken) {
res.setHeader("x-access-token", newAccessToken);
}
const result = verifyJwt(newAccessToken as string);
res.locals.user = result.decoded;
return next();
}
return next();
};
export default deserializeUser;