-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathrole.guard.ts
More file actions
34 lines (29 loc) · 1.18 KB
/
role.guard.ts
File metadata and controls
34 lines (29 loc) · 1.18 KB
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
import { Request } from 'express';
import { decodeAuthToken } from './guards.utils';
import { Role } from '../auth.constants';
/**
* A utility function to check if the required user role are present
* in the authorization token provided in the request headers.
*
* @param {...Role[]} requiredUserRoles - The list of required user roles to validate against.
* @returns {Promise<(req: Request) => boolean>} A function that takes an Express `Request` object
* and returns a boolean indicating whether the required scopes are present.
*
* The function decodes the authorization token from the request headers and checks if
* the required user roles are included in the token's scope claim.
*/
export const checkHasUserRole =
(...requiredUserRoles: Role[]) =>
async (req: Request) => {
const decodedAuth = await decodeAuthToken(req.headers.authorization ?? '');
const decodedUserRoles = Object.keys(decodedAuth).reduce((roles, key) => {
if (key.match(/claims\/roles$/gi)) {
return decodedAuth[key] as string[];
}
return roles;
}, []);
if (!requiredUserRoles.some((role) => decodedUserRoles.includes(role))) {
return false;
}
return true;
};