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

Commit 0f50d39

Browse files
Refactored auth middleware
1 parent 43b796e commit 0f50d39

File tree

1 file changed

+6
-8
lines changed

1 file changed

+6
-8
lines changed

middleware/auth.ts

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,32 @@
11
import jwt from '../lib/jwt'
22
import { AuthenticationError } from '../lib/errors'
33
import { NextFunction, Request, Response } from 'express';
4-
import { checkUserForAuthToken, getUserByID, User } from '../models/users';
4+
import Users, { User } from '../models/users';
55

66
export default async function AuthMiddleware(req: Request, res: Response, next: NextFunction) {
77
let header = req.get('Authorization') as string;
88
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.");
1010
}
1111

12-
1312
// Extract user ID from bearer token
1413
let token = (/^Bearer (.+)$/i.exec(header) as string[])[1].trim();
1514
let id = jwt.verifyAccessToken(token);
1615
if (!id) { // Invalid Bearer token
17-
return res.status(401).json(AuthenticationError('User is not Authenticated'));
16+
return AuthenticationError(res, "Bad/Expired token.");
1817
}
1918

20-
2119
// Get the user
2220
let user: User | undefined;
2321
try {
24-
user = await getUserByID(id);
22+
user = await Users.getUserByID(id);
2523
if (user == null) {
2624
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)) {
2826
throw new Error('Bad/Expired auth token.');
2927
}
3028
} catch (e) {
31-
return res.status(401).json(AuthenticationError((e as Error).message));
29+
return AuthenticationError(res, (e as Error).message);
3230
}
3331

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

0 commit comments

Comments
 (0)