blob: 19de4d8c1409d093a0fcaccc70a7464ecdcc4d64 (
plain) (
blame)
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
|
import { validateJwtToken } from '#util/jwtUtils.js';
import { DbUser, UserType } from '#db/schemas/index.js';
/**
* @param options {AuthValidationOptions}
* @returns {(function(*, *, *): void)|*}
*/
export function validateAuth(options) {
return async function (req, res, next) {
const auth = (req.auth = validateJwtToken(req.headers.authorization));
if (!auth) {
res.status(401).send('Unauthorized');
return;
}
const user = (req.user = await DbUser.findById(auth.id).exec());
// admin can do everything
if (user.type == UserType.ADMIN) {
next();
return;
}
if (options.roles && !options.roles.includes(user.type)) {
res.status(401).send('Unauthorized');
return;
}
next();
};
}
export const requireUser = validateAuth({ roles: [UserType.USER] });
export const requireMonitor = validateAuth({ roles: [UserType.MONITOR] });
export const requireAdmin = validateAuth({ roles: [UserType.ADMIN] });
class AuthValidationOptions {
roles;
}
|