Skip to content
This repository was archived by the owner on Sep 4, 2024. It is now read-only.

Commit effbdcf

Browse files
Refactored auth middleware
1 parent 9cd3f7e commit effbdcf

File tree

1 file changed

+8
-13
lines changed

1 file changed

+8
-13
lines changed

middleware/auth.ts

Lines changed: 8 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,39 +1,34 @@
11
import jwt from '../lib/jwt'
22
import { AuthenticationError } from '../lib/errors'
3-
import User from '../models/user'
43
import { NextFunction, Request, Response } from 'express';
5-
import UserAuthToken from '../models/user_auth_token';
4+
import { checkUserForAuthToken, getUserByID, User } from '../models/users';
65

76
export default async function AuthMiddleware(req: Request, res: Response, next: NextFunction) {
87
let header = req.get('Authorization') as string;
98
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'));
1210
}
1311

1412

1513
// Extract user ID from bearer token
1614
let token = (/^Bearer (.+)$/i.exec(header) as string[])[1].trim();
1715
let id = jwt.verifyAccessToken(token);
1816
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'));
2118
}
2219

2320

2421
// Get the user
2522
let user: User | undefined;
2623
try {
27-
user = await User.findOne({ where: { id } });
28-
24+
user = await getUserByID(id);
2925
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.');
3329
}
3430
} 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));
3732
}
3833

3934
// Pass the user object to the request and execute subsequent requests

0 commit comments

Comments
 (0)