@flusys/nestjs-shared 6.1.2 → 6.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/cjs/constants/permissions.js +2 -1
- package/cjs/guards/permission.guard.js +17 -45
- package/cjs/guards/permission.guard.spec.js +37 -22
- package/cjs/modules/index.js +2 -0
- package/cjs/modules/shared-permission-cache/shared-permission-cache.module.js +32 -0
- package/cjs/modules/shared-permission-cache/shared-permission-cache.service.js +101 -0
- package/cjs/modules/shared-permission-cache/shared-permission-cache.service.spec.js +165 -0
- package/constants/permissions.d.ts +2 -0
- package/fesm/constants/permissions.js +2 -1
- package/fesm/guards/permission.guard.js +18 -46
- package/fesm/guards/permission.guard.spec.js +37 -22
- package/fesm/modules/index.js +2 -0
- package/fesm/modules/shared-permission-cache/shared-permission-cache.module.js +22 -0
- package/fesm/modules/shared-permission-cache/shared-permission-cache.service.js +91 -0
- package/fesm/modules/shared-permission-cache/shared-permission-cache.service.spec.js +161 -0
- package/guards/permission.guard.d.ts +3 -7
- package/modules/index.d.ts +2 -0
- package/modules/shared-permission-cache/shared-permission-cache.module.d.ts +2 -0
- package/modules/shared-permission-cache/shared-permission-cache.service.d.ts +14 -0
- package/package.json +2 -2
|
@@ -49,6 +49,7 @@ export declare const FILE_PERMISSIONS: {
|
|
|
49
49
|
readonly READ: "file.read";
|
|
50
50
|
readonly UPDATE: "file.update";
|
|
51
51
|
readonly DELETE: "file.delete";
|
|
52
|
+
readonly VIEW_PRIVATE_ACTION: "file.view.private";
|
|
52
53
|
};
|
|
53
54
|
export declare const FOLDER_PERMISSIONS: {
|
|
54
55
|
readonly CREATE: "folder.create";
|
|
@@ -206,6 +207,7 @@ export declare const PERMISSIONS: {
|
|
|
206
207
|
readonly READ: "file.read";
|
|
207
208
|
readonly UPDATE: "file.update";
|
|
208
209
|
readonly DELETE: "file.delete";
|
|
210
|
+
readonly VIEW_PRIVATE_ACTION: "file.view.private";
|
|
209
211
|
};
|
|
210
212
|
readonly FOLDER: {
|
|
211
213
|
readonly CREATE: "folder.create";
|
|
@@ -51,7 +51,8 @@ export const FILE_PERMISSIONS = {
|
|
|
51
51
|
CREATE: 'file.create',
|
|
52
52
|
READ: 'file.read',
|
|
53
53
|
UPDATE: 'file.update',
|
|
54
|
-
DELETE: 'file.delete'
|
|
54
|
+
DELETE: 'file.delete',
|
|
55
|
+
VIEW_PRIVATE_ACTION: 'file.view.private'
|
|
55
56
|
};
|
|
56
57
|
export const FOLDER_PERMISSIONS = {
|
|
57
58
|
CREATE: 'folder.create',
|
|
@@ -27,11 +27,9 @@ function _ts_param(paramIndex, decorator) {
|
|
|
27
27
|
}
|
|
28
28
|
import { Inject, Injectable, Optional, UnauthorizedException } from '@nestjs/common';
|
|
29
29
|
import { Reflector } from '@nestjs/core';
|
|
30
|
-
import {
|
|
31
|
-
import { AUTH_MESSAGES, CACHE_INSTANCE, IS_PUBLIC_KEY, PERMISSION_GUARD_CONFIG, PERMISSIONS_KEY } from '../constants';
|
|
30
|
+
import { AUTH_MESSAGES, IS_PUBLIC_KEY, PERMISSIONS_KEY } from '../constants';
|
|
32
31
|
import { InsufficientPermissionsException, NoPermissionsFoundException, PermissionSystemUnavailableException } from '../exceptions/permission.exception';
|
|
33
|
-
import {
|
|
34
|
-
import { buildPermissionCacheKey, DEFAULT_COMPANY_PERMISSION_KEY_FORMAT, DEFAULT_USER_PERMISSION_KEY_FORMAT } from '../utils/permission-cache-key.util';
|
|
32
|
+
import { SharedPermissionCacheService } from '../modules/shared-permission-cache/shared-permission-cache.service';
|
|
35
33
|
export class PermissionGuard {
|
|
36
34
|
async canActivate(context) {
|
|
37
35
|
const isPublic = this.reflector.getAllAndOverride(IS_PUBLIC_KEY, [
|
|
@@ -50,16 +48,21 @@ export class PermissionGuard {
|
|
|
50
48
|
message: 'Authentication required',
|
|
51
49
|
messageKey: AUTH_MESSAGES.TOKEN_REQUIRED
|
|
52
50
|
});
|
|
53
|
-
if (!this.
|
|
51
|
+
if (!this.permissionCacheService?.isCacheConfigured()) {
|
|
54
52
|
throw new PermissionSystemUnavailableException();
|
|
55
53
|
}
|
|
56
|
-
const
|
|
54
|
+
const permissionService = this.permissionCacheService;
|
|
55
|
+
const userPermissions = await permissionService.getPermissions({
|
|
56
|
+
userId: user.id,
|
|
57
|
+
companyId: user.companyId,
|
|
58
|
+
branchId: user.branchId
|
|
59
|
+
});
|
|
57
60
|
if (!userPermissions || userPermissions.length === 0) {
|
|
58
61
|
throw new NoPermissionsFoundException();
|
|
59
62
|
}
|
|
60
63
|
const logicNode = this.normalizeToLogicNode(permissionConfig);
|
|
61
64
|
if (!logicNode) return true;
|
|
62
|
-
const result = this.evaluateLogicNode(logicNode, userPermissions);
|
|
65
|
+
const result = this.evaluateLogicNode(logicNode, userPermissions, permissionService);
|
|
63
66
|
if (!result.passed) {
|
|
64
67
|
throw new InsufficientPermissionsException(result.missingPermissions, result.operator);
|
|
65
68
|
}
|
|
@@ -109,9 +112,9 @@ export class PermissionGuard {
|
|
|
109
112
|
// ILogicNode
|
|
110
113
|
return config;
|
|
111
114
|
}
|
|
112
|
-
evaluateLogicNode(node, userPermissions) {
|
|
115
|
+
evaluateLogicNode(node, userPermissions, permissionService) {
|
|
113
116
|
if (node.type === 'action') {
|
|
114
|
-
const passed =
|
|
117
|
+
const passed = permissionService.matchPermission(userPermissions, node.actionId);
|
|
115
118
|
return {
|
|
116
119
|
passed,
|
|
117
120
|
missingPermissions: passed ? [] : [
|
|
@@ -133,7 +136,7 @@ export class PermissionGuard {
|
|
|
133
136
|
const results = [];
|
|
134
137
|
const missingPermissions = [];
|
|
135
138
|
for (const child of children){
|
|
136
|
-
const childResult = this.evaluateLogicNode(child, userPermissions);
|
|
139
|
+
const childResult = this.evaluateLogicNode(child, userPermissions, permissionService);
|
|
137
140
|
results.push(childResult.passed);
|
|
138
141
|
if (!childResult.passed) {
|
|
139
142
|
missingPermissions.push(...childResult.missingPermissions);
|
|
@@ -146,52 +149,21 @@ export class PermissionGuard {
|
|
|
146
149
|
operator
|
|
147
150
|
};
|
|
148
151
|
}
|
|
149
|
-
|
|
150
|
-
if (!this.cache) throw new PermissionSystemUnavailableException();
|
|
151
|
-
const cacheKey = buildPermissionCacheKey({
|
|
152
|
-
userId: user.id,
|
|
153
|
-
companyId: user.companyId,
|
|
154
|
-
branchId: user.branchId
|
|
155
|
-
}, this.config);
|
|
156
|
-
const cached = await this.cache.get(cacheKey);
|
|
157
|
-
if (!cached) return [];
|
|
158
|
-
return Array.isArray(cached) ? cached : cached.backendCodes || [];
|
|
159
|
-
}
|
|
160
|
-
hasPermission(userPermissions, requiredPermission) {
|
|
161
|
-
if (userPermissions.includes(requiredPermission)) return true;
|
|
162
|
-
for (const permission of userPermissions){
|
|
163
|
-
if (permission === '*') return true;
|
|
164
|
-
if (permission.endsWith('.*') && requiredPermission.startsWith(permission.slice(0, -1))) {
|
|
165
|
-
return true;
|
|
166
|
-
}
|
|
167
|
-
}
|
|
168
|
-
return false;
|
|
169
|
-
}
|
|
170
|
-
constructor(reflector, cache, config){
|
|
152
|
+
constructor(reflector, permissionCacheService){
|
|
171
153
|
_define_property(this, "reflector", void 0);
|
|
172
|
-
_define_property(this, "
|
|
173
|
-
_define_property(this, "config", void 0);
|
|
154
|
+
_define_property(this, "permissionCacheService", void 0);
|
|
174
155
|
this.reflector = reflector;
|
|
175
|
-
this.
|
|
176
|
-
this.config = {
|
|
177
|
-
enableCompanyFeature: false,
|
|
178
|
-
userPermissionKeyFormat: DEFAULT_USER_PERMISSION_KEY_FORMAT,
|
|
179
|
-
companyPermissionKeyFormat: DEFAULT_COMPANY_PERMISSION_KEY_FORMAT,
|
|
180
|
-
...config
|
|
181
|
-
};
|
|
156
|
+
this.permissionCacheService = permissionCacheService;
|
|
182
157
|
}
|
|
183
158
|
}
|
|
184
159
|
PermissionGuard = _ts_decorate([
|
|
185
160
|
Injectable(),
|
|
186
161
|
_ts_param(0, Inject(Reflector)),
|
|
187
162
|
_ts_param(1, Optional()),
|
|
188
|
-
_ts_param(1, Inject(
|
|
189
|
-
_ts_param(2, Optional()),
|
|
190
|
-
_ts_param(2, Inject(PERMISSION_GUARD_CONFIG)),
|
|
163
|
+
_ts_param(1, Inject(SharedPermissionCacheService)),
|
|
191
164
|
_ts_metadata("design:type", Function),
|
|
192
165
|
_ts_metadata("design:paramtypes", [
|
|
193
166
|
typeof Reflector === "undefined" ? Object : Reflector,
|
|
194
|
-
typeof
|
|
195
|
-
typeof PermissionGuardConfig === "undefined" ? Object : PermissionGuardConfig
|
|
167
|
+
typeof SharedPermissionCacheService === "undefined" ? Object : SharedPermissionCacheService
|
|
196
168
|
])
|
|
197
169
|
], PermissionGuard);
|
|
@@ -2,6 +2,7 @@ import { UnauthorizedException } from '@nestjs/common';
|
|
|
2
2
|
import { Reflector } from '@nestjs/core';
|
|
3
3
|
import { AUTH_MESSAGES, IS_PUBLIC_KEY, PERMISSIONS_KEY } from '../constants';
|
|
4
4
|
import { InsufficientPermissionsException, NoPermissionsFoundException, PermissionSystemUnavailableException } from '../exceptions/permission.exception';
|
|
5
|
+
import { SharedPermissionCacheService } from '../modules/shared-permission-cache/shared-permission-cache.service';
|
|
5
6
|
import { PermissionGuard } from './permission.guard';
|
|
6
7
|
function buildContext(request) {
|
|
7
8
|
return {
|
|
@@ -12,9 +13,13 @@ function buildContext(request) {
|
|
|
12
13
|
})
|
|
13
14
|
};
|
|
14
15
|
}
|
|
16
|
+
function buildPermissionService(cache, config) {
|
|
17
|
+
return new SharedPermissionCacheService(cache, config);
|
|
18
|
+
}
|
|
15
19
|
describe('PermissionGuard', ()=>{
|
|
16
20
|
let reflector;
|
|
17
21
|
let cache;
|
|
22
|
+
let permissionCacheService;
|
|
18
23
|
let getAllAndOverrideMock;
|
|
19
24
|
beforeEach(()=>{
|
|
20
25
|
reflector = new Reflector();
|
|
@@ -23,6 +28,7 @@ describe('PermissionGuard', ()=>{
|
|
|
23
28
|
set: jest.fn(),
|
|
24
29
|
del: jest.fn()
|
|
25
30
|
};
|
|
31
|
+
permissionCacheService = buildPermissionService(cache);
|
|
26
32
|
getAllAndOverrideMock = jest.fn();
|
|
27
33
|
jest.spyOn(reflector, 'getAllAndOverride').mockImplementation(getAllAndOverrideMock);
|
|
28
34
|
});
|
|
@@ -36,12 +42,12 @@ describe('PermissionGuard', ()=>{
|
|
|
36
42
|
describe('public routes and missing permission metadata', ()=>{
|
|
37
43
|
it('should allow access when the route is public', async ()=>{
|
|
38
44
|
mockMetadata(true, undefined);
|
|
39
|
-
const guard = new PermissionGuard(reflector,
|
|
45
|
+
const guard = new PermissionGuard(reflector, permissionCacheService);
|
|
40
46
|
await expect(guard.canActivate(buildContext({}))).resolves.toBe(true);
|
|
41
47
|
});
|
|
42
48
|
it('should allow access when no permission metadata is set', async ()=>{
|
|
43
49
|
mockMetadata(false, undefined);
|
|
44
|
-
const guard = new PermissionGuard(reflector,
|
|
50
|
+
const guard = new PermissionGuard(reflector, permissionCacheService);
|
|
45
51
|
await expect(guard.canActivate(buildContext({
|
|
46
52
|
user: {
|
|
47
53
|
id: 'u1'
|
|
@@ -52,7 +58,7 @@ describe('PermissionGuard', ()=>{
|
|
|
52
58
|
describe('authentication requirement', ()=>{
|
|
53
59
|
it('should throw UnauthorizedException when there is no user on the request', async ()=>{
|
|
54
60
|
mockMetadata(false, 'user.read');
|
|
55
|
-
const guard = new PermissionGuard(reflector,
|
|
61
|
+
const guard = new PermissionGuard(reflector, permissionCacheService);
|
|
56
62
|
await expect(guard.canActivate(buildContext({}))).rejects.toMatchObject({
|
|
57
63
|
constructor: UnauthorizedException
|
|
58
64
|
});
|
|
@@ -67,6 +73,15 @@ describe('PermissionGuard', ()=>{
|
|
|
67
73
|
});
|
|
68
74
|
describe('cache availability', ()=>{
|
|
69
75
|
it('should throw PermissionSystemUnavailableException when no cache is injected', async ()=>{
|
|
76
|
+
mockMetadata(false, 'user.read');
|
|
77
|
+
const guard = new PermissionGuard(reflector, buildPermissionService(undefined));
|
|
78
|
+
await expect(guard.canActivate(buildContext({
|
|
79
|
+
user: {
|
|
80
|
+
id: 'u1'
|
|
81
|
+
}
|
|
82
|
+
}))).rejects.toBeInstanceOf(PermissionSystemUnavailableException);
|
|
83
|
+
});
|
|
84
|
+
it('should throw PermissionSystemUnavailableException when no permission service is injected', async ()=>{
|
|
70
85
|
mockMetadata(false, 'user.read');
|
|
71
86
|
const guard = new PermissionGuard(reflector, undefined);
|
|
72
87
|
await expect(guard.canActivate(buildContext({
|
|
@@ -80,7 +95,7 @@ describe('PermissionGuard', ()=>{
|
|
|
80
95
|
it('should throw NoPermissionsFoundException when the user has no cached permissions', async ()=>{
|
|
81
96
|
mockMetadata(false, 'user.read');
|
|
82
97
|
cache.get.mockResolvedValue(undefined);
|
|
83
|
-
const guard = new PermissionGuard(reflector,
|
|
98
|
+
const guard = new PermissionGuard(reflector, permissionCacheService);
|
|
84
99
|
await expect(guard.canActivate(buildContext({
|
|
85
100
|
user: {
|
|
86
101
|
id: 'u1'
|
|
@@ -90,7 +105,7 @@ describe('PermissionGuard', ()=>{
|
|
|
90
105
|
it('should throw NoPermissionsFoundException when the cached permission array is empty', async ()=>{
|
|
91
106
|
mockMetadata(false, 'user.read');
|
|
92
107
|
cache.get.mockResolvedValue([]);
|
|
93
|
-
const guard = new PermissionGuard(reflector,
|
|
108
|
+
const guard = new PermissionGuard(reflector, permissionCacheService);
|
|
94
109
|
await expect(guard.canActivate(buildContext({
|
|
95
110
|
user: {
|
|
96
111
|
id: 'u1'
|
|
@@ -102,7 +117,7 @@ describe('PermissionGuard', ()=>{
|
|
|
102
117
|
cache.get.mockResolvedValue([
|
|
103
118
|
'user.read'
|
|
104
119
|
]);
|
|
105
|
-
const guard = new PermissionGuard(reflector,
|
|
120
|
+
const guard = new PermissionGuard(reflector, permissionCacheService);
|
|
106
121
|
await expect(guard.canActivate(buildContext({
|
|
107
122
|
user: {
|
|
108
123
|
id: 'u1'
|
|
@@ -114,7 +129,7 @@ describe('PermissionGuard', ()=>{
|
|
|
114
129
|
cache.get.mockResolvedValue([
|
|
115
130
|
'user.read'
|
|
116
131
|
]);
|
|
117
|
-
const guard = new PermissionGuard(reflector,
|
|
132
|
+
const guard = new PermissionGuard(reflector, permissionCacheService);
|
|
118
133
|
await expect(guard.canActivate(buildContext({
|
|
119
134
|
user: {
|
|
120
135
|
id: 'u1'
|
|
@@ -126,7 +141,7 @@ describe('PermissionGuard', ()=>{
|
|
|
126
141
|
cache.get.mockResolvedValue([
|
|
127
142
|
'*'
|
|
128
143
|
]);
|
|
129
|
-
const guard = new PermissionGuard(reflector,
|
|
144
|
+
const guard = new PermissionGuard(reflector, permissionCacheService);
|
|
130
145
|
await expect(guard.canActivate(buildContext({
|
|
131
146
|
user: {
|
|
132
147
|
id: 'u1'
|
|
@@ -138,7 +153,7 @@ describe('PermissionGuard', ()=>{
|
|
|
138
153
|
cache.get.mockResolvedValue([
|
|
139
154
|
'user.*'
|
|
140
155
|
]);
|
|
141
|
-
const guard = new PermissionGuard(reflector,
|
|
156
|
+
const guard = new PermissionGuard(reflector, permissionCacheService);
|
|
142
157
|
await expect(guard.canActivate(buildContext({
|
|
143
158
|
user: {
|
|
144
159
|
id: 'u1'
|
|
@@ -153,7 +168,7 @@ describe('PermissionGuard', ()=>{
|
|
|
153
168
|
cache.get.mockResolvedValue([
|
|
154
169
|
'user.read'
|
|
155
170
|
]);
|
|
156
|
-
const guard = new PermissionGuard(reflector,
|
|
171
|
+
const guard = new PermissionGuard(reflector, permissionCacheService);
|
|
157
172
|
await expect(guard.canActivate(buildContext({
|
|
158
173
|
user: {
|
|
159
174
|
id: 'u1'
|
|
@@ -169,7 +184,7 @@ describe('PermissionGuard', ()=>{
|
|
|
169
184
|
'user.read',
|
|
170
185
|
'user.write'
|
|
171
186
|
]);
|
|
172
|
-
const guard = new PermissionGuard(reflector,
|
|
187
|
+
const guard = new PermissionGuard(reflector, permissionCacheService);
|
|
173
188
|
await expect(guard.canActivate(buildContext({
|
|
174
189
|
user: {
|
|
175
190
|
id: 'u1'
|
|
@@ -181,7 +196,7 @@ describe('PermissionGuard', ()=>{
|
|
|
181
196
|
cache.get.mockResolvedValue([
|
|
182
197
|
'user.read'
|
|
183
198
|
]);
|
|
184
|
-
const guard = new PermissionGuard(reflector,
|
|
199
|
+
const guard = new PermissionGuard(reflector, permissionCacheService);
|
|
185
200
|
await expect(guard.canActivate(buildContext({
|
|
186
201
|
user: {
|
|
187
202
|
id: 'u1'
|
|
@@ -199,7 +214,7 @@ describe('PermissionGuard', ()=>{
|
|
|
199
214
|
cache.get.mockResolvedValue([
|
|
200
215
|
'manager'
|
|
201
216
|
]);
|
|
202
|
-
const guard = new PermissionGuard(reflector,
|
|
217
|
+
const guard = new PermissionGuard(reflector, permissionCacheService);
|
|
203
218
|
await expect(guard.canActivate(buildContext({
|
|
204
219
|
user: {
|
|
205
220
|
id: 'u1'
|
|
@@ -217,7 +232,7 @@ describe('PermissionGuard', ()=>{
|
|
|
217
232
|
cache.get.mockResolvedValue([
|
|
218
233
|
'guest'
|
|
219
234
|
]);
|
|
220
|
-
const guard = new PermissionGuard(reflector,
|
|
235
|
+
const guard = new PermissionGuard(reflector, permissionCacheService);
|
|
221
236
|
await expect(guard.canActivate(buildContext({
|
|
222
237
|
user: {
|
|
223
238
|
id: 'u1'
|
|
@@ -232,7 +247,7 @@ describe('PermissionGuard', ()=>{
|
|
|
232
247
|
cache.get.mockResolvedValue([
|
|
233
248
|
'user.read'
|
|
234
249
|
]);
|
|
235
|
-
const guard = new PermissionGuard(reflector,
|
|
250
|
+
const guard = new PermissionGuard(reflector, permissionCacheService);
|
|
236
251
|
await expect(guard.canActivate(buildContext({
|
|
237
252
|
user: {
|
|
238
253
|
id: 'u1'
|
|
@@ -268,7 +283,7 @@ describe('PermissionGuard', ()=>{
|
|
|
268
283
|
'users.read',
|
|
269
284
|
'manager'
|
|
270
285
|
]);
|
|
271
|
-
const guard = new PermissionGuard(reflector,
|
|
286
|
+
const guard = new PermissionGuard(reflector, permissionCacheService);
|
|
272
287
|
await expect(guard.canActivate(buildContext({
|
|
273
288
|
user: {
|
|
274
289
|
id: 'u1'
|
|
@@ -284,7 +299,7 @@ describe('PermissionGuard', ()=>{
|
|
|
284
299
|
cache.get.mockResolvedValue([
|
|
285
300
|
'user.read'
|
|
286
301
|
]);
|
|
287
|
-
const guard = new PermissionGuard(reflector,
|
|
302
|
+
const guard = new PermissionGuard(reflector, permissionCacheService);
|
|
288
303
|
await expect(guard.canActivate(buildContext({
|
|
289
304
|
user: {
|
|
290
305
|
id: 'u1'
|
|
@@ -298,7 +313,7 @@ describe('PermissionGuard', ()=>{
|
|
|
298
313
|
'user.read'
|
|
299
314
|
]
|
|
300
315
|
});
|
|
301
|
-
const guard = new PermissionGuard(reflector,
|
|
316
|
+
const guard = new PermissionGuard(reflector, permissionCacheService);
|
|
302
317
|
await expect(guard.canActivate(buildContext({
|
|
303
318
|
user: {
|
|
304
319
|
id: 'u1'
|
|
@@ -308,7 +323,7 @@ describe('PermissionGuard', ()=>{
|
|
|
308
323
|
it('should treat an object-shaped cache value with no backendCodes as no permissions', async ()=>{
|
|
309
324
|
mockMetadata(false, 'user.read');
|
|
310
325
|
cache.get.mockResolvedValue({});
|
|
311
|
-
const guard = new PermissionGuard(reflector,
|
|
326
|
+
const guard = new PermissionGuard(reflector, permissionCacheService);
|
|
312
327
|
await expect(guard.canActivate(buildContext({
|
|
313
328
|
user: {
|
|
314
329
|
id: 'u1'
|
|
@@ -322,9 +337,9 @@ describe('PermissionGuard', ()=>{
|
|
|
322
337
|
cache.get.mockResolvedValue([
|
|
323
338
|
'user.read'
|
|
324
339
|
]);
|
|
325
|
-
const guard = new PermissionGuard(reflector, cache, {
|
|
340
|
+
const guard = new PermissionGuard(reflector, buildPermissionService(cache, {
|
|
326
341
|
enableCompanyFeature: true
|
|
327
|
-
});
|
|
342
|
+
}));
|
|
328
343
|
await guard.canActivate(buildContext({
|
|
329
344
|
user: {
|
|
330
345
|
id: 'u1',
|
|
@@ -339,7 +354,7 @@ describe('PermissionGuard', ()=>{
|
|
|
339
354
|
cache.get.mockResolvedValue([
|
|
340
355
|
'user.read'
|
|
341
356
|
]);
|
|
342
|
-
const guard = new PermissionGuard(reflector,
|
|
357
|
+
const guard = new PermissionGuard(reflector, permissionCacheService);
|
|
343
358
|
await guard.canActivate(buildContext({
|
|
344
359
|
user: {
|
|
345
360
|
id: 'u1',
|
package/fesm/modules/index.js
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
export * from './cache/cache.module';
|
|
2
2
|
export * from './datasource';
|
|
3
|
+
export * from './shared-permission-cache/shared-permission-cache.module';
|
|
4
|
+
export * from './shared-permission-cache/shared-permission-cache.service';
|
|
3
5
|
export * from './utils/utils.module';
|
|
4
6
|
export * from './utils/utils.service';
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
function _ts_decorate(decorators, target, key, desc) {
|
|
2
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
3
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
4
|
+
else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
5
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
6
|
+
}
|
|
7
|
+
import { Global, Module } from '@nestjs/common';
|
|
8
|
+
import { SharedPermissionCacheService } from './shared-permission-cache.service';
|
|
9
|
+
export class SharedPermissionCacheModule {
|
|
10
|
+
}
|
|
11
|
+
SharedPermissionCacheModule = _ts_decorate([
|
|
12
|
+
Global(),
|
|
13
|
+
Module({
|
|
14
|
+
imports: [],
|
|
15
|
+
providers: [
|
|
16
|
+
SharedPermissionCacheService
|
|
17
|
+
],
|
|
18
|
+
exports: [
|
|
19
|
+
SharedPermissionCacheService
|
|
20
|
+
]
|
|
21
|
+
})
|
|
22
|
+
], SharedPermissionCacheModule);
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
function _define_property(obj, key, value) {
|
|
2
|
+
if (key in obj) {
|
|
3
|
+
Object.defineProperty(obj, key, {
|
|
4
|
+
value: value,
|
|
5
|
+
enumerable: true,
|
|
6
|
+
configurable: true,
|
|
7
|
+
writable: true
|
|
8
|
+
});
|
|
9
|
+
} else {
|
|
10
|
+
obj[key] = value;
|
|
11
|
+
}
|
|
12
|
+
return obj;
|
|
13
|
+
}
|
|
14
|
+
function _ts_decorate(decorators, target, key, desc) {
|
|
15
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
16
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
17
|
+
else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
18
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
19
|
+
}
|
|
20
|
+
function _ts_metadata(k, v) {
|
|
21
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
22
|
+
}
|
|
23
|
+
function _ts_param(paramIndex, decorator) {
|
|
24
|
+
return function(target, key) {
|
|
25
|
+
decorator(target, key, paramIndex);
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
import { Inject, Injectable, Optional } from '@nestjs/common';
|
|
29
|
+
import { HybridCache } from '../../classes/hybrid-cache.class';
|
|
30
|
+
import { CACHE_INSTANCE, PERMISSION_GUARD_CONFIG } from '../../constants';
|
|
31
|
+
import { PermissionGuardConfig } from '../../interfaces';
|
|
32
|
+
import { buildPermissionCacheKey, DEFAULT_COMPANY_PERMISSION_KEY_FORMAT, DEFAULT_USER_PERMISSION_KEY_FORMAT } from '../../utils/permission-cache-key.util';
|
|
33
|
+
export class SharedPermissionCacheService {
|
|
34
|
+
/** Read the cached permission codes for a user; empty array when cache is unavailable or unset */ async getPermissions(options) {
|
|
35
|
+
if (!this.cache) return [];
|
|
36
|
+
const cacheKey = buildPermissionCacheKey(options, this.config);
|
|
37
|
+
const cached = await this.cache.get(cacheKey);
|
|
38
|
+
if (!cached) return [];
|
|
39
|
+
return Array.isArray(cached) ? cached : cached.backendCodes || [];
|
|
40
|
+
}
|
|
41
|
+
/** Overwrite the cached permission codes for a user with a fixed list */ async setPermissions(options, permissions, ttl) {
|
|
42
|
+
if (!this.cache) return;
|
|
43
|
+
const cacheKey = buildPermissionCacheKey(options, this.config);
|
|
44
|
+
await this.cache.set(cacheKey, permissions, ttl);
|
|
45
|
+
}
|
|
46
|
+
/** Clear the cached permission codes for a user */ async clearPermissions(options) {
|
|
47
|
+
if (!this.cache) return;
|
|
48
|
+
const cacheKey = buildPermissionCacheKey(options, this.config);
|
|
49
|
+
await this.cache.del(cacheKey);
|
|
50
|
+
}
|
|
51
|
+
/** Check a single permission against the cached list, honoring `*` and `prefix.*` wildcards */ async hasPermission(options, requiredPermission) {
|
|
52
|
+
const permissions = await this.getPermissions(options);
|
|
53
|
+
return this.matchPermission(permissions, requiredPermission);
|
|
54
|
+
}
|
|
55
|
+
/** Whether a cache instance is wired up; false means permission checks can't be served at all */ isCacheConfigured() {
|
|
56
|
+
return !!this.cache;
|
|
57
|
+
}
|
|
58
|
+
/** Match an already-fetched permission list against a required permission, honoring `*` and `prefix.*` wildcards */ matchPermission(userPermissions, requiredPermission) {
|
|
59
|
+
if (userPermissions.includes(requiredPermission)) return true;
|
|
60
|
+
for (const permission of userPermissions){
|
|
61
|
+
if (permission === '*') return true;
|
|
62
|
+
if (permission.endsWith('.*') && requiredPermission.startsWith(permission.slice(0, -1))) {
|
|
63
|
+
return true;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
return false;
|
|
67
|
+
}
|
|
68
|
+
constructor(cache, config){
|
|
69
|
+
_define_property(this, "cache", void 0);
|
|
70
|
+
_define_property(this, "config", void 0);
|
|
71
|
+
this.cache = cache;
|
|
72
|
+
this.config = {
|
|
73
|
+
enableCompanyFeature: false,
|
|
74
|
+
userPermissionKeyFormat: DEFAULT_USER_PERMISSION_KEY_FORMAT,
|
|
75
|
+
companyPermissionKeyFormat: DEFAULT_COMPANY_PERMISSION_KEY_FORMAT,
|
|
76
|
+
...config
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
SharedPermissionCacheService = _ts_decorate([
|
|
81
|
+
Injectable(),
|
|
82
|
+
_ts_param(0, Optional()),
|
|
83
|
+
_ts_param(0, Inject(CACHE_INSTANCE)),
|
|
84
|
+
_ts_param(1, Optional()),
|
|
85
|
+
_ts_param(1, Inject(PERMISSION_GUARD_CONFIG)),
|
|
86
|
+
_ts_metadata("design:type", Function),
|
|
87
|
+
_ts_metadata("design:paramtypes", [
|
|
88
|
+
typeof HybridCache === "undefined" ? Object : HybridCache,
|
|
89
|
+
typeof PermissionGuardConfig === "undefined" ? Object : PermissionGuardConfig
|
|
90
|
+
])
|
|
91
|
+
], SharedPermissionCacheService);
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import { SharedPermissionCacheService } from './shared-permission-cache.service';
|
|
2
|
+
describe('SharedPermissionCacheService', ()=>{
|
|
3
|
+
let service;
|
|
4
|
+
let mockCache;
|
|
5
|
+
beforeEach(()=>{
|
|
6
|
+
mockCache = {
|
|
7
|
+
get: jest.fn(),
|
|
8
|
+
set: jest.fn(),
|
|
9
|
+
del: jest.fn()
|
|
10
|
+
};
|
|
11
|
+
service = new SharedPermissionCacheService(mockCache);
|
|
12
|
+
});
|
|
13
|
+
describe('getPermissions', ()=>{
|
|
14
|
+
it('returns an empty array when nothing is cached', async ()=>{
|
|
15
|
+
mockCache.get.mockResolvedValue(undefined);
|
|
16
|
+
const permissions = await service.getPermissions({
|
|
17
|
+
userId: 'user-1'
|
|
18
|
+
});
|
|
19
|
+
expect(permissions).toEqual([]);
|
|
20
|
+
expect(mockCache.get).toHaveBeenCalledWith('my-permissions:user:user-1');
|
|
21
|
+
});
|
|
22
|
+
it('returns the cached array as-is', async ()=>{
|
|
23
|
+
mockCache.get.mockResolvedValue([
|
|
24
|
+
'file.read',
|
|
25
|
+
'file.update'
|
|
26
|
+
]);
|
|
27
|
+
const permissions = await service.getPermissions({
|
|
28
|
+
userId: 'user-1'
|
|
29
|
+
});
|
|
30
|
+
expect(permissions).toEqual([
|
|
31
|
+
'file.read',
|
|
32
|
+
'file.update'
|
|
33
|
+
]);
|
|
34
|
+
});
|
|
35
|
+
it('unwraps a { backendCodes } shaped cache value', async ()=>{
|
|
36
|
+
mockCache.get.mockResolvedValue({
|
|
37
|
+
backendCodes: [
|
|
38
|
+
'file.read'
|
|
39
|
+
]
|
|
40
|
+
});
|
|
41
|
+
const permissions = await service.getPermissions({
|
|
42
|
+
userId: 'user-1'
|
|
43
|
+
});
|
|
44
|
+
expect(permissions).toEqual([
|
|
45
|
+
'file.read'
|
|
46
|
+
]);
|
|
47
|
+
});
|
|
48
|
+
it('scopes the cache key by company and branch when enableCompanyFeature is on', async ()=>{
|
|
49
|
+
const scopedService = new SharedPermissionCacheService(mockCache, {
|
|
50
|
+
enableCompanyFeature: true
|
|
51
|
+
});
|
|
52
|
+
mockCache.get.mockResolvedValue(undefined);
|
|
53
|
+
await scopedService.getPermissions({
|
|
54
|
+
userId: 'user-1',
|
|
55
|
+
companyId: 'company-1',
|
|
56
|
+
branchId: 'branch-1'
|
|
57
|
+
});
|
|
58
|
+
expect(mockCache.get).toHaveBeenCalledWith('my-permissions:company:company-1:branch:branch-1:user:user-1');
|
|
59
|
+
});
|
|
60
|
+
it('returns an empty array when no cache instance is configured', async ()=>{
|
|
61
|
+
const noCacheService = new SharedPermissionCacheService();
|
|
62
|
+
await expect(noCacheService.getPermissions({
|
|
63
|
+
userId: 'user-1'
|
|
64
|
+
})).resolves.toEqual([]);
|
|
65
|
+
});
|
|
66
|
+
});
|
|
67
|
+
describe('setPermissions', ()=>{
|
|
68
|
+
it('writes the fixed permission list under the user cache key', async ()=>{
|
|
69
|
+
await service.setPermissions({
|
|
70
|
+
userId: 'user-1'
|
|
71
|
+
}, [
|
|
72
|
+
'file.read',
|
|
73
|
+
'file.update'
|
|
74
|
+
]);
|
|
75
|
+
expect(mockCache.set).toHaveBeenCalledWith('my-permissions:user:user-1', [
|
|
76
|
+
'file.read',
|
|
77
|
+
'file.update'
|
|
78
|
+
], undefined);
|
|
79
|
+
});
|
|
80
|
+
it('forwards a ttl when given', async ()=>{
|
|
81
|
+
await service.setPermissions({
|
|
82
|
+
userId: 'user-1'
|
|
83
|
+
}, [
|
|
84
|
+
'file.read'
|
|
85
|
+
], 60);
|
|
86
|
+
expect(mockCache.set).toHaveBeenCalledWith('my-permissions:user:user-1', [
|
|
87
|
+
'file.read'
|
|
88
|
+
], 60);
|
|
89
|
+
});
|
|
90
|
+
it('does nothing when no cache instance is configured', async ()=>{
|
|
91
|
+
const noCacheService = new SharedPermissionCacheService();
|
|
92
|
+
await expect(noCacheService.setPermissions({
|
|
93
|
+
userId: 'user-1'
|
|
94
|
+
}, [
|
|
95
|
+
'file.read'
|
|
96
|
+
])).resolves.toBeUndefined();
|
|
97
|
+
});
|
|
98
|
+
});
|
|
99
|
+
describe('clearPermissions', ()=>{
|
|
100
|
+
it('deletes the cache key for the user', async ()=>{
|
|
101
|
+
await service.clearPermissions({
|
|
102
|
+
userId: 'user-1'
|
|
103
|
+
});
|
|
104
|
+
expect(mockCache.del).toHaveBeenCalledWith('my-permissions:user:user-1');
|
|
105
|
+
});
|
|
106
|
+
});
|
|
107
|
+
describe('hasPermission', ()=>{
|
|
108
|
+
it('returns true when the exact permission is cached', async ()=>{
|
|
109
|
+
mockCache.get.mockResolvedValue([
|
|
110
|
+
'file.view.private'
|
|
111
|
+
]);
|
|
112
|
+
await expect(service.hasPermission({
|
|
113
|
+
userId: 'user-1'
|
|
114
|
+
}, 'file.view.private')).resolves.toBe(true);
|
|
115
|
+
});
|
|
116
|
+
it('returns false when the permission is missing', async ()=>{
|
|
117
|
+
mockCache.get.mockResolvedValue([
|
|
118
|
+
'file.read'
|
|
119
|
+
]);
|
|
120
|
+
await expect(service.hasPermission({
|
|
121
|
+
userId: 'user-1'
|
|
122
|
+
}, 'file.view.private')).resolves.toBe(false);
|
|
123
|
+
});
|
|
124
|
+
it('honors the global "*" wildcard', async ()=>{
|
|
125
|
+
mockCache.get.mockResolvedValue([
|
|
126
|
+
'*'
|
|
127
|
+
]);
|
|
128
|
+
await expect(service.hasPermission({
|
|
129
|
+
userId: 'user-1'
|
|
130
|
+
}, 'file.view.private')).resolves.toBe(true);
|
|
131
|
+
});
|
|
132
|
+
it('honors a "prefix.*" wildcard', async ()=>{
|
|
133
|
+
mockCache.get.mockResolvedValue([
|
|
134
|
+
'file.*'
|
|
135
|
+
]);
|
|
136
|
+
await expect(service.hasPermission({
|
|
137
|
+
userId: 'user-1'
|
|
138
|
+
}, 'file.view.private')).resolves.toBe(true);
|
|
139
|
+
});
|
|
140
|
+
});
|
|
141
|
+
describe('matchPermission', ()=>{
|
|
142
|
+
it('matches an already-fetched list without touching the cache', ()=>{
|
|
143
|
+
expect(service.matchPermission([
|
|
144
|
+
'file.read'
|
|
145
|
+
], 'file.read')).toBe(true);
|
|
146
|
+
expect(service.matchPermission([
|
|
147
|
+
'file.read'
|
|
148
|
+
], 'file.write')).toBe(false);
|
|
149
|
+
expect(mockCache.get).not.toHaveBeenCalled();
|
|
150
|
+
});
|
|
151
|
+
});
|
|
152
|
+
describe('isCacheConfigured', ()=>{
|
|
153
|
+
it('returns true when a cache instance is injected', ()=>{
|
|
154
|
+
expect(service.isCacheConfigured()).toBe(true);
|
|
155
|
+
});
|
|
156
|
+
it('returns false when no cache instance is injected', ()=>{
|
|
157
|
+
const noCacheService = new SharedPermissionCacheService();
|
|
158
|
+
expect(noCacheService.isCacheConfigured()).toBe(false);
|
|
159
|
+
});
|
|
160
|
+
});
|
|
161
|
+
});
|