|
| 1 | +import { randomUUID } from 'crypto'; |
| 2 | +import type { Request, Response, NextFunction } from 'express'; |
1 | 3 | import jwt from 'jsonwebtoken'; |
| 4 | +import { logger, Logger } from 'kv-logger'; |
2 | 5 | import _ from 'lodash'; |
3 | 6 | import moment from 'moment'; |
4 | 7 | import { Op } from 'sequelize'; |
5 | 8 | import { UserTokens } from '../models/user_tokens'; |
6 | | -import { Users } from '../models/users'; |
| 9 | +import { Users, UsersInterface } from '../models/users'; |
7 | 10 | import { AppError, Unauthorized } from './app-error'; |
8 | 11 | import { config } from './config'; |
9 | 12 | import { parseToken, md5 } from './utils/security'; |
10 | 13 |
|
11 | | -function checkAuthToken(authToken) { |
| 14 | +// eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 15 | +export interface Req<P = Record<string, string>, B = any, Q = Record<string, string | string[]>> |
| 16 | + // eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 17 | + extends Request<P, any, B, Q> { |
| 18 | + users: UsersInterface; |
| 19 | + logger: Logger; |
| 20 | +} |
| 21 | + |
| 22 | +// eslint-disable-next-line @typescript-eslint/no-empty-interface, @typescript-eslint/no-explicit-any |
| 23 | +export interface Res<B = any> extends Response<B> {} |
| 24 | + |
| 25 | +/** |
| 26 | + * bind logger to request |
| 27 | + */ |
| 28 | +export function withLogger(req: Req, res: Res, next: NextFunction) { |
| 29 | + const { method, path, headers } = req; |
| 30 | + req.logger = logger.bindContext({ |
| 31 | + path, |
| 32 | + method, |
| 33 | + requestId: headers['x-request-id'] || randomUUID(), |
| 34 | + }); |
| 35 | + next(); |
| 36 | +} |
| 37 | + |
| 38 | +async function checkAuthToken(authToken: string) { |
12 | 39 | const objToken = parseToken(authToken); |
13 | | - return Users.findOne({ |
| 40 | + const users = await Users.findOne({ |
14 | 41 | where: { identical: objToken.identical }, |
15 | | - }) |
16 | | - .then((users) => { |
17 | | - if (_.isEmpty(users)) { |
18 | | - throw new Unauthorized(); |
19 | | - } |
20 | | - return UserTokens.findOne({ |
21 | | - where: { |
22 | | - tokens: authToken, |
23 | | - uid: users.id, |
24 | | - expires_at: { |
25 | | - [Op.gt]: moment().format('YYYY-MM-DD HH:mm:ss'), |
26 | | - }, |
27 | | - }, |
28 | | - }).then((tokenInfo) => { |
29 | | - if (_.isEmpty(tokenInfo)) { |
30 | | - throw new Unauthorized(); |
31 | | - } |
32 | | - return users; |
33 | | - }); |
34 | | - }) |
35 | | - .then((users) => { |
36 | | - return users; |
37 | | - }); |
| 42 | + }); |
| 43 | + if (_.isEmpty(users)) { |
| 44 | + throw new Unauthorized(); |
| 45 | + } |
| 46 | + |
| 47 | + const tokenInfo = await UserTokens.findOne({ |
| 48 | + where: { |
| 49 | + tokens: authToken, |
| 50 | + uid: users.id, |
| 51 | + expires_at: { |
| 52 | + [Op.gt]: moment().format('YYYY-MM-DD HH:mm:ss'), |
| 53 | + }, |
| 54 | + }, |
| 55 | + }); |
| 56 | + if (_.isEmpty(tokenInfo)) { |
| 57 | + throw new Unauthorized(); |
| 58 | + } |
| 59 | + |
| 60 | + return users; |
38 | 61 | } |
39 | 62 |
|
40 | | -function checkAccessToken(accessToken) { |
41 | | - return new Promise((resolve, reject) => { |
42 | | - if (_.isEmpty(accessToken)) { |
43 | | - reject(new Unauthorized()); |
44 | | - return; |
45 | | - } |
46 | | - let authData; |
47 | | - try { |
48 | | - authData = jwt.verify(accessToken, config.jwt.tokenSecret); |
49 | | - } catch (e) { |
50 | | - reject(new Unauthorized()); |
51 | | - return; |
52 | | - } |
53 | | - const uid = _.get(authData, 'uid', null); |
54 | | - const hash = _.get(authData, 'hash', null); |
55 | | - if (parseInt(uid, 10) > 0) { |
56 | | - Users.findOne({ |
57 | | - where: { id: uid }, |
58 | | - }) |
59 | | - .then((users) => { |
60 | | - if (_.isEmpty(users)) { |
61 | | - throw new Unauthorized(); |
62 | | - } |
63 | | - if (!_.eq(hash, md5(users.get('ack_code')))) { |
64 | | - throw new Unauthorized(); |
65 | | - } |
66 | | - resolve(users); |
67 | | - }) |
68 | | - .catch((e) => { |
69 | | - reject(e); |
70 | | - }); |
71 | | - return; |
72 | | - } |
73 | | - reject(new Unauthorized()); |
| 63 | +async function checkAccessToken(accessToken: string) { |
| 64 | + if (_.isEmpty(accessToken)) { |
| 65 | + throw new Unauthorized(); |
| 66 | + } |
| 67 | + |
| 68 | + let authData: { uid: number; hash: string }; |
| 69 | + try { |
| 70 | + authData = jwt.verify(accessToken, config.jwt.tokenSecret) as { |
| 71 | + uid: number; |
| 72 | + hash: string; |
| 73 | + }; |
| 74 | + } catch (e) { |
| 75 | + throw new Unauthorized(); |
| 76 | + } |
| 77 | + |
| 78 | + const { uid, hash } = authData; |
| 79 | + if (uid <= 0) { |
| 80 | + throw new Unauthorized(); |
| 81 | + } |
| 82 | + |
| 83 | + const users = await Users.findOne({ |
| 84 | + where: { id: uid }, |
74 | 85 | }); |
| 86 | + if (_.isEmpty(users)) { |
| 87 | + throw new Unauthorized(); |
| 88 | + } |
| 89 | + |
| 90 | + if (hash !== md5(users.get('ack_code'))) { |
| 91 | + throw new Unauthorized(); |
| 92 | + } |
| 93 | + return users; |
75 | 94 | } |
76 | 95 |
|
77 | | -export function checkToken(req, res, next) { |
78 | | - const authArr = _.split(req.get('Authorization'), ' '); |
79 | | - let authType = 1; |
| 96 | +/** |
| 97 | + * check user token and bind user to request |
| 98 | + */ |
| 99 | +export function checkToken(req: Req, res: Res, next: NextFunction) { |
| 100 | + // get token and type |
| 101 | + let authType: 1 | 2 = 1; |
80 | 102 | let authToken = ''; |
81 | | - if (_.eq(authArr[0], 'Bearer')) { |
| 103 | + const authArr = _.split(req.get('Authorization'), ' '); |
| 104 | + if (authArr[0] === 'Bearer') { |
82 | 105 | [, authToken] = authArr; // Bearer |
83 | 106 | if (authToken && authToken.length > 64) { |
84 | 107 | authType = 2; |
85 | 108 | } else { |
86 | 109 | authType = 1; |
87 | 110 | } |
88 | | - } else if (_.eq(authArr[0], 'Basic')) { |
| 111 | + } else if (authArr[0] === 'Basic') { |
89 | 112 | authType = 2; |
90 | 113 | const b = Buffer.from(authArr[1], 'base64'); |
91 | 114 | const user = _.split(b.toString(), ':'); |
92 | 115 | [, authToken] = user; |
93 | 116 | } |
| 117 | + |
| 118 | + // do check token |
| 119 | + let checkTokenResult: Promise<UsersInterface>; |
94 | 120 | if (authToken && authType === 1) { |
95 | | - checkAuthToken(authToken) |
96 | | - .then((users) => { |
97 | | - req.users = users; |
98 | | - next(); |
99 | | - return users; |
100 | | - }) |
101 | | - .catch((e) => { |
102 | | - if (e instanceof AppError) { |
103 | | - res.status(e.status || 404).send(e.message); |
104 | | - } else { |
105 | | - next(e); |
106 | | - } |
107 | | - }); |
| 121 | + checkTokenResult = checkAuthToken(authToken); |
108 | 122 | } else if (authToken && authType === 2) { |
109 | | - checkAccessToken(authToken) |
110 | | - .then((users) => { |
111 | | - req.users = users; |
112 | | - next(); |
113 | | - return users; |
114 | | - }) |
115 | | - .catch((e) => { |
116 | | - if (e instanceof AppError) { |
117 | | - res.status(e.status || 404).send(e.message); |
118 | | - } else { |
119 | | - next(e); |
120 | | - } |
121 | | - }); |
| 123 | + checkTokenResult = checkAccessToken(authToken); |
122 | 124 | } else { |
123 | 125 | res.send(new Unauthorized(`Auth type not supported.`)); |
| 126 | + return; |
124 | 127 | } |
| 128 | + |
| 129 | + checkTokenResult |
| 130 | + .then((users) => { |
| 131 | + req.users = users; |
| 132 | + next(); |
| 133 | + }) |
| 134 | + .catch((e) => { |
| 135 | + if (e instanceof AppError) { |
| 136 | + res.status(e.status || 404).send(e.message); |
| 137 | + } else { |
| 138 | + next(e); |
| 139 | + } |
| 140 | + }); |
125 | 141 | } |
0 commit comments