blob: 3a71e45d47c8e8e8bc837b09ee3c4dd2c46f7220 (
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
40
41
42
43
|
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 requireAuth = validateAuth({});
export const requireAdmin = validateAuth({ roles: [UserType.ADMIN] });
export const requireMonitor = validateAuth({ roles: [UserType.MONITOR] });
export const requireUser = validateAuth({ roles: [UserType.USER] });
export const requireUserOrMonitor = validateAuth({
roles: [UserType.USER, UserType.MONITOR]
});
class AuthValidationOptions {
roles;
}
|