|
1 | 1 | import jwt from '../lib/jwt' |
2 | 2 | import { AuthenticationError } from '../lib/errors' |
3 | | -import User from '../models/user' |
4 | 3 | import { NextFunction, Request, Response } from 'express'; |
5 | | -import UserAuthToken from '../models/user_auth_token'; |
| 4 | +import { checkUserForAuthToken, getUserByID, User } from '../models/users'; |
6 | 5 |
|
7 | 6 | export default async function AuthMiddleware(req: Request, res: Response, next: NextFunction) { |
8 | 7 | let header = req.get('Authorization') as string; |
9 | 8 | if (!/^Bearer (.+)$/i.test(header)) { // Bearer token is not present |
10 | | - res.status(401).json(AuthenticationError('User is not Authenticated')); |
11 | | - return; |
| 9 | + return res.status(401).json(AuthenticationError('User is not Authenticated')); |
12 | 10 | } |
13 | 11 |
|
14 | 12 |
|
15 | 13 | // Extract user ID from bearer token |
16 | 14 | let token = (/^Bearer (.+)$/i.exec(header) as string[])[1].trim(); |
17 | 15 | let id = jwt.verifyAccessToken(token); |
18 | 16 | if (!id) { // Invalid Bearer token |
19 | | - res.status(401).json(AuthenticationError('User is not Authenticated')); |
20 | | - return; |
| 17 | + return res.status(401).json(AuthenticationError('User is not Authenticated')); |
21 | 18 | } |
22 | 19 |
|
23 | 20 |
|
24 | 21 | // Get the user |
25 | 22 | let user: User | undefined; |
26 | 23 | try { |
27 | | - user = await User.findOne({ where: { id } }); |
28 | | - |
| 24 | + user = await getUserByID(id); |
29 | 25 | if (user == null) { |
30 | | - throw new Error('User is not Authenticated'); |
31 | | - } else if (await UserAuthToken.count({ where: { user: { id: user.id }, token } }) != 0) { |
32 | | - throw new Error('User is not Authenticated'); |
| 26 | + throw new Error('User is not Authenticated.'); |
| 27 | + } else if (await checkUserForAuthToken(Number(user.id), token)) { |
| 28 | + throw new Error('Bad/Expired auth token.'); |
33 | 29 | } |
34 | 30 | } catch (e) { |
35 | | - res.status(401).json(AuthenticationError((e as Error).message)); |
36 | | - return; |
| 31 | + return res.status(401).json(AuthenticationError((e as Error).message)); |
37 | 32 | } |
38 | 33 |
|
39 | 34 | // Pass the user object to the request and execute subsequent requests |
|
0 commit comments