104 lines
2.7 KiB
TypeScript
104 lines
2.7 KiB
TypeScript
import { Organization } from './classes.organization.js';
|
|
import { Reception } from './classes.reception.js';
|
|
import { Role } from './classes.role.js';
|
|
import { User } from './classes.user.js';
|
|
import * as plugins from '../plugins.js';
|
|
|
|
export class RoleManager {
|
|
// INSTANCE
|
|
public receptionRef: Reception;
|
|
public get db() {
|
|
return this.receptionRef.db.smartdataDb;
|
|
}
|
|
public CRole = plugins.smartdata.setDefaultManagerForDoc(this, Role);
|
|
constructor(receptionRefArg: Reception) {
|
|
this.receptionRef = receptionRefArg;
|
|
}
|
|
|
|
/**
|
|
* Create, change, or delete a role for a user in an organization.
|
|
* Supports both old single-role and new multi-role patterns.
|
|
*/
|
|
public async modifyRoleForUserAtOrg(optionsArg: {
|
|
action: 'create' | 'change' | 'delete';
|
|
userId: string;
|
|
organizationId: string;
|
|
/** @deprecated Use `roles` instead */
|
|
role?: string;
|
|
/** Array of roles to assign */
|
|
roles?: string[];
|
|
}) {
|
|
let returnRole: Role;
|
|
|
|
// Support both old single role and new roles array
|
|
const roles = optionsArg.roles || (optionsArg.role ? [optionsArg.role] : ['viewer']);
|
|
|
|
switch (optionsArg.action) {
|
|
case 'create':
|
|
returnRole = new this.CRole();
|
|
returnRole.id = plugins.smartunique.shortId();
|
|
returnRole.data = {
|
|
userId: optionsArg.userId,
|
|
organizationId: optionsArg.organizationId,
|
|
roles: roles,
|
|
};
|
|
await returnRole.save();
|
|
break;
|
|
|
|
case 'change':
|
|
returnRole = await this.CRole.getInstance({
|
|
data: {
|
|
userId: optionsArg.userId,
|
|
organizationId: optionsArg.organizationId,
|
|
},
|
|
});
|
|
if (returnRole) {
|
|
returnRole.data.roles = roles;
|
|
await returnRole.save();
|
|
}
|
|
break;
|
|
|
|
case 'delete':
|
|
returnRole = await this.CRole.getInstance({
|
|
data: {
|
|
userId: optionsArg.userId,
|
|
organizationId: optionsArg.organizationId,
|
|
},
|
|
});
|
|
if (returnRole) {
|
|
await returnRole.delete();
|
|
}
|
|
break;
|
|
}
|
|
return returnRole;
|
|
}
|
|
|
|
public async getRoleForUserAndOrg(userArg: User, orgArg: Organization) {
|
|
const role = await this.CRole.getInstance({
|
|
data: {
|
|
userId: userArg.id,
|
|
organizationId: orgArg.id,
|
|
}
|
|
})
|
|
return role;
|
|
}
|
|
|
|
public async getAllRolesForUser(userArg: User) {
|
|
const roles = await this.CRole.getInstances({
|
|
data: {
|
|
userId: userArg.id
|
|
}
|
|
});
|
|
return roles;
|
|
}
|
|
|
|
public async getAllRolesForOrg(organizationId: string) {
|
|
const roles = await this.CRole.getInstances({
|
|
data: {
|
|
organizationId: organizationId
|
|
}
|
|
});
|
|
return roles;
|
|
}
|
|
}
|