@nu-art/permissions-backend 0.500.0 → 0.500.6
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/RequirePermission.d.ts +22 -10
- package/RequirePermission.js +24 -15
- package/_entity/access-group/ModuleBE_AccessGroupDB.d.ts +13 -0
- package/_entity/access-group/ModuleBE_AccessGroupDB.js +36 -0
- package/_entity/access-group/module-pack.d.ts +1 -0
- package/_entity/access-group/module-pack.js +3 -0
- package/_entity/permission-scope/ModuleBE_PermissionScopeDB.d.ts +6 -0
- package/_entity/permission-scope/ModuleBE_PermissionScopeDB.js +8 -0
- package/_entity/permission-scope/module-pack.d.ts +1 -0
- package/_entity/permission-scope/module-pack.js +3 -0
- package/_entity/user-permissions/ModuleBE_UserPermissionsAPI.d.ts +9 -0
- package/_entity/{permission-user/ModuleBE_PermissionUserAPI.js → user-permissions/ModuleBE_UserPermissionsAPI.js} +17 -16
- package/_entity/user-permissions/ModuleBE_UserPermissionsDB.d.ts +6 -0
- package/_entity/user-permissions/ModuleBE_UserPermissionsDB.js +8 -0
- package/_entity/user-permissions/module-pack.d.ts +2 -0
- package/_entity/user-permissions/module-pack.js +3 -0
- package/assertion-types.d.ts +9 -0
- package/consts.d.ts +7 -4
- package/consts.js +4 -2
- package/core/function-permission-registry.d.ts +5 -6
- package/core/function-permission-registry.js +10 -0
- package/core/module-pack.js +6 -7
- package/document-access-api.d.ts +6 -0
- package/document-access-api.js +49 -0
- package/document-access-enforcement.d.ts +9 -0
- package/document-access-enforcement.js +137 -0
- package/index.d.ts +12 -6
- package/index.js +12 -6
- package/modules/ModuleBE_Permissions.d.ts +63 -78
- package/modules/ModuleBE_Permissions.js +494 -441
- package/modules/ModuleBE_PermissionsAssert.d.ts +6 -54
- package/modules/ModuleBE_PermissionsAssert.js +60 -285
- package/package.json +14 -12
- package/PermissionKey_BE.d.ts +0 -16
- package/PermissionKey_BE.js +0 -59
- package/_entity/permission-access-level/ModuleBE_PermissionAccessLevelDB.d.ts +0 -13
- package/_entity/permission-access-level/ModuleBE_PermissionAccessLevelDB.js +0 -49
- package/_entity/permission-access-level/index.d.ts +0 -2
- package/_entity/permission-access-level/index.js +0 -2
- package/_entity/permission-access-level/module-pack.d.ts +0 -1
- package/_entity/permission-access-level/module-pack.js +0 -3
- package/_entity/permission-api/ModuleBE_PermissionAPIDB.d.ts +0 -10
- package/_entity/permission-api/ModuleBE_PermissionAPIDB.js +0 -62
- package/_entity/permission-api/index.d.ts +0 -2
- package/_entity/permission-api/index.js +0 -2
- package/_entity/permission-api/module-pack.d.ts +0 -1
- package/_entity/permission-api/module-pack.js +0 -3
- package/_entity/permission-domain/ModuleBE_PermissionDomainDB.d.ts +0 -9
- package/_entity/permission-domain/ModuleBE_PermissionDomainDB.js +0 -22
- package/_entity/permission-domain/index.d.ts +0 -2
- package/_entity/permission-domain/index.js +0 -2
- package/_entity/permission-domain/module-pack.d.ts +0 -1
- package/_entity/permission-domain/module-pack.js +0 -3
- package/_entity/permission-group/ModuleBE_PermissionGroupDB.d.ts +0 -12
- package/_entity/permission-group/ModuleBE_PermissionGroupDB.js +0 -65
- package/_entity/permission-group/index.d.ts +0 -2
- package/_entity/permission-group/index.js +0 -2
- package/_entity/permission-group/module-pack.d.ts +0 -1
- package/_entity/permission-group/module-pack.js +0 -3
- package/_entity/permission-project/ModuleBE_PermissionProjectDB.d.ts +0 -8
- package/_entity/permission-project/ModuleBE_PermissionProjectDB.js +0 -12
- package/_entity/permission-project/index.d.ts +0 -2
- package/_entity/permission-project/index.js +0 -2
- package/_entity/permission-project/module-pack.d.ts +0 -1
- package/_entity/permission-project/module-pack.js +0 -3
- package/_entity/permission-user/ModuleBE_PermissionUserAPI.d.ts +0 -9
- package/_entity/permission-user/ModuleBE_PermissionUserDB.d.ts +0 -34
- package/_entity/permission-user/ModuleBE_PermissionUserDB.js +0 -241
- package/_entity/permission-user/index.d.ts +0 -3
- package/_entity/permission-user/index.js +0 -3
- package/_entity/permission-user/module-pack.d.ts +0 -2
- package/_entity/permission-user/module-pack.js +0 -3
- package/_entity.d.ts +0 -12
- package/_entity.js +0 -18
- package/core/external-api-paths.d.ts +0 -13
- package/core/external-api-paths.js +0 -13
- package/core/utils.d.ts +0 -25
- package/core/utils.js +0 -85
- package/modules/consts.d.ts +0 -11
- package/modules/consts.js +0 -29
- package/modules/index.d.ts +0 -2
- package/modules/index.js +0 -20
- package/permissions-wire.d.ts +0 -46
- package/permissions-wire.js +0 -47
- package/permissions.d.ts +0 -22
- package/permissions.js +0 -152
- package/types.d.ts +0 -28
- /package/{types.js → assertion-types.js} +0 -0
|
@@ -1,65 +1,17 @@
|
|
|
1
|
-
import { Module
|
|
1
|
+
import { Module } from '@nu-art/ts-common';
|
|
2
2
|
import type { ServerApi_Middleware } from '@nu-art/http-server';
|
|
3
|
-
import { ModuleBE_BaseDB } from '@nu-art/db-api-backend';
|
|
4
3
|
import { CollectSessionData } from '@nu-art/user-account-backend';
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import type {
|
|
8
|
-
export type UserCalculatedAccessLevel = {
|
|
9
|
-
[domainId: string]: number;
|
|
10
|
-
};
|
|
11
|
-
export type GroupPairWithBaseLevelsObj = {
|
|
12
|
-
accessLevels: Base_AccessLevel[];
|
|
13
|
-
};
|
|
14
|
-
export type RequestPairWithLevelsObj = {
|
|
15
|
-
accessLevels: DB_PermissionAccessLevel[];
|
|
16
|
-
};
|
|
4
|
+
import { SessionData_StrictMode } from '@nu-art/permissions-shared';
|
|
5
|
+
import type { PermissionScope } from '@nu-art/permissions-shared';
|
|
6
|
+
import type { PermissionAssertionContext } from '../assertion-types.js';
|
|
17
7
|
type Config = {
|
|
18
8
|
strictMode?: boolean;
|
|
19
9
|
};
|
|
20
|
-
/**
|
|
21
|
-
* [DomainId uniqueString]: accessLevel's numerical value
|
|
22
|
-
*/
|
|
23
10
|
export declare class ModuleBE_PermissionsAssert_Class extends Module<Config> implements CollectSessionData<SessionData_StrictMode> {
|
|
24
|
-
private projectId;
|
|
25
|
-
_keys: TypedMap<boolean>;
|
|
26
|
-
permissionKeys: TypedMap<PermissionKey_BE<any>>;
|
|
27
|
-
readonly Middleware: (keys?: string[]) => ServerApi_Middleware;
|
|
28
11
|
readonly LoadPermissionsMiddleware: ServerApi_Middleware;
|
|
29
|
-
readonly CustomMiddleware: (keys: string[], action: (projectId: string, customFields: StringMap) => Promise<void>) => ServerApi_Middleware;
|
|
30
12
|
__collectSessionData(): Promise<SessionData_StrictMode>;
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
* @deprecated Path-based sync filter; use function-based permissions instead. API collection deprecated.
|
|
34
|
-
* Returns a filter for sync manager. The app must call SyncManager.setModuleFilter(ModuleBE_PermissionsAssert.getPermissionsAssertSyncFilter()) when using a sync manager.
|
|
35
|
-
*/
|
|
36
|
-
getPermissionsAssertSyncFilter(): (dbModules: (ModuleBE_BaseDB<any>)[]) => Promise<(ModuleBE_BaseDB<any>)[]>;
|
|
37
|
-
assertUserPermissions(body: API_PermissionsAssert['assertUserPermissions']['Body']): Promise<API_PermissionsAssert['assertUserPermissions']['Response']>;
|
|
38
|
-
private assertPermission;
|
|
39
|
-
/**
|
|
40
|
-
* @deprecated Path-based API permission; use function-based permissions and assertFunctionPermission(def) instead. API collection deprecated.
|
|
41
|
-
*/
|
|
42
|
-
assertPathPermissions(projectId: string, path: string): Promise<void>;
|
|
43
|
-
assertUserPassesAccessLevels(domainToLevelValueMap: DomainToLevelValueMap, userPermissions: TypedMap<number>): void;
|
|
44
|
-
/**
|
|
45
|
-
* Asserts that the user has at least the required level for the function-permission def (from @RequirePermission).
|
|
46
|
-
* Call this before invoking a handler when getRequirePermissionDef(handler) returns a def.
|
|
47
|
-
*/
|
|
48
|
-
assertFunctionPermission(def: FunctionPermissionDef): void;
|
|
49
|
-
/** @deprecated Path-based API lookup; API collection deprecated. Use function-based permissions. */
|
|
50
|
-
getApiDetails(_path: string, projectId: string): Promise<{
|
|
51
|
-
dbApi: DB_PermissionAPI;
|
|
52
|
-
requestPermissions: DB_PermissionAccessLevel[];
|
|
53
|
-
} | undefined>;
|
|
54
|
-
getApisDetails(urls: string[], projectId: string): Promise<({
|
|
55
|
-
apiDb: DB_PermissionAPI;
|
|
56
|
-
requestPermissions: DB_PermissionAccessLevel[];
|
|
57
|
-
} | undefined)[]>;
|
|
58
|
-
private getAccessLevels;
|
|
59
|
-
setProjectId: (projectId: string) => void;
|
|
60
|
-
getRegEx(value: string): RegExp;
|
|
61
|
-
registerPermissionKeys(keys: string[]): void;
|
|
62
|
-
private isStrictMode;
|
|
13
|
+
assertScopePermission(scope: PermissionScope, requiredValue: string): void;
|
|
14
|
+
createAssertionContext(): PermissionAssertionContext;
|
|
63
15
|
}
|
|
64
16
|
export declare const ModuleBE_PermissionsAssert: ModuleBE_PermissionsAssert_Class;
|
|
65
17
|
export {};
|
|
@@ -16,293 +16,68 @@
|
|
|
16
16
|
* See the License for the specific language governing permissions and
|
|
17
17
|
* limitations under the License.
|
|
18
18
|
*/
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
19
|
+
import { ApiException, Module } from '@nu-art/ts-common';
|
|
20
|
+
import { stringToUniqueId } from '@nu-art/db-api-shared';
|
|
21
|
+
import { SessionKey_Account_BE } from '@nu-art/user-account-backend';
|
|
22
|
+
import { AccessScope_Self } from '@nu-art/permissions-shared';
|
|
23
|
+
import { MemKey_UserAccessIds, MemKey_UserEntityContexts, MemKey_UserScopePermissions } from '../consts.js';
|
|
24
|
+
import { ModuleBE_UserPermissionsDB } from '../_entity/user-permissions/ModuleBE_UserPermissionsDB.js';
|
|
25
|
+
export class ModuleBE_PermissionsAssert_Class extends Module {
|
|
26
|
+
LoadPermissionsMiddleware = async () => {
|
|
27
|
+
const account = SessionKey_Account_BE.get();
|
|
28
|
+
const permissionsId = stringToUniqueId(account._id);
|
|
29
|
+
const entity = await ModuleBE_UserPermissionsDB.query.unique(permissionsId);
|
|
30
|
+
MemKey_UserScopePermissions.set(entity?.scopeEntries ?? []);
|
|
31
|
+
const personalGroupId = stringToUniqueId(account._id);
|
|
32
|
+
MemKey_UserAccessIds.set(entity?.accessIds ?? { [AccessScope_Self]: [personalGroupId] });
|
|
33
|
+
};
|
|
34
|
+
async __collectSessionData() {
|
|
35
|
+
return { key: 'strictMode', value: { isStrictMode: !!this.config?.strictMode } };
|
|
23
36
|
}
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
if (kind === "accessor") {
|
|
39
|
-
if (result === void 0) continue;
|
|
40
|
-
if (result === null || typeof result !== "object") throw new TypeError("Object expected");
|
|
41
|
-
if (_ = accept(result.get)) descriptor.get = _;
|
|
42
|
-
if (_ = accept(result.set)) descriptor.set = _;
|
|
43
|
-
if (_ = accept(result.init)) initializers.unshift(_);
|
|
44
|
-
}
|
|
45
|
-
else if (_ = accept(result)) {
|
|
46
|
-
if (kind === "field") initializers.unshift(_);
|
|
47
|
-
else descriptor[key] = _;
|
|
37
|
+
assertScopePermission(scope, requiredValue) {
|
|
38
|
+
const userPerms = MemKey_UserScopePermissions.get();
|
|
39
|
+
const prefix = scope.key + ':';
|
|
40
|
+
const entry = userPerms.find(p => p.startsWith(prefix));
|
|
41
|
+
if (!entry)
|
|
42
|
+
throw new ApiException(403, `No access for scope: ${scope.key}`);
|
|
43
|
+
const userValue = entry.substring(prefix.length);
|
|
44
|
+
const requiredIdx = scope.values.indexOf(requiredValue);
|
|
45
|
+
if (requiredIdx === -1)
|
|
46
|
+
throw new ApiException(503, `Unknown permission value '${requiredValue}' for scope '${scope.key}'`);
|
|
47
|
+
const userIdx = scope.values.indexOf(userValue);
|
|
48
|
+
if (userIdx === -1 || userIdx < requiredIdx) {
|
|
49
|
+
this.logErrorBold(`scope permission denied: ${scope.key} (has: ${userValue}, needs: ${requiredValue})`);
|
|
50
|
+
throw new ApiException(403, `Insufficient access for scope: ${scope.key}`);
|
|
48
51
|
}
|
|
49
52
|
}
|
|
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
|
-
projectId = __runInitializers(this, _instanceExtraInitializers);
|
|
78
|
-
_keys = {};
|
|
79
|
-
permissionKeys = {};
|
|
80
|
-
// constructor() {
|
|
81
|
-
// super();
|
|
82
|
-
// this.setMinLevel(LogLevel.Debug);
|
|
83
|
-
// }
|
|
84
|
-
Middleware = (keys = []) => async () => {
|
|
85
|
-
await this.CustomMiddleware(keys, async (projectId) => {
|
|
86
|
-
return this.assertPathPermissions(projectId, MemKey_HttpRequestUrl.get());
|
|
87
|
-
})();
|
|
88
|
-
};
|
|
89
|
-
LoadPermissionsMiddleware = async () => {
|
|
90
|
-
try {
|
|
91
|
-
MemKey_UserPermissions.get();
|
|
92
|
-
}
|
|
93
|
-
catch (err) {
|
|
94
|
-
MemKey_UserPermissions.set(SessionKey_Permissions_BE.get().domainToValueMap);
|
|
95
|
-
}
|
|
96
|
-
};
|
|
97
|
-
CustomMiddleware = (keys, action) => async () => {
|
|
98
|
-
const customFields = {};
|
|
99
|
-
let object;
|
|
100
|
-
const reqMethod = MemKey_HttpRequestMethod.get();
|
|
101
|
-
switch (reqMethod) {
|
|
102
|
-
case HttpMethod.POST:
|
|
103
|
-
case HttpMethod.PATCH:
|
|
104
|
-
case HttpMethod.PUT:
|
|
105
|
-
object = MemKey_HttpRequestBody.get();
|
|
106
|
-
break;
|
|
107
|
-
case HttpMethod.GET:
|
|
108
|
-
case HttpMethod.DELETE:
|
|
109
|
-
object = MemKey_HttpRequestQuery.get();
|
|
110
|
-
break;
|
|
111
|
-
default:
|
|
112
|
-
throw new BadImplementationException(`Generic custom fields cannot be extracted on api with method: ${reqMethod}`);
|
|
113
|
-
}
|
|
114
|
-
_keys(object).filter(key => keys.includes(key)).forEach(key => {
|
|
115
|
-
const oElement = object[key];
|
|
116
|
-
if (oElement === undefined || oElement === null)
|
|
117
|
-
return;
|
|
118
|
-
if (typeof oElement !== 'string')
|
|
119
|
-
return;
|
|
120
|
-
customFields[key] = oElement;
|
|
121
|
-
});
|
|
122
|
-
const projectId = this.projectId;
|
|
123
|
-
await action(projectId, customFields);
|
|
53
|
+
createAssertionContext() {
|
|
54
|
+
const userPerms = MemKey_UserScopePermissions.get();
|
|
55
|
+
const entityContexts = MemKey_UserEntityContexts.get();
|
|
56
|
+
return {
|
|
57
|
+
hasScope: (scope, value) => {
|
|
58
|
+
const prefix = scope.key + ':';
|
|
59
|
+
const entry = userPerms.find(p => p.startsWith(prefix));
|
|
60
|
+
if (!entry)
|
|
61
|
+
return false;
|
|
62
|
+
const userValue = entry.substring(prefix.length);
|
|
63
|
+
const requiredIdx = scope.values.indexOf(value);
|
|
64
|
+
if (requiredIdx === -1)
|
|
65
|
+
return false;
|
|
66
|
+
const userIdx = scope.values.indexOf(userValue);
|
|
67
|
+
return userIdx >= requiredIdx;
|
|
68
|
+
},
|
|
69
|
+
ownsEntity: async (pointer) => {
|
|
70
|
+
return entityContexts.some(ctx => ctx.dbKey === pointer.dbKey && ctx.id === pointer.id);
|
|
71
|
+
},
|
|
72
|
+
and: async (...predicates) => {
|
|
73
|
+
const results = await Promise.all(predicates);
|
|
74
|
+
return results.every(r => r);
|
|
75
|
+
},
|
|
76
|
+
or: async (...predicates) => {
|
|
77
|
+
const results = await Promise.all(predicates);
|
|
78
|
+
return results.some(r => r);
|
|
79
|
+
},
|
|
124
80
|
};
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
}
|
|
128
|
-
init() {
|
|
129
|
-
super.init();
|
|
130
|
-
_keys(this._keys).forEach(key => this.permissionKeys[key] = new PermissionKey_BE(key));
|
|
131
|
-
}
|
|
132
|
-
/**
|
|
133
|
-
* @deprecated Path-based sync filter; use function-based permissions instead. API collection deprecated.
|
|
134
|
-
* Returns a filter for sync manager. The app must call SyncManager.setModuleFilter(ModuleBE_PermissionsAssert.getPermissionsAssertSyncFilter()) when using a sync manager.
|
|
135
|
-
*/
|
|
136
|
-
getPermissionsAssertSyncFilter() {
|
|
137
|
-
const assert = this;
|
|
138
|
-
return async (dbModules) => {
|
|
139
|
-
const userPermissions = MemKey_UserPermissions.get();
|
|
140
|
-
const mapDbNameToApiModules = arrayToMap(RuntimeBE_Modules(), (item) => item.dbModule.dbDef.dbKey);
|
|
141
|
-
const paths = dbModules.map(module => {
|
|
142
|
-
const apiModule = mapDbNameToApiModules[module.dbDef.dbKey];
|
|
143
|
-
if (!apiModule)
|
|
144
|
-
return undefined;
|
|
145
|
-
return apiModule.crudApiDef?.query?.path;
|
|
146
|
-
});
|
|
147
|
-
const _allApis = await ModuleBE_PermissionAPIDB.query.where({});
|
|
148
|
-
const apis = _allApis.filter(_api => paths.includes(_api.path));
|
|
149
|
-
const mapPathToDBApi = arrayToMap(apis, api => api.path);
|
|
150
|
-
return dbModules.filter((dbModule, index) => {
|
|
151
|
-
const path = paths[index];
|
|
152
|
-
if (!path)
|
|
153
|
-
return false;
|
|
154
|
-
const dbApi = mapPathToDBApi[path];
|
|
155
|
-
if (!dbApi)
|
|
156
|
-
return !ModuleBE_PermissionsAssert.isStrictMode();
|
|
157
|
-
const accessLevels = dbApi._accessLevels;
|
|
158
|
-
return _keys(accessLevels).reduce((hasAccess, domainId) => {
|
|
159
|
-
if (!hasAccess)
|
|
160
|
-
return false;
|
|
161
|
-
const userDomainAccessValue = userPermissions[domainId];
|
|
162
|
-
const apiRequiredAccessValue = accessLevels[domainId];
|
|
163
|
-
if (!userDomainAccessValue)
|
|
164
|
-
return false;
|
|
165
|
-
if (!exists(userDomainAccessValue) || userDomainAccessValue < apiRequiredAccessValue) {
|
|
166
|
-
assert.logErrorBold(`${(userDomainAccessValue ?? 0)} < ${apiRequiredAccessValue} === ${(userDomainAccessValue ?? 0) < apiRequiredAccessValue}`);
|
|
167
|
-
return false;
|
|
168
|
-
}
|
|
169
|
-
return hasAccess;
|
|
170
|
-
}, true);
|
|
171
|
-
});
|
|
172
|
-
};
|
|
173
|
-
}
|
|
174
|
-
async assertUserPermissions(body) {
|
|
175
|
-
return this.assertPermission(body);
|
|
176
|
-
}
|
|
177
|
-
assertPermission = async (body) => {
|
|
178
|
-
await ModuleBE_PermissionsAssert.assertPathPermissions(body.projectId, body.path);
|
|
179
|
-
return { userId: MemKey_AccountId.get() };
|
|
180
|
-
};
|
|
181
|
-
/**
|
|
182
|
-
* @deprecated Path-based API permission; use function-based permissions and assertFunctionPermission(def) instead. API collection deprecated.
|
|
183
|
-
*/
|
|
184
|
-
async assertPathPermissions(projectId, path) {
|
|
185
|
-
// [DomainId]: accessLevel's numerical value
|
|
186
|
-
const userPermissions = MemKey_UserPermissions.get();
|
|
187
|
-
const apiDetails = await this.getApiDetails(path, projectId);
|
|
188
|
-
this.logDebug('______________________________');
|
|
189
|
-
this.logDebug(userPermissions);
|
|
190
|
-
this.logDebug('______________________________');
|
|
191
|
-
this.logDebug(apiDetails?.dbApi);
|
|
192
|
-
this.logDebug('______________________________');
|
|
193
|
-
if (!apiDetails || !apiDetails.dbApi.accessLevelIds) {
|
|
194
|
-
if (!this.config.strictMode)
|
|
195
|
-
return;
|
|
196
|
-
throw new ApiException(403, `No permissions configuration specified for api: ${projectId ? `${projectId}--` : ''}${path}`);
|
|
197
|
-
}
|
|
198
|
-
//_accessLevels is a map[domain id <> access level numeric value]
|
|
199
|
-
this.assertUserPassesAccessLevels(apiDetails.dbApi._accessLevels, userPermissions);
|
|
200
|
-
}
|
|
201
|
-
assertUserPassesAccessLevels(domainToLevelValueMap, userPermissions) {
|
|
202
|
-
_keys(domainToLevelValueMap).forEach(domainId => {
|
|
203
|
-
const userDomainPermission = userPermissions[domainId];
|
|
204
|
-
if (!exists(userDomainPermission))
|
|
205
|
-
throw new ApiException(403, 'Missing Access For This Domain');
|
|
206
|
-
if (userDomainPermission < domainToLevelValueMap[domainId]) {
|
|
207
|
-
this.logErrorBold(`for domain - userAccessLevel <> expectedAccessLevel: "${domainId}" ${(userDomainPermission ?? 0)} <> ${domainToLevelValueMap[domainId]}`);
|
|
208
|
-
throw new ApiException(403, 'Action Forbidden');
|
|
209
|
-
}
|
|
210
|
-
});
|
|
211
|
-
}
|
|
212
|
-
/**
|
|
213
|
-
* Asserts that the user has at least the required level for the function-permission def (from @RequirePermission).
|
|
214
|
-
* Call this before invoking a handler when getRequirePermissionDef(handler) returns a def.
|
|
215
|
-
*/
|
|
216
|
-
assertFunctionPermission(def) {
|
|
217
|
-
if (def.domainId === undefined || def.levelValue === undefined)
|
|
218
|
-
throw new ApiException(503, `Function permission "${def.scopeKey}/${def.value}" not yet provisioned; run project setup to create domains/levels from registry.`);
|
|
219
|
-
const userPermissions = MemKey_UserPermissions.get();
|
|
220
|
-
const userDomainPermission = userPermissions[def.domainId];
|
|
221
|
-
if (!exists(userDomainPermission))
|
|
222
|
-
throw new ApiException(403, 'Missing Access For This Domain');
|
|
223
|
-
if (userDomainPermission < def.levelValue) {
|
|
224
|
-
this.logErrorBold(`function permission - userLevel < required: "${def.scopeKey}/${def.value}" ${userDomainPermission} < ${def.levelValue}`);
|
|
225
|
-
throw new ApiException(403, 'Action Forbidden');
|
|
226
|
-
}
|
|
227
|
-
}
|
|
228
|
-
/** @deprecated Path-based API lookup; API collection deprecated. Use function-based permissions. */
|
|
229
|
-
async getApiDetails(_path, projectId) {
|
|
230
|
-
let path = _path.substring(0, (_path + '?').indexOf('?')); //Get raw path without query
|
|
231
|
-
if (path.at(0) === '/')
|
|
232
|
-
path = path.substring(1);
|
|
233
|
-
this.logDebug(`Fetching Permission API for path: ${path} and project id: ${projectId}`);
|
|
234
|
-
const dbApi = (await ModuleBE_PermissionAPIDB.query.custom({
|
|
235
|
-
where: {
|
|
236
|
-
path,
|
|
237
|
-
projectId
|
|
238
|
-
}
|
|
239
|
-
}))[0];
|
|
240
|
-
if (!dbApi)
|
|
241
|
-
return undefined;
|
|
242
|
-
const requestPermissions = await this.getAccessLevels(dbApi.accessLevelIds || []);
|
|
243
|
-
return {
|
|
244
|
-
dbApi,
|
|
245
|
-
requestPermissions
|
|
246
|
-
};
|
|
247
|
-
}
|
|
248
|
-
async getApisDetails(urls, projectId) {
|
|
249
|
-
const paths = urls.map(_path => _path.substring(0, (_path + '?').indexOf('?')));
|
|
250
|
-
const apiDbs = await batchActionParallel(paths, 10, elements => ModuleBE_PermissionAPIDB.query.custom({
|
|
251
|
-
where: {
|
|
252
|
-
projectId,
|
|
253
|
-
path: { $in: elements }
|
|
254
|
-
}
|
|
255
|
-
}));
|
|
256
|
-
return Promise.all(paths.map(async (path) => {
|
|
257
|
-
const apiDb = apiDbs.find(_apiDb => _apiDb.path === path);
|
|
258
|
-
if (!apiDb)
|
|
259
|
-
return;
|
|
260
|
-
try {
|
|
261
|
-
const requestPermissions = await this.getAccessLevels(apiDb.accessLevelIds);
|
|
262
|
-
return ({
|
|
263
|
-
apiDb,
|
|
264
|
-
requestPermissions
|
|
265
|
-
});
|
|
266
|
-
}
|
|
267
|
-
catch (e) {
|
|
268
|
-
return;
|
|
269
|
-
}
|
|
270
|
-
}));
|
|
271
|
-
}
|
|
272
|
-
async getAccessLevels(_accessLevelIds) {
|
|
273
|
-
const accessLevelIds = filterDuplicates(_accessLevelIds || []);
|
|
274
|
-
const requestPermissions = filterInstances(await ModuleBE_PermissionAccessLevelDB.query.all(accessLevelIds));
|
|
275
|
-
const idNotFound = accessLevelIds.find(lId => !requestPermissions.find(r => r._id === lId));
|
|
276
|
-
if (idNotFound)
|
|
277
|
-
throw new ApiException(404, `Could not find api level with _id: ${idNotFound}`);
|
|
278
|
-
return requestPermissions;
|
|
279
|
-
}
|
|
280
|
-
setProjectId = (projectId) => {
|
|
281
|
-
this.projectId = projectId;
|
|
282
|
-
};
|
|
283
|
-
getRegEx(value) {
|
|
284
|
-
if (!value)
|
|
285
|
-
return new RegExp(`^${value}$`, 'g');
|
|
286
|
-
let regExValue = value;
|
|
287
|
-
const startRegEx = '^';
|
|
288
|
-
const endRegEx = '$';
|
|
289
|
-
if (value[0] !== startRegEx)
|
|
290
|
-
regExValue = startRegEx + regExValue;
|
|
291
|
-
if (value[value.length - 1] !== endRegEx)
|
|
292
|
-
regExValue = regExValue + endRegEx;
|
|
293
|
-
return new RegExp(regExValue, 'g');
|
|
294
|
-
}
|
|
295
|
-
registerPermissionKeys(keys) {
|
|
296
|
-
keys.forEach(key => {
|
|
297
|
-
if (this._keys[key])
|
|
298
|
-
throw new ImplementationMissingException(`Registered PermissionKey '${key}' more than once!`);
|
|
299
|
-
this._keys[key] = true;
|
|
300
|
-
});
|
|
301
|
-
}
|
|
302
|
-
isStrictMode() {
|
|
303
|
-
return !!this.config.strictMode;
|
|
304
|
-
}
|
|
305
|
-
};
|
|
306
|
-
})();
|
|
307
|
-
export { ModuleBE_PermissionsAssert_Class };
|
|
81
|
+
}
|
|
82
|
+
}
|
|
308
83
|
export const ModuleBE_PermissionsAssert = new ModuleBE_PermissionsAssert_Class();
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nu-art/permissions-backend",
|
|
3
|
-
"version": "0.500.
|
|
3
|
+
"version": "0.500.6",
|
|
4
4
|
"description": "Permissions Backend",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"TacB0sS",
|
|
@@ -34,13 +34,14 @@
|
|
|
34
34
|
"test": "ts-mocha -w -p src/test/tsconfig.json --timeout 0 --inspect=8107 --watch-files '**/*.ts' src/test/__all-tests.ts"
|
|
35
35
|
},
|
|
36
36
|
"dependencies": {
|
|
37
|
-
"@nu-art/
|
|
38
|
-
"@nu-art/
|
|
39
|
-
"@nu-art/firebase-
|
|
40
|
-
"@nu-art/
|
|
41
|
-
"@nu-art/
|
|
42
|
-
"@nu-art/
|
|
43
|
-
"@nu-art/user-account-
|
|
37
|
+
"@nu-art/action-processor-backend": "0.500.6",
|
|
38
|
+
"@nu-art/permissions-shared": "0.500.6",
|
|
39
|
+
"@nu-art/firebase-backend": "0.500.6",
|
|
40
|
+
"@nu-art/firebase-shared": "0.500.6",
|
|
41
|
+
"@nu-art/google-services-backend": "0.500.6",
|
|
42
|
+
"@nu-art/ts-common": "0.500.6",
|
|
43
|
+
"@nu-art/user-account-backend": "0.500.6",
|
|
44
|
+
"@nu-art/user-account-shared": "0.500.6",
|
|
44
45
|
"express": "^4.18.2",
|
|
45
46
|
"firebase": "^11.9.0",
|
|
46
47
|
"firebase-admin": "13.4.0",
|
|
@@ -50,12 +51,13 @@
|
|
|
50
51
|
"react-dom": "^18.0.0",
|
|
51
52
|
"react-router-dom": "^6.9.0",
|
|
52
53
|
"saml2-js": "^4.0.1",
|
|
53
|
-
"@nu-art/http-server": "
|
|
54
|
-
"@nu-art/api-types": "
|
|
55
|
-
"@nu-art/db-api-backend": "0.500.
|
|
56
|
-
"@nu-art/db-api-shared": "0.500.
|
|
54
|
+
"@nu-art/http-server": "0.500.6",
|
|
55
|
+
"@nu-art/api-types": "0.500.6",
|
|
56
|
+
"@nu-art/db-api-backend": "0.500.6",
|
|
57
|
+
"@nu-art/db-api-shared": "0.500.6"
|
|
57
58
|
},
|
|
58
59
|
"devDependencies": {
|
|
60
|
+
"@nu-art/testalot": "0.500.6",
|
|
59
61
|
"@types/react": "^18.0.0",
|
|
60
62
|
"@types/express": "^4.17.17",
|
|
61
63
|
"@types/react-dom": "^18.0.0",
|
package/PermissionKey_BE.d.ts
DELETED
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
import { Logger } from '@nu-art/ts-common';
|
|
2
|
-
import { DatabaseDef_PermissionDomain, DB_PermissionKeyData } from '@nu-art/permissions-shared';
|
|
3
|
-
type Resolver = (logger?: Logger) => Promise<DB_PermissionKeyData>;
|
|
4
|
-
export declare class PermissionKey_BE<K extends string> {
|
|
5
|
-
readonly key: K;
|
|
6
|
-
readonly resolver: Resolver;
|
|
7
|
-
readonly dataManipulator: (data: DB_PermissionKeyData) => Promise<DB_PermissionKeyData>;
|
|
8
|
-
static _resolver: Resolver;
|
|
9
|
-
static buildData: (data: DB_PermissionKeyData) => Promise<DB_PermissionKeyData>;
|
|
10
|
-
constructor(key: K, initialDataResolver?: Resolver);
|
|
11
|
-
get(): Promise<DB_PermissionKeyData>;
|
|
12
|
-
set(value: DB_PermissionKeyData): Promise<void>;
|
|
13
|
-
}
|
|
14
|
-
export declare const defaultValueResolverV2: (domainId: DatabaseDef_PermissionDomain["id"], accessLevelName: string) => Promise<DB_PermissionKeyData>;
|
|
15
|
-
export declare const defaultValueResolver: (domainNamespace: string, accessLevelValue: number) => Promise<DB_PermissionKeyData>;
|
|
16
|
-
export {};
|
package/PermissionKey_BE.js
DELETED
|
@@ -1,59 +0,0 @@
|
|
|
1
|
-
import { filterInstances } from '@nu-art/ts-common';
|
|
2
|
-
import { ModuleBE_PermissionAccessLevelDB, ModuleBE_PermissionDomainDB } from './_entity.js';
|
|
3
|
-
import { getAppConfigKeyHandler } from './permissions-wire.js';
|
|
4
|
-
import { Const_PermissionKeyType } from '@nu-art/permissions-shared';
|
|
5
|
-
export class PermissionKey_BE {
|
|
6
|
-
key;
|
|
7
|
-
resolver;
|
|
8
|
-
dataManipulator;
|
|
9
|
-
static _resolver = async () => {
|
|
10
|
-
return { type: Const_PermissionKeyType, accessLevelIds: [], _accessLevels: {} };
|
|
11
|
-
};
|
|
12
|
-
static buildData = async (data) => {
|
|
13
|
-
const accessLevels = filterInstances(await ModuleBE_PermissionAccessLevelDB.query.all(data.accessLevelIds));
|
|
14
|
-
return {
|
|
15
|
-
type: 'permission-key',
|
|
16
|
-
accessLevelIds: data.accessLevelIds,
|
|
17
|
-
_accessLevels: accessLevels.reduce((acc, level) => {
|
|
18
|
-
acc[level.domainId] = level.value;
|
|
19
|
-
return acc;
|
|
20
|
-
}, {})
|
|
21
|
-
};
|
|
22
|
-
};
|
|
23
|
-
constructor(key, initialDataResolver) {
|
|
24
|
-
this.key = key;
|
|
25
|
-
this.resolver = initialDataResolver ?? PermissionKey_BE._resolver;
|
|
26
|
-
this.dataManipulator = PermissionKey_BE.buildData;
|
|
27
|
-
getAppConfigKeyHandler()?.registerKey(this);
|
|
28
|
-
}
|
|
29
|
-
async get() {
|
|
30
|
-
const handler = getAppConfigKeyHandler();
|
|
31
|
-
if (!handler)
|
|
32
|
-
throw new Error('AppConfigKeyHandler not set; wire setAppConfigKeyHandler(ModuleBE_AppConfigDB) when using app-config-backend');
|
|
33
|
-
return handler.getAppKey(this);
|
|
34
|
-
}
|
|
35
|
-
async set(value) {
|
|
36
|
-
const dbValue = await PermissionKey_BE.buildData(value);
|
|
37
|
-
const handler = getAppConfigKeyHandler();
|
|
38
|
-
if (!handler)
|
|
39
|
-
throw new Error('AppConfigKeyHandler not set; wire setAppConfigKeyHandler(ModuleBE_AppConfigDB) when using app-config-backend');
|
|
40
|
-
await handler.setAppKey(this, dbValue);
|
|
41
|
-
}
|
|
42
|
-
}
|
|
43
|
-
export const defaultValueResolverV2 = async (domainId, accessLevelName) => {
|
|
44
|
-
const accessLevel = await ModuleBE_PermissionAccessLevelDB.query.uniqueCustom({ where: { domainId, name: accessLevelName } });
|
|
45
|
-
return {
|
|
46
|
-
type: Const_PermissionKeyType,
|
|
47
|
-
accessLevelIds: [accessLevel._id],
|
|
48
|
-
_accessLevels: { [accessLevel._id]: accessLevel.value }
|
|
49
|
-
};
|
|
50
|
-
};
|
|
51
|
-
export const defaultValueResolver = async (domainNamespace, accessLevelValue) => {
|
|
52
|
-
const domain = await ModuleBE_PermissionDomainDB.query.uniqueCustom({ where: { namespace: domainNamespace } });
|
|
53
|
-
const accessLevel = await ModuleBE_PermissionAccessLevelDB.query.uniqueCustom({ where: { domainId: domain._id, value: accessLevelValue } });
|
|
54
|
-
return {
|
|
55
|
-
type: Const_PermissionKeyType,
|
|
56
|
-
accessLevelIds: [accessLevel._id],
|
|
57
|
-
_accessLevels: { [accessLevel._id]: accessLevel.value }
|
|
58
|
-
};
|
|
59
|
-
};
|
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
import { ModuleBE_BaseDB } from '@nu-art/db-api-backend';
|
|
2
|
-
import { Transaction } from 'firebase-admin/firestore';
|
|
3
|
-
import { CollectionActionType, PostWriteProcessingData } from '@nu-art/firebase-backend/firestore-v3/FirestoreCollectionV3';
|
|
4
|
-
import { DatabaseDef_PermissionAccessLevel, DB_PermissionAccessLevel } from '@nu-art/permissions-shared';
|
|
5
|
-
export declare class ModuleBE_PermissionAccessLevelDB_Class extends ModuleBE_BaseDB<DatabaseDef_PermissionAccessLevel> {
|
|
6
|
-
constructor();
|
|
7
|
-
protected preWriteProcessing(dbInstance: DB_PermissionAccessLevel, originalDbInstance: DatabaseDef_PermissionAccessLevel['dbType'], transaction?: Transaction): Promise<void>;
|
|
8
|
-
protected postWriteProcessing(data: PostWriteProcessingData<DatabaseDef_PermissionAccessLevel['dbType']>, actionType: CollectionActionType, transaction?: Transaction): Promise<void>;
|
|
9
|
-
protected assertDeletion(transaction: Transaction, dbInstance: DB_PermissionAccessLevel): Promise<void>;
|
|
10
|
-
private upgrade_100_101;
|
|
11
|
-
}
|
|
12
|
-
export declare const ModuleBE_PermissionAccessLevelDB: ModuleBE_PermissionAccessLevelDB_Class;
|
|
13
|
-
export declare function checkDuplicateLevelsDomain(levels: DB_PermissionAccessLevel[]): void;
|
|
@@ -1,49 +0,0 @@
|
|
|
1
|
-
import { ModuleBE_BaseDB } from '@nu-art/db-api-backend';
|
|
2
|
-
import { ApiException, batchActionParallel, dbObjectToId, filterDuplicates } from '@nu-art/ts-common';
|
|
3
|
-
import { ModuleBE_PermissionAPIDB } from '../permission-api/index.js';
|
|
4
|
-
import { ModuleBE_PermissionDomainDB } from '../permission-domain/index.js';
|
|
5
|
-
import { ModuleBE_PermissionGroupDB } from '../permission-group/index.js';
|
|
6
|
-
import { DBDef_PermissionAccessLevel } from '@nu-art/permissions-shared';
|
|
7
|
-
export class ModuleBE_PermissionAccessLevelDB_Class extends ModuleBE_BaseDB {
|
|
8
|
-
constructor() {
|
|
9
|
-
super(DBDef_PermissionAccessLevel);
|
|
10
|
-
this.registerVersionUpgradeProcessor('1.0.0', this.upgrade_100_101);
|
|
11
|
-
}
|
|
12
|
-
async preWriteProcessing(dbInstance, originalDbInstance, transaction) {
|
|
13
|
-
await ModuleBE_PermissionDomainDB.query.uniqueAssert(dbInstance.domainId);
|
|
14
|
-
}
|
|
15
|
-
async postWriteProcessing(data, actionType, transaction) {
|
|
16
|
-
const deleted = data.deleted ? (Array.isArray(data.deleted) ? data.deleted : [data.deleted]) : [];
|
|
17
|
-
const updated = data.updated ? (Array.isArray(data.updated) ? data.updated : [data.updated]) : [];
|
|
18
|
-
//Collect all apis that hold an access level id in the levels that have changed
|
|
19
|
-
const deletedIds = deleted.map(dbObjectToId);
|
|
20
|
-
const levelIds = [...deletedIds, ...updated.map(dbObjectToId)];
|
|
21
|
-
const _connectedApis = await batchActionParallel(levelIds, 10, async (ids) => await ModuleBE_PermissionAPIDB.query.custom({ where: { accessLevelIds: { $aca: ids } } }));
|
|
22
|
-
const connectedApis = filterDuplicates(_connectedApis, api => api._id);
|
|
23
|
-
deletedIds.forEach(id => {
|
|
24
|
-
//For each deleted level remove it from any api that held it
|
|
25
|
-
connectedApis.forEach(api => {
|
|
26
|
-
api.accessLevelIds = api.accessLevelIds?.filter(i => i !== id);
|
|
27
|
-
});
|
|
28
|
-
});
|
|
29
|
-
//Send all apis to upsert so their _accessLevels update
|
|
30
|
-
await ModuleBE_PermissionAPIDB.set.all(connectedApis);
|
|
31
|
-
return super.postWriteProcessing(data, actionType, transaction);
|
|
32
|
-
}
|
|
33
|
-
async assertDeletion(transaction, dbInstance) {
|
|
34
|
-
const groups = await ModuleBE_PermissionGroupDB.query.custom({ where: { accessLevelIds: { $ac: dbInstance._id } } });
|
|
35
|
-
const apis = await ModuleBE_PermissionAPIDB.query.custom({ where: { accessLevelIds: { $ac: dbInstance._id } } });
|
|
36
|
-
if (groups.length || apis.length)
|
|
37
|
-
throw new ApiException(403, 'You trying delete access level that associated with users/groups/apis, you need delete the associations first');
|
|
38
|
-
}
|
|
39
|
-
upgrade_100_101 = async (items) => {
|
|
40
|
-
items.forEach(accessLevel => accessLevel.uiLabel = accessLevel.name);
|
|
41
|
-
};
|
|
42
|
-
}
|
|
43
|
-
export const ModuleBE_PermissionAccessLevelDB = new ModuleBE_PermissionAccessLevelDB_Class();
|
|
44
|
-
export function checkDuplicateLevelsDomain(levels) {
|
|
45
|
-
const domainIds = levels.map(level => level.domainId);
|
|
46
|
-
const filteredDomainIds = filterDuplicates(domainIds);
|
|
47
|
-
if (filteredDomainIds.length !== domainIds.length)
|
|
48
|
-
throw new ApiException(422, 'You trying test-add-data duplicate accessLevel with the same domain');
|
|
49
|
-
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export declare const ModulePackBE_PermissionAccessLevel: (import("./ModuleBE_PermissionAccessLevelDB.js").ModuleBE_PermissionAccessLevelDB_Class | import("@nu-art/db-api-backend").ModuleBE_BaseApi_Class<import("@nu-art/permissions-shared").DatabaseDef_PermissionAccessLevel>)[];
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import { createApisForDBModule } from '@nu-art/db-api-backend';
|
|
2
|
-
import { ModuleBE_PermissionAccessLevelDB } from './ModuleBE_PermissionAccessLevelDB.js';
|
|
3
|
-
export const ModulePackBE_PermissionAccessLevel = [ModuleBE_PermissionAccessLevelDB, createApisForDBModule(ModuleBE_PermissionAccessLevelDB)];
|