-
Notifications
You must be signed in to change notification settings - Fork 3
/
policy-middleware.ts
67 lines (62 loc) · 2.16 KB
/
policy-middleware.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
57
58
59
60
61
62
63
64
65
66
67
/**
* SudoSOS back-end API service.
* Copyright (C) 2024 Study association GEWIS
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { RequestHandler, Response } from 'express';
import { PolicyImplementation } from '../controller/policy';
import { RequestWithToken } from './token-middleware';
/**
* This class is responsible for:
* - enforcing a given policy implementation as middleware.
*/
export default class PolicyMiddleware {
/**
* A reference to the policy to be used by this middleware instance.
*/
private readonly policy: PolicyImplementation;
/**
* Creates a new policy middleware instance.
* @param policy - the policy to be used by this middleware.
*/
public constructor(policy: PolicyImplementation) {
this.policy = policy;
}
/**
* Middleware handler for enforcing the policy.
* @param req - the express request to handle.
* @param res - the express response object.
* @param next - the express next function to continue processing of the request.
*/
public async handle(req: RequestWithToken, res: Response, next: Function): Promise<void> {
try {
if (await this.policy(req)) {
next();
return;
}
res.status(403).end('You have insufficient permissions for the requested action.');
return;
} catch (e) {
console.error(e);
res.status(500).json('Internal server error.');
}
}
/**
* @returns a middleware handler to be used by express.
*/
public getMiddleware(): RequestHandler {
return this.handle.bind(this);
}
}