@nu-art/permissions-backend 0.401.9 → 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 +33 -0
- package/RequirePermission.js +56 -0
- 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/user-permissions/ModuleBE_UserPermissionsAPI.js +67 -0
- 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 +24 -0
- package/core/function-permission-registry.js +60 -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 +14 -3
- package/index.js +14 -3
- package/modules/ModuleBE_Permissions.d.ts +63 -72
- package/modules/ModuleBE_Permissions.js +493 -339
- package/modules/ModuleBE_PermissionsAssert.d.ts +7 -38
- package/modules/ModuleBE_PermissionsAssert.js +53 -212
- package/package.json +16 -12
- package/PermissionKey_BE.d.ts +0 -13
- package/PermissionKey_BE.js +0 -48
- package/_entity/permission-access-level/ModuleBE_PermissionAccessLevelDB.d.ts +0 -17
- package/_entity/permission-access-level/ModuleBE_PermissionAccessLevelDB.js +0 -55
- 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 -12
- 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 -15
- package/_entity/permission-domain/ModuleBE_PermissionDomainDB.js +0 -25
- 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 -14
- package/_entity/permission-group/ModuleBE_PermissionGroupDB.js +0 -62
- 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 -10
- 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 -8
- package/_entity/permission-user/ModuleBE_PermissionUserAPI.js +0 -13
- package/_entity/permission-user/ModuleBE_PermissionUserDB.d.ts +0 -37
- package/_entity/permission-user/ModuleBE_PermissionUserDB.js +0 -228
- 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/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 -1
- package/modules/index.js +0 -19
- package/permissions.d.ts +0 -23
- package/permissions.js +0 -159
- package/types.d.ts +0 -28
- /package/{types.js → assertion-types.js} +0 -0
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
import { DBApiConfigV3, ModuleBE_BaseDB } from '@nu-art/thunderstorm-backend';
|
|
2
|
-
import { DB_PermissionDomain, DBProto_PermissionDomain } from '@nu-art/permissions-shared';
|
|
3
|
-
import { Transaction } from 'firebase-admin/firestore';
|
|
4
|
-
type Config = DBApiConfigV3<DBProto_PermissionDomain> & {};
|
|
5
|
-
export declare class ModuleBE_PermissionDomainDB_Class extends ModuleBE_BaseDB<DBProto_PermissionDomain, Config> {
|
|
6
|
-
constructor();
|
|
7
|
-
protected assertDeletion(transaction: Transaction, dbInstance: DB_PermissionDomain): Promise<void>;
|
|
8
|
-
internalFilter(item: DB_PermissionDomain): {
|
|
9
|
-
namespace: string;
|
|
10
|
-
projectId: string;
|
|
11
|
-
}[];
|
|
12
|
-
protected preWriteProcessing(dbInstance: DB_PermissionDomain, originalDbInstance: DBProto_PermissionDomain['dbType'], t?: Transaction): Promise<void>;
|
|
13
|
-
}
|
|
14
|
-
export declare const ModuleBE_PermissionDomainDB: ModuleBE_PermissionDomainDB_Class;
|
|
15
|
-
export {};
|
|
@@ -1,25 +0,0 @@
|
|
|
1
|
-
import { ModuleBE_BaseDB, } from '@nu-art/thunderstorm-backend';
|
|
2
|
-
import { DBDef_PermissionDomain } from '@nu-art/permissions-shared';
|
|
3
|
-
import { ApiException } from '@nu-art/ts-common';
|
|
4
|
-
import { MemKey_AccountId } from '@nu-art/user-account-backend';
|
|
5
|
-
import { ModuleBE_PermissionAccessLevelDB } from '../permission-access-level/index.js';
|
|
6
|
-
import { ModuleBE_PermissionProjectDB } from '../permission-project/index.js';
|
|
7
|
-
export class ModuleBE_PermissionDomainDB_Class extends ModuleBE_BaseDB {
|
|
8
|
-
constructor() {
|
|
9
|
-
super(DBDef_PermissionDomain);
|
|
10
|
-
}
|
|
11
|
-
async assertDeletion(transaction, dbInstance) {
|
|
12
|
-
const accessLevels = await ModuleBE_PermissionAccessLevelDB.query.custom({ where: { domainId: dbInstance._id } });
|
|
13
|
-
if (accessLevels.length) {
|
|
14
|
-
throw new ApiException(403, 'You trying delete domain that associated with accessLevels, you need delete the accessLevels first');
|
|
15
|
-
}
|
|
16
|
-
}
|
|
17
|
-
internalFilter(item) {
|
|
18
|
-
return [{ namespace: item.namespace, projectId: item.projectId }];
|
|
19
|
-
}
|
|
20
|
-
async preWriteProcessing(dbInstance, originalDbInstance, t) {
|
|
21
|
-
await ModuleBE_PermissionProjectDB.query.uniqueAssert(dbInstance.projectId, t);
|
|
22
|
-
dbInstance._auditorId = MemKey_AccountId.get();
|
|
23
|
-
}
|
|
24
|
-
}
|
|
25
|
-
export const ModuleBE_PermissionDomainDB = new ModuleBE_PermissionDomainDB_Class();
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export declare const ModulePackBE_PermissionDomain: (import("./ModuleBE_PermissionDomainDB.js").ModuleBE_PermissionDomainDB_Class | import("@nu-art/thunderstorm-backend").ModuleBE_BaseApi_Class<import("@nu-art/permissions-shared").DBProto_PermissionDomain>)[];
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import { createApisForDBModuleV3 } from '@nu-art/thunderstorm-backend';
|
|
2
|
-
import { ModuleBE_PermissionDomainDB } from './ModuleBE_PermissionDomainDB.js';
|
|
3
|
-
export const ModulePackBE_PermissionDomain = [ModuleBE_PermissionDomainDB, createApisForDBModuleV3(ModuleBE_PermissionDomainDB)];
|
|
@@ -1,14 +0,0 @@
|
|
|
1
|
-
import { DBApiConfigV3, ModuleBE_BaseDB } from '@nu-art/thunderstorm-backend';
|
|
2
|
-
import { DB_PermissionGroup, DBProto_PermissionGroup } from '@nu-art/permissions-shared';
|
|
3
|
-
import { Transaction } from 'firebase-admin/firestore';
|
|
4
|
-
import { CollectionActionType, PostWriteProcessingData } from '@nu-art/firebase-backend/firestore-v3/FirestoreCollectionV3';
|
|
5
|
-
type Config = DBApiConfigV3<DBProto_PermissionGroup> & {};
|
|
6
|
-
export declare class ModuleBE_PermissionGroupDB_Class extends ModuleBE_BaseDB<DBProto_PermissionGroup, Config> {
|
|
7
|
-
constructor();
|
|
8
|
-
protected preWriteProcessing(instance: DB_PermissionGroup, originalDbInstance: DBProto_PermissionGroup['dbType'], t?: Transaction): Promise<void>;
|
|
9
|
-
protected postWriteProcessing(data: PostWriteProcessingData<DBProto_PermissionGroup>, actionType: CollectionActionType): Promise<void>;
|
|
10
|
-
private clearUnused;
|
|
11
|
-
private upgrade_100_101;
|
|
12
|
-
}
|
|
13
|
-
export declare const ModuleBE_PermissionGroupDB: ModuleBE_PermissionGroupDB_Class;
|
|
14
|
-
export {};
|
|
@@ -1,62 +0,0 @@
|
|
|
1
|
-
import { ModuleBE_ActionProcessor, ModuleBE_BaseDB, } from '@nu-art/thunderstorm-backend';
|
|
2
|
-
import { DBDef_PermissionGroup } from '@nu-art/permissions-shared';
|
|
3
|
-
import { _keys, ApiException, batchActionParallel, dbObjectToId, filterDuplicates, filterInstances, reduceToMap } from '@nu-art/ts-common';
|
|
4
|
-
import { ModuleBE_PermissionAccessLevelDB } from '../permission-access-level/index.js';
|
|
5
|
-
import { MemKey_AccountId, SlackReporter } from '@nu-art/user-account-backend';
|
|
6
|
-
import { ModuleBE_PermissionUserDB } from '../permission-user/index.js';
|
|
7
|
-
import { _EmptyQuery } from '@nu-art/firebase-shared';
|
|
8
|
-
export class ModuleBE_PermissionGroupDB_Class extends ModuleBE_BaseDB {
|
|
9
|
-
constructor() {
|
|
10
|
-
super(DBDef_PermissionGroup);
|
|
11
|
-
ModuleBE_ActionProcessor.registerAction({
|
|
12
|
-
key: 'clear-unused-permission-groups',
|
|
13
|
-
group: 'Permissions',
|
|
14
|
-
description: 'Clears all permission groups that aren\'t in use',
|
|
15
|
-
processor: this.clearUnused
|
|
16
|
-
}, this);
|
|
17
|
-
this.registerVersionUpgradeProcessor('1.0.0', this.upgrade_100_101);
|
|
18
|
-
}
|
|
19
|
-
async preWriteProcessing(instance, originalDbInstance, t) {
|
|
20
|
-
instance._auditorId = MemKey_AccountId.get();
|
|
21
|
-
const dbLevels = filterInstances(await ModuleBE_PermissionAccessLevelDB.query.all(instance.accessLevelIds, t));
|
|
22
|
-
if (dbLevels.length < instance.accessLevelIds.length) {
|
|
23
|
-
const dbAccessLevelIds = dbLevels.map(dbObjectToId);
|
|
24
|
-
throw new ApiException(404, `Asked to assign a group non existing accessLevels: ${instance.accessLevelIds.filter(id => !dbAccessLevelIds.includes(id))}`);
|
|
25
|
-
}
|
|
26
|
-
// Find if there is more than one access level with the same domainId.
|
|
27
|
-
const duplicationMap = dbLevels.reduce((map, level) => {
|
|
28
|
-
if (map[level.domainId] === undefined)
|
|
29
|
-
map[level.domainId] = 0;
|
|
30
|
-
else
|
|
31
|
-
map[level.domainId]++;
|
|
32
|
-
return map;
|
|
33
|
-
}, {});
|
|
34
|
-
// Get all domainIds that appear more than once in this group
|
|
35
|
-
const duplicateDomainIds = filterInstances(_keys(duplicationMap)
|
|
36
|
-
.map(domainId => duplicationMap[domainId] > 1 ? domainId : undefined));
|
|
37
|
-
if (duplicateDomainIds.length > 0)
|
|
38
|
-
throw new ApiException(400, `Can't add a group with more than one access level per domain: ${duplicateDomainIds}, group: ${instance.label}`);
|
|
39
|
-
instance._levelsMap = reduceToMap(dbLevels, dbLevel => dbLevel.domainId, dbLevel => dbLevel.value);
|
|
40
|
-
}
|
|
41
|
-
async postWriteProcessing(data, actionType) {
|
|
42
|
-
const deleted = data.deleted ? (Array.isArray(data.deleted) ? data.deleted : [data.deleted]) : [];
|
|
43
|
-
const updated = data.updated ? (Array.isArray(data.updated) ? data.updated : [data.updated]) : [];
|
|
44
|
-
const groupIds = filterDuplicates([...deleted, ...updated].map(dbObjectToId));
|
|
45
|
-
const users = await batchActionParallel(groupIds, 10, async (ids) => await ModuleBE_PermissionUserDB.query.custom({ where: { __groupIds: { $aca: ids } } }));
|
|
46
|
-
await ModuleBE_PermissionUserDB.rotateSession(users.map(dbObjectToId));
|
|
47
|
-
}
|
|
48
|
-
clearUnused = async () => {
|
|
49
|
-
let report = 'Report for refactor action *Clean Unused Permission Groups*:\n\n';
|
|
50
|
-
const allPermissionUsers = await ModuleBE_PermissionUserDB.query.custom(_EmptyQuery);
|
|
51
|
-
const allGroups = await this.query.custom(_EmptyQuery);
|
|
52
|
-
const usedGroupIds = allPermissionUsers.map(user => user.__groupIds ?? []).flat();
|
|
53
|
-
const unusedGroups = allGroups.filter(group => !usedGroupIds.includes(group._id));
|
|
54
|
-
report += `Cleared ${unusedGroups.length} groups: ${unusedGroups.map(group => group.label).join(',\n')}`;
|
|
55
|
-
await this.delete.allItems(unusedGroups);
|
|
56
|
-
await new SlackReporter(report).sendReportToChannel();
|
|
57
|
-
};
|
|
58
|
-
upgrade_100_101 = async (items) => {
|
|
59
|
-
items.forEach(group => group.uiLabel = group.label);
|
|
60
|
-
};
|
|
61
|
-
}
|
|
62
|
-
export const ModuleBE_PermissionGroupDB = new ModuleBE_PermissionGroupDB_Class();
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export declare const ModulePackBE_PermissionGroup: (import("./ModuleBE_PermissionGroupDB.js").ModuleBE_PermissionGroupDB_Class | import("@nu-art/thunderstorm-backend").ModuleBE_BaseApi_Class<import("@nu-art/permissions-shared").DBProto_PermissionGroup>)[];
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import { createApisForDBModuleV3 } from '@nu-art/thunderstorm-backend';
|
|
2
|
-
import { ModuleBE_PermissionGroupDB } from './ModuleBE_PermissionGroupDB.js';
|
|
3
|
-
export const ModulePackBE_PermissionGroup = [ModuleBE_PermissionGroupDB, createApisForDBModuleV3(ModuleBE_PermissionGroupDB)];
|
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
import { DBApiConfigV3, ModuleBE_BaseDB } from '@nu-art/thunderstorm-backend';
|
|
2
|
-
import { DB_PermissionProject, DBProto_PermissionProject } from '@nu-art/permissions-shared';
|
|
3
|
-
import { Transaction } from 'firebase-admin/firestore';
|
|
4
|
-
type Config = DBApiConfigV3<DBProto_PermissionProject> & {};
|
|
5
|
-
export declare class ModuleBE_PermissionProjectDB_Class extends ModuleBE_BaseDB<DBProto_PermissionProject, Config> {
|
|
6
|
-
constructor();
|
|
7
|
-
protected preWriteProcessing(dbInstance: DB_PermissionProject, originalDbInstance: DBProto_PermissionProject['dbType'], t?: Transaction): Promise<void>;
|
|
8
|
-
}
|
|
9
|
-
export declare const ModuleBE_PermissionProjectDB: ModuleBE_PermissionProjectDB_Class;
|
|
10
|
-
export {};
|
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
import { ModuleBE_BaseDB, } from '@nu-art/thunderstorm-backend';
|
|
2
|
-
import { DBDef_PermissionProject } from '@nu-art/permissions-shared';
|
|
3
|
-
import { MemKey_AccountId } from '@nu-art/user-account-backend';
|
|
4
|
-
export class ModuleBE_PermissionProjectDB_Class extends ModuleBE_BaseDB {
|
|
5
|
-
constructor() {
|
|
6
|
-
super(DBDef_PermissionProject);
|
|
7
|
-
}
|
|
8
|
-
async preWriteProcessing(dbInstance, originalDbInstance, t) {
|
|
9
|
-
dbInstance._auditorId = MemKey_AccountId.get();
|
|
10
|
-
}
|
|
11
|
-
}
|
|
12
|
-
export const ModuleBE_PermissionProjectDB = new ModuleBE_PermissionProjectDB_Class();
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export declare const ModulePackBE_PermissionProject: (import("./ModuleBE_PermissionProjectDB.js").ModuleBE_PermissionProjectDB_Class | import("@nu-art/thunderstorm-backend").ModuleBE_BaseApi_Class<import("@nu-art/permissions-shared").DBProto_PermissionProject>)[];
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import { createApisForDBModuleV3 } from '@nu-art/thunderstorm-backend';
|
|
2
|
-
import { ModuleBE_PermissionProjectDB } from './ModuleBE_PermissionProjectDB.js';
|
|
3
|
-
export const ModulePackBE_PermissionProject = [ModuleBE_PermissionProjectDB, createApisForDBModuleV3(ModuleBE_PermissionProjectDB)];
|
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
import { ModuleBE_BaseApi_Class } from '@nu-art/thunderstorm-backend';
|
|
2
|
-
import { DBProto_PermissionUser } from '@nu-art/permissions-shared';
|
|
3
|
-
declare class ModuleBE_PermissionUserAPI_Class extends ModuleBE_BaseApi_Class<DBProto_PermissionUser> {
|
|
4
|
-
constructor();
|
|
5
|
-
init(): void;
|
|
6
|
-
}
|
|
7
|
-
export declare const ModuleBE_PermissionUserAPI: ModuleBE_PermissionUserAPI_Class;
|
|
8
|
-
export {};
|
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
import { addRoutes, createBodyServerApi, ModuleBE_BaseApi_Class } from '@nu-art/thunderstorm-backend';
|
|
2
|
-
import { ApiDef_PermissionUser } from '@nu-art/permissions-shared';
|
|
3
|
-
import { ModuleBE_PermissionUserDB } from './ModuleBE_PermissionUserDB.js';
|
|
4
|
-
class ModuleBE_PermissionUserAPI_Class extends ModuleBE_BaseApi_Class {
|
|
5
|
-
constructor() {
|
|
6
|
-
super(ModuleBE_PermissionUserDB);
|
|
7
|
-
}
|
|
8
|
-
init() {
|
|
9
|
-
super.init();
|
|
10
|
-
addRoutes([createBodyServerApi(ApiDef_PermissionUser._v1.assignPermissions, ModuleBE_PermissionUserDB.assignPermissions)]);
|
|
11
|
-
}
|
|
12
|
-
}
|
|
13
|
-
export const ModuleBE_PermissionUserAPI = new ModuleBE_PermissionUserAPI_Class();
|
|
@@ -1,37 +0,0 @@
|
|
|
1
|
-
import { DBApiConfigV3, ModuleBE_BaseDB } from '@nu-art/thunderstorm-backend';
|
|
2
|
-
import { DB_PermissionUser, DBProto_PermissionUser, Request_AssignPermissions } from '@nu-art/permissions-shared';
|
|
3
|
-
import { PerformProjectSetup } from '@nu-art/thunderstorm-backend/modules/action-processor/Action_SetupProject';
|
|
4
|
-
import { DB_BaseObject, UniqueId } from '@nu-art/ts-common';
|
|
5
|
-
import { OnAccountDeleted, OnNewUserRegistered, OnUserLogin } from '@nu-art/user-account-backend';
|
|
6
|
-
import { Transaction } from 'firebase-admin/firestore';
|
|
7
|
-
import { SafeDB_Account, UI_Account } from '@nu-art/user-account-shared';
|
|
8
|
-
import { CollectionActionType, PostWriteProcessingData } from '@nu-art/firebase-backend/firestore-v3/FirestoreCollectionV3';
|
|
9
|
-
type Config = DBApiConfigV3<DBProto_PermissionUser> & {
|
|
10
|
-
defaultPermissionGroupIds?: UniqueId[];
|
|
11
|
-
};
|
|
12
|
-
export declare class ModuleBE_PermissionUserDB_Class extends ModuleBE_BaseDB<DBProto_PermissionUser, Config> implements OnNewUserRegistered, OnUserLogin, PerformProjectSetup, OnAccountDeleted {
|
|
13
|
-
constructor();
|
|
14
|
-
__performProjectSetup(): {
|
|
15
|
-
priority: number;
|
|
16
|
-
processor: () => Promise<void>;
|
|
17
|
-
};
|
|
18
|
-
__onUserLogin(account: UI_Account, transaction: Transaction): Promise<void>;
|
|
19
|
-
__onNewUserRegistered(account: UI_Account, transaction: Transaction): Promise<void>;
|
|
20
|
-
__onAccountDeleted: (account: SafeDB_Account, transaction: Transaction) => Promise<void>;
|
|
21
|
-
protected preWriteProcessing(instance: DB_PermissionUser, originalDbInstance: DBProto_PermissionUser['dbType'], t?: Transaction): Promise<void>;
|
|
22
|
-
protected postWriteProcessing(data: PostWriteProcessingData<DBProto_PermissionUser>, actionType: CollectionActionType): Promise<void>;
|
|
23
|
-
insertIfNotExist: (uiAccount: UI_Account & DB_BaseObject, transaction: Transaction) => Promise<DB_PermissionUser | (Omit<DB_PermissionUser, "_id" | "__metadata1" | "__hardDelete" | "__created" | "__updated" | "_v" | "_originDocId" | ("_auditorId" | "__groupIds")> & Partial<import("@nu-art/ts-common").SubsetObjectByKeys<DB_PermissionUser, "_id" | "__metadata1" | "__hardDelete" | "__created" | "__updated" | "_v" | "_originDocId" | ("_auditorId" | "__groupIds")>> & Partial<import("@nu-art/ts-common").DB_Object>)>;
|
|
24
|
-
assignPermissions(body: Request_AssignPermissions): Promise<void>;
|
|
25
|
-
private getDefaultPermissionGroups;
|
|
26
|
-
/**
|
|
27
|
-
* The system requires to perform action, which in other cases can also be done by a human.
|
|
28
|
-
* This requires system features to identify as a bot user, or "Service Account"
|
|
29
|
-
*
|
|
30
|
-
* @param serviceAccounts - List of Accounts to create
|
|
31
|
-
* @private
|
|
32
|
-
*/
|
|
33
|
-
private createSystemServiceAccount;
|
|
34
|
-
rotateSession(accountIds: UniqueId[]): Promise<void>;
|
|
35
|
-
}
|
|
36
|
-
export declare const ModuleBE_PermissionUserDB: ModuleBE_PermissionUserDB_Class;
|
|
37
|
-
export {};
|
|
@@ -1,228 +0,0 @@
|
|
|
1
|
-
import { MemKey_ServerApi, ModuleBE_BaseDB, Storm, } from '@nu-art/thunderstorm-backend';
|
|
2
|
-
import { DBDef_PermissionUser } from '@nu-art/permissions-shared';
|
|
3
|
-
import { _keys, ApiException, asOptionalArray, batchAction, batchActionParallel, dbObjectToId, exists, filterDuplicates, filterInstances, filterKeys, flatArray, JwtTools, merge, Year } from '@nu-art/ts-common';
|
|
4
|
-
import { ModuleBE_PermissionGroupDB } from '../permission-group/ModuleBE_PermissionGroupDB.js';
|
|
5
|
-
import { MemKey_AccountId, ModuleBE_AccountDB, ModuleBE_SessionDB } from '@nu-art/user-account-backend';
|
|
6
|
-
import { MemKey_UserPermissions } from '../../consts.js';
|
|
7
|
-
import { dispatcher_collectServiceAccounts } from '@nu-art/thunderstorm-backend/modules/_tdb/service-accounts';
|
|
8
|
-
export class ModuleBE_PermissionUserDB_Class extends ModuleBE_BaseDB {
|
|
9
|
-
constructor() {
|
|
10
|
-
super(DBDef_PermissionUser);
|
|
11
|
-
}
|
|
12
|
-
__performProjectSetup() {
|
|
13
|
-
return {
|
|
14
|
-
priority: 200,
|
|
15
|
-
processor: async () => {
|
|
16
|
-
const accounts = await ModuleBE_AccountDB.query.where({});
|
|
17
|
-
const permissionsUser = await this.query.all(accounts.map(dbObjectToId));
|
|
18
|
-
const usersToUpsert = [];
|
|
19
|
-
const usersToDelete = [];
|
|
20
|
-
permissionsUser.forEach((user, index) => {
|
|
21
|
-
if (exists(user)) {
|
|
22
|
-
if (!exists(accounts.find(account => account._id === user._id)))
|
|
23
|
-
usersToDelete.push(user);
|
|
24
|
-
return;
|
|
25
|
-
}
|
|
26
|
-
usersToUpsert.push({
|
|
27
|
-
_id: accounts[index]._id,
|
|
28
|
-
groups: [],
|
|
29
|
-
});
|
|
30
|
-
});
|
|
31
|
-
await this.set.all(usersToUpsert);
|
|
32
|
-
await this.delete.all(usersToDelete);
|
|
33
|
-
// This stage updates the rtdb's config- which is why it's last. Changing the rtdb's config kills the server.
|
|
34
|
-
const serviceAccounts = flatArray(dispatcher_collectServiceAccounts.dispatchModule());
|
|
35
|
-
await this.createSystemServiceAccount(serviceAccounts);
|
|
36
|
-
}
|
|
37
|
-
};
|
|
38
|
-
}
|
|
39
|
-
async __onUserLogin(account, transaction) {
|
|
40
|
-
await this.insertIfNotExist(account, transaction);
|
|
41
|
-
}
|
|
42
|
-
async __onNewUserRegistered(account, transaction) {
|
|
43
|
-
await this.insertIfNotExist(account, transaction);
|
|
44
|
-
}
|
|
45
|
-
__onAccountDeleted = async (account, transaction) => {
|
|
46
|
-
await this.delete.unique(account._id, transaction);
|
|
47
|
-
};
|
|
48
|
-
// protected async canDeleteDocument(transaction: FirestoreTransaction, dbInstances: DB_PermissionUser[]) {
|
|
49
|
-
// const conflicts: DB_PermissionUser[] = [];
|
|
50
|
-
// const accounts = await ModuleBE_AccountDB.query.custom(_EmptyQuery);
|
|
51
|
-
//
|
|
52
|
-
// for (const item of dbInstances) {
|
|
53
|
-
// const account = accounts.find(acc => acc._id === item.accountId);
|
|
54
|
-
// if (account)
|
|
55
|
-
// conflicts.push(item);
|
|
56
|
-
// }
|
|
57
|
-
//
|
|
58
|
-
// if (conflicts.length)
|
|
59
|
-
// throw new ApiException<DB_EntityDependency<any>[]>(422, 'permission users are connected to accounts').setErrorBody({
|
|
60
|
-
// type: 'has-dependencies',
|
|
61
|
-
// body: conflicts.map(conflict => ({collectionKey: 'User', conflictingIds: [conflict._id]}))
|
|
62
|
-
// });
|
|
63
|
-
// }
|
|
64
|
-
async preWriteProcessing(instance, originalDbInstance, t) {
|
|
65
|
-
instance._auditorId = MemKey_AccountId.get();
|
|
66
|
-
instance.__groupIds = filterDuplicates(instance.groups.map(group => group.groupId) || []);
|
|
67
|
-
if (!instance.__groupIds.length)
|
|
68
|
-
return;
|
|
69
|
-
// Get all groups the user has from the collection
|
|
70
|
-
const dbGroups = filterInstances(await ModuleBE_PermissionGroupDB.query.all(instance.__groupIds, t));
|
|
71
|
-
// Verify all groups actually existing in the collection
|
|
72
|
-
if (instance.__groupIds.length !== dbGroups.length) {
|
|
73
|
-
const dbGroupIds = dbGroups.map(dbObjectToId);
|
|
74
|
-
throw new ApiException(422, `Trying to assign a user to a permission-group that does not exist: ${instance.__groupIds.filter(groupId => !dbGroupIds.includes(groupId))}`);
|
|
75
|
-
}
|
|
76
|
-
//todo check for duplications in data
|
|
77
|
-
}
|
|
78
|
-
async postWriteProcessing(data, actionType) {
|
|
79
|
-
const deleted = asOptionalArray(data.deleted) ?? [];
|
|
80
|
-
const updated = asOptionalArray(data.updated) ?? [];
|
|
81
|
-
const beforeIds = (asOptionalArray(data.before) ?? []).map(before => before?._id);
|
|
82
|
-
const accountIdToInvalidate = filterDuplicates(filterInstances([...deleted, ...updated].map(i => i?._id))).filter(id => beforeIds.includes(id));
|
|
83
|
-
await this.rotateSession(accountIdToInvalidate);
|
|
84
|
-
}
|
|
85
|
-
insertIfNotExist = async (uiAccount, transaction) => {
|
|
86
|
-
const create = async (transaction) => {
|
|
87
|
-
const defaultPermissionGroups = await this.getDefaultPermissionGroups();
|
|
88
|
-
const permissionsUserToCreate = {
|
|
89
|
-
_id: uiAccount._id,
|
|
90
|
-
groups: defaultPermissionGroups.map(group => ({ groupId: group._id })),
|
|
91
|
-
_auditorId: MemKey_AccountId.get()
|
|
92
|
-
};
|
|
93
|
-
return ModuleBE_PermissionUserDB.create.item(permissionsUserToCreate, transaction);
|
|
94
|
-
};
|
|
95
|
-
return ModuleBE_PermissionUserDB.collection.uniqueGetOrCreate({ _id: uiAccount._id }, create, transaction);
|
|
96
|
-
};
|
|
97
|
-
async assignPermissions(body) {
|
|
98
|
-
if (!body.targetAccountIds.length)
|
|
99
|
-
throw new ApiException(400, `Asked to modify permissions but provided no users to modify permissions of.`);
|
|
100
|
-
const usersToGiveTo = filterInstances(await this.query.all(body.targetAccountIds));
|
|
101
|
-
// console.log('assignPermissions target accounts ');
|
|
102
|
-
// console.log(await this.query.custom(_EmptyQuery));
|
|
103
|
-
if (!usersToGiveTo.length || usersToGiveTo.length !== body.targetAccountIds.length) {
|
|
104
|
-
const dbUserIds = usersToGiveTo.map(dbObjectToId);
|
|
105
|
-
throw new ApiException(404, `Asked to give permissions to non-existent user accounts: ${body.targetAccountIds.filter(id => !dbUserIds.includes(id))}`);
|
|
106
|
-
}
|
|
107
|
-
const dbGroups = filterInstances(await ModuleBE_PermissionGroupDB.query.all(body.permissionGroupIds));
|
|
108
|
-
if (dbGroups.length !== body.permissionGroupIds.length) {
|
|
109
|
-
const dbGroupIds = dbGroups.map(dbObjectToId);
|
|
110
|
-
throw new ApiException(404, `Asked to give users non-existing permission groups: ${body.permissionGroupIds.filter(id => !dbGroupIds.includes(id))}`);
|
|
111
|
-
}
|
|
112
|
-
const myUserPermissions = MemKey_UserPermissions.get();
|
|
113
|
-
const permissionsToGive = dbGroups.reduce((map, group) => {
|
|
114
|
-
// Gather the highest permissions for each domain, from all groups
|
|
115
|
-
_keys(group._levelsMap || []).forEach(domainId => {
|
|
116
|
-
if (map[domainId] === undefined)
|
|
117
|
-
map[domainId] = 0;
|
|
118
|
-
if (map[domainId] < group._levelsMap[domainId])
|
|
119
|
-
map[domainId] = group._levelsMap[domainId];
|
|
120
|
-
});
|
|
121
|
-
return map;
|
|
122
|
-
}, {});
|
|
123
|
-
const failedDomains = _keys(permissionsToGive).filter(domainId => {
|
|
124
|
-
const tooLowPermission = myUserPermissions[domainId] < permissionsToGive[domainId];
|
|
125
|
-
this.logError(`${myUserPermissions[domainId]} < ${permissionsToGive[domainId]} === ${tooLowPermission}`);
|
|
126
|
-
const noPermissionInThisDomain = myUserPermissions[domainId] === undefined;
|
|
127
|
-
return noPermissionInThisDomain || tooLowPermission;
|
|
128
|
-
});
|
|
129
|
-
if (failedDomains.length)
|
|
130
|
-
throw new ApiException(403, `Attempted to give higher permissions than current user has: ${failedDomains}`);
|
|
131
|
-
const groupIds = dbGroups.map(group => ({ groupId: group._id }));
|
|
132
|
-
const usersToUpdate = usersToGiveTo.map(user => {
|
|
133
|
-
user.groups = groupIds;
|
|
134
|
-
return user;
|
|
135
|
-
});
|
|
136
|
-
await this.set.multi(usersToUpdate);
|
|
137
|
-
}
|
|
138
|
-
getDefaultPermissionGroups = async () => {
|
|
139
|
-
if (!this.config.defaultPermissionGroupIds?.length)
|
|
140
|
-
return [];
|
|
141
|
-
return ModuleBE_PermissionGroupDB.query.where({ _id: { $in: this.config.defaultPermissionGroupIds } });
|
|
142
|
-
};
|
|
143
|
-
/**
|
|
144
|
-
* The system requires to perform action, which in other cases can also be done by a human.
|
|
145
|
-
* This requires system features to identify as a bot user, or "Service Account"
|
|
146
|
-
*
|
|
147
|
-
* @param serviceAccounts - List of Accounts to create
|
|
148
|
-
* @private
|
|
149
|
-
*/
|
|
150
|
-
async createSystemServiceAccount(serviceAccounts) {
|
|
151
|
-
this.logInfoBold('Creating Service Accounts: ', serviceAccounts);
|
|
152
|
-
// @ts-ignore
|
|
153
|
-
const tokenCreator = ModuleBE_AccountDB.token.create;
|
|
154
|
-
const envConfigRef = Storm.getInstance().getGlobalEnvConfigRef();
|
|
155
|
-
const updatedConfig = {};
|
|
156
|
-
//Run over all service accounts
|
|
157
|
-
for (const serviceAccount of serviceAccounts) {
|
|
158
|
-
// Create account if it doesn't already exist
|
|
159
|
-
const accountsToRequest = filterKeys({
|
|
160
|
-
type: 'service',
|
|
161
|
-
email: serviceAccount.email,
|
|
162
|
-
description: serviceAccount.description
|
|
163
|
-
});
|
|
164
|
-
let account;
|
|
165
|
-
//Get or create service account
|
|
166
|
-
try {
|
|
167
|
-
account = await ModuleBE_AccountDB.impl.querySafeAccount({ email: serviceAccount.email });
|
|
168
|
-
}
|
|
169
|
-
catch (e) {
|
|
170
|
-
this.logInfo('NOTICE: querySafeAccount failed, creating accounts');
|
|
171
|
-
account = await ModuleBE_AccountDB.account.create(accountsToRequest);
|
|
172
|
-
}
|
|
173
|
-
// Assign permissions groups to service account
|
|
174
|
-
const permissionsUser = await ModuleBE_PermissionUserDB.query.uniqueAssert({ _id: account._id });
|
|
175
|
-
permissionsUser.groups = serviceAccount.groupIds?.map(groupId => ({ groupId })) || [];
|
|
176
|
-
await ModuleBE_PermissionUserDB.set.item(permissionsUser);
|
|
177
|
-
//Service accounts are only allowed to have one session... but this isn't the defined place to be a cop about it
|
|
178
|
-
const sessions = await ModuleBE_AccountDB.account.getSessions(account);
|
|
179
|
-
//If we have a valid session(not expired) we use its JWT instead of creating a new one
|
|
180
|
-
let validSession;
|
|
181
|
-
for (const session of sessions.sessions) {
|
|
182
|
-
if (await JwtTools.isJwtActive(session.sessionIdJwt)) {
|
|
183
|
-
validSession = session;
|
|
184
|
-
break;
|
|
185
|
-
}
|
|
186
|
-
}
|
|
187
|
-
this.logError(serviceAccount.ttl);
|
|
188
|
-
const token = validSession?.sessionIdJwt ? { token: validSession?.sessionIdJwt } : await tokenCreator({
|
|
189
|
-
accountId: account._id,
|
|
190
|
-
ttl: serviceAccount.ttl ?? Year
|
|
191
|
-
});
|
|
192
|
-
updatedConfig[serviceAccount.moduleName] = {
|
|
193
|
-
serviceAccount: filterKeys({
|
|
194
|
-
token,
|
|
195
|
-
description: serviceAccount.description,
|
|
196
|
-
accountId: account._id,
|
|
197
|
-
email: account.email
|
|
198
|
-
})
|
|
199
|
-
};
|
|
200
|
-
}
|
|
201
|
-
if (_keys(updatedConfig).length > 0)
|
|
202
|
-
MemKey_ServerApi.get().addPostCallAction(async () => {
|
|
203
|
-
const currentConfig = await envConfigRef.get({});
|
|
204
|
-
await envConfigRef.set(merge(currentConfig, updatedConfig));
|
|
205
|
-
this.logInfoBold('Created Service Accounts for', _keys(updatedConfig));
|
|
206
|
-
});
|
|
207
|
-
}
|
|
208
|
-
async rotateSession(accountIds) {
|
|
209
|
-
if (!accountIds.length)
|
|
210
|
-
return;
|
|
211
|
-
//Collect all sessions connected to account
|
|
212
|
-
const sessions = await batchActionParallel(accountIds, 10, async (ids) => await ModuleBE_SessionDB.query.custom({ where: { accountId: { $in: ids } } }));
|
|
213
|
-
//TODO - Make sure new logic in ModuleBE_SessionDB that deletes expired sessions happens before this code, this will be redundant
|
|
214
|
-
//Filter to sessions that aren't expired
|
|
215
|
-
const validSessions = filterInstances(await Promise.all(sessions.map(async (session) => {
|
|
216
|
-
const isExpired = await JwtTools.isJwtExpired(session.sessionIdJwt);
|
|
217
|
-
return isExpired ? undefined : session;
|
|
218
|
-
})));
|
|
219
|
-
//TODO END
|
|
220
|
-
this.logWarning(`#### Rotating ${validSessions.length} Sessions! ####`);
|
|
221
|
-
await batchAction(validSessions, 500, async (sessions) => {
|
|
222
|
-
await this.runTransaction(async (t) => {
|
|
223
|
-
await Promise.all(sessions.map(session => ModuleBE_SessionDB._session.rotate.reissue.bySession(session, t)));
|
|
224
|
-
});
|
|
225
|
-
});
|
|
226
|
-
}
|
|
227
|
-
}
|
|
228
|
-
export const ModuleBE_PermissionUserDB = new ModuleBE_PermissionUserDB_Class();
|
package/_entity.d.ts
DELETED
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
export * from './_entity/permission-access-level/index.js';
|
|
2
|
-
export * from './_entity/permission-access-level/index.js';
|
|
3
|
-
export * from './_entity/permission-api/index.js';
|
|
4
|
-
export * from './_entity/permission-api/index.js';
|
|
5
|
-
export * from './_entity/permission-project/index.js';
|
|
6
|
-
export * from './_entity/permission-project/index.js';
|
|
7
|
-
export * from './_entity/permission-domain/index.js';
|
|
8
|
-
export * from './_entity/permission-domain/index.js';
|
|
9
|
-
export * from './_entity/permission-group/index.js';
|
|
10
|
-
export * from './_entity/permission-group/index.js';
|
|
11
|
-
export * from './_entity/permission-user/index.js';
|
|
12
|
-
export * from './_entity/permission-user/index.js';
|
package/_entity.js
DELETED
|
@@ -1,18 +0,0 @@
|
|
|
1
|
-
//Access Level
|
|
2
|
-
export * from './_entity/permission-access-level/index.js';
|
|
3
|
-
export * from './_entity/permission-access-level/index.js';
|
|
4
|
-
//API
|
|
5
|
-
export * from './_entity/permission-api/index.js';
|
|
6
|
-
export * from './_entity/permission-api/index.js';
|
|
7
|
-
//Project
|
|
8
|
-
export * from './_entity/permission-project/index.js';
|
|
9
|
-
export * from './_entity/permission-project/index.js';
|
|
10
|
-
//Domain
|
|
11
|
-
export * from './_entity/permission-domain/index.js';
|
|
12
|
-
export * from './_entity/permission-domain/index.js';
|
|
13
|
-
//Group
|
|
14
|
-
export * from './_entity/permission-group/index.js';
|
|
15
|
-
export * from './_entity/permission-group/index.js';
|
|
16
|
-
//User
|
|
17
|
-
export * from './_entity/permission-user/index.js';
|
|
18
|
-
export * from './_entity/permission-user/index.js';
|
package/core/utils.d.ts
DELETED
|
@@ -1,25 +0,0 @@
|
|
|
1
|
-
import { TypedMap, UniqueId } from '@nu-art/ts-common';
|
|
2
|
-
import { DefaultDef_Group, PreDBAccessLevel } from '@nu-art/permissions-shared';
|
|
3
|
-
import { PermissionKey_BE } from '../PermissionKey_BE.js';
|
|
4
|
-
import { DefaultDef_Domain, DefaultDef_Package } from '../types.js';
|
|
5
|
-
export declare const Permissions_abTest: (seed: UniqueId, namespace: string, permutations: string[]) => DefaultDef_Package;
|
|
6
|
-
/**
|
|
7
|
-
* Generate automatic BE permission keys for a domain
|
|
8
|
-
* @param accessLevels the relevant access levels to generate keys for
|
|
9
|
-
* @param keyByLevelMapper the key name mapper by access level name
|
|
10
|
-
* @param domainId the domain id to apply in the resolver
|
|
11
|
-
*/
|
|
12
|
-
export declare const generatePermissionKeys: <Key extends string | number | symbol>(accessLevels: PreDBAccessLevel[], keyByLevelMapper: TypedMap<string>, domainId: UniqueId) => { [key in Key]: PermissionKey_BE<string>; };
|
|
13
|
-
/**
|
|
14
|
-
* Automatic generator for domain default definitions,
|
|
15
|
-
* @param key MUST NEVER CHANGE! the key is the "key" to uniqueness of the entire permission decleration
|
|
16
|
-
* @param namespace The name space of the current generated domain definitions
|
|
17
|
-
* @param preDBAccessLevels The access levels to create (can be default or custom)
|
|
18
|
-
* @param permissionKeysByLevel The permission key name for each access level
|
|
19
|
-
* @param dbNames List of db names (optional)
|
|
20
|
-
*/
|
|
21
|
-
export declare const generateDomainDefaults: <Key extends string | number | symbol>(key: string, namespace: string, preDBAccessLevels: PreDBAccessLevel[], permissionKeysByLevel: { [key in Key]: string; }, dbNames?: string[]) => {
|
|
22
|
-
domain: DefaultDef_Domain;
|
|
23
|
-
groups: DefaultDef_Group[];
|
|
24
|
-
keys: { [key in Key]: PermissionKey_BE<string>; };
|
|
25
|
-
};
|