This repository has been archived by the owner on Feb 11, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.ts
56 lines (54 loc) · 1.52 KB
/
auth.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import { Request, Response, NextFunction } from 'express';
import mongoose from 'mongoose';
import { logger } from './logger';
import { AuthModel, UserModel } from '../models';
import {
getTokenFromRequest,
checkToken,
getUserIdFromToken,
checkAuth,
checkPermission,
} from '../utils';
export const getAuthMiddleware =
(param?: number | number[] | ((user: IUserDocument) => boolean)) =>
async (request: Request, response: Response, next: NextFunction) => {
const token = getTokenFromRequest(request);
if (!checkToken(token)) {
next({
status: 403,
message: 'Please sign in first.',
});
return;
}
try {
const userId = getUserIdFromToken(token);
const auth = await AuthModel.findOne({ userId: new mongoose.Types.ObjectId(userId), token });
if (!checkAuth(auth)) {
next({
status: 403,
message: 'Please sign in first.',
});
return;
}
const user = await UserModel.findById(userId);
if (!checkPermission(user, param)) {
next({
status: 401,
message: 'Access denied. Do you have the access?',
});
return;
}
request.body.user = user;
next();
return;
} catch (error) {
// https://github.com/auth0/node-jsonwebtoken#errors--codes
// @ts-ignore
logger.error(error?.message ?? error ?? '');
next({
status: 403,
message: `Please sign in first.`,
});
}
};
export const authMiddleware = getAuthMiddleware();