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