-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
336 lines (291 loc) · 10.4 KB
/
index.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
import AuthenticationProvider from './src/services/AuthenticationProvider.js';
import PermissionParser from './src/services/PermissionParser.js';
import parseOptions from './src/util/parseOptions.js';
import responseError from './src/util/responseError.js';
import type { Request, Response, NextFunction } from 'express';
import type Options from './src/interfaces/Options.js';
import type RequestMethods from './src/interfaces/RequestMethods.js';
import type Permission from './src/interfaces/Permission.js';
import type Role from './src/interfaces/Role.js';
import type Nullable from './src/interfaces/Nullable.js';
import requestKind from './src/util/requestKind.js';
/**
* Internal type of the `Express.Request` interface, used to augment the
* interface with the `authZ` property to allow the property to be
* set on the global middleware
*/
type InternalRequest = {
/**
* AuthZ permissions handler with optional attribute to allow setting
* the property on the global middleware
*/
authZ?: RequestMethods;
};
/**
* Augment the `Express.Request` interface to include the `authZ` property
*/
declare global {
namespace Express {
interface Request {
/**
* AuthZ permissions handler, will be truthy if the `AuthZ.globalMiddleware`
* middleware has been added on the app request life-cycle using `Express.use`
*/
readonly authZ: RequestMethods;
}
}
}
/**
* `AuthZ` service creator, used to create an instance to be used within a
* express application, allowing `JWT` authentication and complex authorization
* handling
*/
export default function AuthZ<TUserIdentifier = string>(
options: Options<TUserIdentifier>
) {
/**
* Parsed options, with default values for missing properties
*/
const _options = parseOptions(options);
const authenticationRequestKind = requestKind(
_options.authentication.method,
_options.authentication.path
);
const iamEndpointRequestKind =
options.authorization.iamEndpoint !== null &&
_options.authorization.iamEndpoint
? requestKind(
_options.authorization.iamEndpoint.method,
_options.authorization.iamEndpoint.path
)
: null;
/**
* Global middleware to be used on the express application, it will
* handle the `JWT` authentication, set the `Request.authZ` property
* and allow the use of route-specific middlewares
*/
async function middleware(
request: Request,
response: Response,
next: NextFunction
): Promise<void> {
/**
* Authentication provider, used to authenticate and validate the
* `JWT` token within the application.
*/
const authProvider = AuthenticationProvider(
_options,
request,
response
);
/**
* Request kind, used to identify the request and apply the correct
*/
const kind = requestKind(request.method, request.path);
/**
* If the request is an authentication request, the authentication is performed
* and the flow is stopped
*/
if (kind === authenticationRequestKind) {
await authProvider.authenticate();
return;
}
let userId: TUserIdentifier;
/**
* Validate the `JWT` token, and get the user identifier from the
* token payload
*/
try {
userId = authProvider.validate();
} catch (err) {
response
.status(401)
.json(
responseError(
'Authentication error: ' + (err as Error).message
)
);
return;
}
/**
* Get the roles of the user, based on the user identifier.
* It is a responsibility of the application to provide the
* correct roles
*/
const roles = await _options.authorization.rolesProvider(userId);
/**
* Parse the roles into a `Permission` array, to be used by the
* `Request.authZ` property
*/
const permissionParser = PermissionParser(roles);
/**
* Parsed `Permission` array, to be used by the `Request.authZ`
*/
const permissions = permissionParser.unwrap();
if (iamEndpointRequestKind && kind === iamEndpointRequestKind) {
response.json({
userId,
roles,
permissions
});
return;
}
/**
* Set the `Request.authZ` property, containing the authorization methods
*/
(request as InternalRequest).authZ = {
getPermissions() {
return structuredClone(permissions);
},
getGlobalPermissions() {
return structuredClone(
permissions.filter(
permission => permission.context === 'global'
)
);
},
getLocalPermissions() {
return structuredClone(
permissions.filter(
permission => permission.context === 'local'
)
);
},
getRoles() {
return structuredClone(roles);
},
getPermissionContext(permission: string) {
return permissionParser.checkContext(permission);
},
hasPermissions(...permissions) {
return permissions.every(permissionParser.check);
},
hasGlobalPermissions(...globalPermissions) {
return globalPermissions.every(permissionParser.checkGlobal);
},
hasLocalPermissions(...localPermissions) {
return localPermissions.every(permissionParser.checkLocal);
},
hasActions(...permissionActions) {
return permissionActions.every(permissionParser.checkAction);
},
hasGlobalActions(...globalPermissionActions) {
return globalPermissionActions.every(
permissionParser.checkActionGlobal
);
},
hasLocalActions(...localPermissionActions) {
return localPermissionActions.every(
permissionParser.checkActionLocal
);
},
getUserIdentifier<TUserIdentifier = unknown>() {
return userId as unknown as TUserIdentifier;
}
};
next();
}
/**
* Middleware Factory factory, used to create a middleware factory with
* a certain filter applied to the permissions, such as context (`local` or `global`)
* or search type (`full` or `action`)
*/
function _withPermissions(
contextType: Nullable<Permission['context']> = null,
type: 'full' | 'action' = 'full'
) {
/**
* Checker function factory, used to load the correct
* checker function based on the type and context
*/
function getChecker(authZ: Request['authZ']) {
if (type === 'full') {
if (contextType) {
return contextType === 'global'
? authZ.hasGlobalPermissions
: authZ.hasLocalPermissions;
}
return authZ.hasPermissions;
}
if (type === 'action') {
if (contextType) {
return contextType === 'global'
? authZ.hasGlobalActions
: authZ.hasLocalActions;
}
return authZ.hasActions;
}
return () => false;
}
/**
* Middleware factory, used to create a middleware that will check
* based on the parameters provided to the middleware factory factory
*/
function middlewareFactory(...permissions: string[]) {
function middleware(
request: Request,
response: Response,
next: NextFunction
) {
/**
* Checker function, used to check if the user has the specified
* permissions
*/
const permissionChecker = getChecker(request.authZ);
const allowed = permissionChecker(...permissions);
if (!allowed) {
response
.status(403)
.json(
responseError(
`You don't have permissions to access this resource.`
)
);
return;
}
next();
}
return middleware;
}
return middlewareFactory;
}
/**
* `AuthZ` instance, containing the global middleware and the middleware factories
* for specific routes.
*/
const instance = {
/**
* Global middleware, to create authentication and authorization on the application. **REQUIRED**
*/
middleware,
/**
* Middleware to check if the user has the specified permissions on a route
*/
withPermissions: _withPermissions(),
/**
* Middleware to check if the user has the specified global permissions on a route
*/
withGlobalPermissions: _withPermissions('global'),
/**
* Middleware to check if the user has the specified local permissions on a route
*/
withLocalPermissions: _withPermissions('local'),
/**
* Middleware to check if the user has the specified permission actions on a route
*/
withActions: _withPermissions(null, 'action'),
/**
* Middleware to check if the user has the specified global permission actions on a route
*/
withGlobalActions: _withPermissions('global', 'action'),
/**
* Middleware to check if the user has the specified local permission actions on a route
*/
withLocalActions: _withPermissions('local', 'action')
};
return instance;
}
/**
* Public interfaces exported by the library
*/
export { Options, Permission, Role, RequestMethods };