@tomei/sso
Version:
Tomei SSO Package
542 lines (488 loc) • 18.9 kB
text/typescript
import { ClassError, ObjectBase } from '@tomei/general';
import { SystemRepository } from '../system/system.repository';
import { SystemPrivilegeRepository } from './system-privilege.repository';
import { ISystemPrivilegeAttr } from '../../interfaces/system-privilege.interface';
import { LoginUser } from '../login-user/login-user';
import { ApplicationConfig, ComponentConfig } from '@tomei/config';
import { System } from '../system/system';
import { ActionEnum, Activity } from '@tomei/activity-history';
import { ISystemPrivilegeSearch } from '../../interfaces/system-privilege-search.interface';
import { Op } from 'sequelize';
export class SystemPrivilege extends ObjectBase {
ObjectType = 'SystemPrivilege';
TableName = 'sso_SystemPrivilege';
ObjectId: string;
PrivilegeCode: string;
SystemCode: string;
ObjectName: string;
Description: string;
Status: string;
private _CreatedAt: Date;
private _UpdatedAt: Date;
private _CreatedById: number;
private _UpdatedById: number;
get SystemPrivilegeId() {
return this.ObjectId;
}
set SystemPrivilegeId(value: string) {
this.ObjectId = value;
}
get CreatedAt() {
return this._CreatedAt;
}
get UpdatedAt() {
return this._UpdatedAt;
}
get CreatedById() {
return this._CreatedById;
}
get UpdatedById() {
return this._UpdatedById;
}
private static _Repository = new SystemPrivilegeRepository();
private static _SystemRepository = new SystemRepository();
private constructor(systemPrivilegeAttr?: ISystemPrivilegeAttr) {
super();
if (systemPrivilegeAttr) {
this.SystemPrivilegeId = systemPrivilegeAttr.SystemPrivilegeId;
this.PrivilegeCode = systemPrivilegeAttr.PrivilegeCode;
this.SystemCode = systemPrivilegeAttr.SystemCode;
this.Description = systemPrivilegeAttr.Description;
this.Status = systemPrivilegeAttr.Status;
this._CreatedById = systemPrivilegeAttr.CreatedById;
this._CreatedAt = systemPrivilegeAttr.CreatedAt;
this._UpdatedById = systemPrivilegeAttr.UpdatedById;
this._UpdatedAt = systemPrivilegeAttr.UpdatedAt;
}
}
setAttributes(systemPrivilegeAttr: ISystemPrivilegeAttr) {
this.PrivilegeCode = systemPrivilegeAttr.PrivilegeCode;
this.SystemPrivilegeId = systemPrivilegeAttr.SystemPrivilegeId;
this.SystemCode = systemPrivilegeAttr.SystemCode;
this.Description = systemPrivilegeAttr.Description;
this.Status = systemPrivilegeAttr.Status;
this._CreatedAt = systemPrivilegeAttr.CreatedAt;
this._UpdatedAt = systemPrivilegeAttr.UpdatedAt;
this._CreatedById = systemPrivilegeAttr.CreatedById;
this._UpdatedById = systemPrivilegeAttr.UpdatedById;
}
static async init(dbTransaction: any, SystemPrivilegeId?: string) {
try {
const systemPrivilege = new SystemPrivilege();
if (SystemPrivilegeId) {
const systemPrivilegeAttr = await this._Repository.findByPk(
SystemPrivilegeId,
{
transaction: dbTransaction,
},
);
if (systemPrivilegeAttr) {
systemPrivilege.PrivilegeCode = systemPrivilegeAttr.PrivilegeCode;
systemPrivilege.ObjectId = systemPrivilegeAttr.SystemPrivilegeId;
systemPrivilege.SystemCode = systemPrivilegeAttr.SystemCode;
systemPrivilege.Description = systemPrivilegeAttr.Description;
systemPrivilege.Status = systemPrivilegeAttr.Status;
systemPrivilege._CreatedById = systemPrivilegeAttr.CreatedById;
systemPrivilege._CreatedAt = systemPrivilegeAttr.CreatedAt;
systemPrivilege._UpdatedById = systemPrivilegeAttr.UpdatedById;
systemPrivilege._UpdatedAt = systemPrivilegeAttr.UpdatedAt;
} else {
throw new ClassError(
'SystemPrivilege',
'SystemPrivilegeErrMsg00',
'System Privilege Not Found',
);
}
}
return systemPrivilege;
} catch (error) {
throw error;
}
}
static async create(
loginUser: LoginUser,
dbTransaction: any,
systemPrivilege: SystemPrivilege,
) {
try {
//Part 1: Privilege Checking
const systemCode: string =
ApplicationConfig.getComponentConfigValue('system-code');
const isPrivileged = await loginUser.checkPrivileges(
systemCode,
'PRIVILEGE_CREATE',
);
if (!isPrivileged) {
throw new ClassError(
'SystemPrivilege',
'SystemPrivilegeErrMsg01',
'You do not have permission to create system privileges',
);
}
//Part 2: Validation
//Make sure systemCode and PrivilegeCode are not empty
if (!systemPrivilege.SystemCode) {
throw new ClassError(
'SystemPrivilege',
'SystemPrivilegeErrMsg02',
'System Code is required',
);
}
if (!systemPrivilege.PrivilegeCode) {
throw new ClassError(
'SystemPrivilege',
'SystemPrivilegeErrMsg02',
'Privilege Code is required',
);
}
//Call System.init() method by passing systemCode
await System.init(dbTransaction, systemPrivilege.SystemCode);
//Call SystemPrivilege._Repo findByPk
const existingSystemPrivilege = await this._Repository.findByPk(
systemPrivilege.PrivilegeCode,
{
transaction: dbTransaction,
},
);
//If PrivilegeCode found, throw new ClassError
if (existingSystemPrivilege) {
throw new ClassError(
'SystemPrivilege',
'SystemPrivilegeErrMsg03',
'System Privilege already exists',
);
}
//Part 3: Create Privilege
//Initialise new SystemPrivilege instance and populate below
const newSystemPrivilege = new SystemPrivilege();
newSystemPrivilege.ObjectId = newSystemPrivilege.createId();
newSystemPrivilege.PrivilegeCode = systemPrivilege.PrivilegeCode;
newSystemPrivilege.SystemCode = systemPrivilege.SystemCode;
newSystemPrivilege.Description = systemPrivilege.Description;
newSystemPrivilege.Status = 'Active';
newSystemPrivilege._CreatedById = loginUser.UserId;
newSystemPrivilege._UpdatedById = loginUser.UserId;
newSystemPrivilege._CreatedAt = new Date();
newSystemPrivilege._UpdatedAt = new Date();
//Call SystemPrivilege._Repo create method
await this._Repository.create(
{
SystemPrivilegeId: newSystemPrivilege.ObjectId,
PrivilegeCode: newSystemPrivilege.PrivilegeCode,
SystemCode: newSystemPrivilege.SystemCode,
Description: newSystemPrivilege.Description,
Status: newSystemPrivilege.Status,
CreatedById: newSystemPrivilege._CreatedById,
UpdatedById: newSystemPrivilege._UpdatedById,
CreatedAt: newSystemPrivilege._CreatedAt,
UpdatedAt: newSystemPrivilege._UpdatedAt,
},
{
transaction: dbTransaction,
},
);
//Part 4: Record Create Privilege Activity
//Initialise EntityValueBefore variable and set to empty object.
const EntityValueBefore = {};
//Initialise EntityValueAfter variable and set to newSystemPrivilege object.
const EntityValueAfter = newSystemPrivilege;
//Instantiate new activity object and populate
const activity = new Activity();
activity.ActivityId = activity.createId();
activity.Action = ActionEnum.CREATE;
activity.Description = 'Add System Privilege';
activity.EntityType = 'SystemPrivilege';
activity.EntityId = newSystemPrivilege.SystemPrivilegeId;
activity.EntityValueBefore = JSON.stringify(EntityValueBefore);
activity.EntityValueAfter = JSON.stringify(EntityValueAfter);
//Call Activity.create method
await activity.create(loginUser.ObjectId, dbTransaction);
return newSystemPrivilege;
} catch (error) {
throw error;
}
}
public static async findAll(
loginUser: LoginUser,
dbTransaction: any,
page?: number,
row?: number,
search?: ISystemPrivilegeSearch,
) {
try {
// Part 1: Privilege Checking
const systemCode =
ApplicationConfig.getComponentConfigValue('system-code');
const isPrivileged = await loginUser.checkPrivileges(
systemCode,
'PRIVILEGE_LIST',
);
if (!isPrivileged) {
throw new ClassError(
'SystemPrivilege',
'SystemPrivilegeErrMsg01',
'You do not have permission to list system privileges',
);
}
// Part 2: Retrieve listing
const options: any = {
distinct: true,
order: [['createdAt', 'DESC']],
transaction: dbTransaction,
};
//If page and row exist, please add limit and offset to the findAll options
if (page && row) {
const offset = row * (page - 1);
const limit = row;
options.offset = offset;
options.limit = limit;
}
//If search query exists, please set it to sequelize where option.
if (search) {
const queryObj: any = {};
Object.entries(search).forEach(([key, value]) => {
queryObj[key] = {
[Op.substring]: value,
};
});
options.where = queryObj;
}
const result =
await SystemPrivilege._Repository.findAllWithPagination(options);
// Part 3: Return result
// Map the result to SystemPrivilege object
const systemPrivileges: SystemPrivilege[] = [];
for (const systemPrivilegeAttr of result.rows) {
systemPrivileges.push(
new SystemPrivilege(systemPrivilegeAttr.get({ plain: true })),
);
}
return {
count: result.count,
SystemPrivileges: systemPrivileges,
};
} catch (error) {
throw error;
}
}
public static async loadAllPrivileges(
dbTransaction: any,
systemCode: string,
): Promise<string> {
try {
//Instantiate existing System by passing:
// dbTransaction
// SystemCode: Params.SystemCode
await System.init(dbTransaction, systemCode);
// Part 2: Load Privileges
// Load sso component config.loadComponentConfig Call Config. by passing:
// filepath: '/component-config/sso-config.json'
ComponentConfig.loadComponentConfig('./component-config/sso-config.json');
// Retrieve privileges array by call Config.getComponentConfigValue by passing:
// componentName: '@tomei/sso'
// configKey: 'privileges'
const privilegesConfig: {
privilegeCode: string;
description: string;
}[] = ComponentConfig.getComponentConfigValue('@tomei/sso', 'privileges');
// Retrieve system user id. Call Config.getComponentConfigValue by passing:
// componentName: '@tomei/sso'
// configKey: 'system'
const systemConfig: {
name: string;
code: string;
description: string;
userId: string;
} = ComponentConfig.getComponentConfigValue('@tomei/sso', 'system');
//Set systemUserId to system.userId.
const systemUserId = systemConfig.userId;
//Retrieve existing SystemPrivilege. Call SystemPrivilege._Repo findAll method by passing:
// where:
// SystemCode: Params.SystemCode
const existingSystemPrivileges = await this._Repository.findAll({
where: {
SystemCode: systemCode,
},
transaction: dbTransaction,
});
//Filter out existing privileges with the privileges array above to identify which privileges to be created and map it tobeCreatePrivileges.
const tobeCreatePrivileges = privilegesConfig.filter(
(privilegeConfig) =>
!existingSystemPrivileges.find(
(existingPrivilege) =>
existingPrivilege.PrivilegeCode === privilegeConfig.privilegeCode,
),
);
//Call SystemPrivilege._Repo create method for each newPrivileges.
const np = new SystemPrivilege();
for (const privilegeConfig of tobeCreatePrivileges) {
await this._Repository.create(
{
SystemPrivilegeId: np.createId(),
PrivilegeCode: privilegeConfig.privilegeCode,
SystemCode: systemCode,
Description: privilegeConfig.description,
Status: 'Active',
CreatedById: parseInt(systemUserId),
UpdatedById: parseInt(systemUserId),
CreatedAt: new Date(),
UpdatedAt: new Date(),
},
{
transaction: dbTransaction,
},
);
}
return 'Privileges Loaded';
} catch (error) {
throw error;
}
}
public async update(
loginUser: LoginUser, //The user object representing the currently logged-in user.
dbTransaction: any, //The database transaction instance for managing the transaction scope.
privilege: {
PrivilegeCode?: string;
Description?: string;
SystemCode?: string; //The System Code for System Privilege
Status?: string; //The new privilege status (Active/Inactive) for the system privilege
},
) {
try {
// Part 1: Update System Privilege
// Call the SystemPrivilege._Repo.update() method to perform the update operation, passing:
// - SystemCode: The new SystemCode.
// - Status: The new status.
// - UpdatedById: loginUser.UserId (to indicate who updated the record).
// - UpdatedAt: Set to the current date and time.
// - dbTransaction: The database transaction instance.
const entityValueBefore = {
SystemPrivilegeId: this.SystemPrivilegeId,
Description: this.Description,
PrivilegeCode: this.PrivilegeCode,
SystemCode: this.SystemCode,
Status: this.Status,
CreatedById: this.CreatedById,
CreatedAt: this.CreatedAt,
UpdatedById: this.UpdatedById,
UpdatedAt: this.UpdatedAt,
};
await SystemPrivilege._Repository.update(
{
PrivilegeCode: privilege.PrivilegeCode || this.PrivilegeCode,
Description: privilege.Description || this.Description,
SystemCode: privilege.SystemCode || this.SystemCode,
Status: privilege.Status || this.Status,
UpdatedById: loginUser.UserId,
UpdatedAt: new Date(),
},
{
where: {
SystemPrivilegeId: this.SystemPrivilegeId,
},
transaction: dbTransaction,
},
);
const entityValueAfter = {
SystemPrivilegeId: this.SystemPrivilegeId,
PrivilegeCode: privilege.PrivilegeCode || this.PrivilegeCode,
Description: privilege.Description || this.Description,
SystemCode: privilege.SystemCode || this.SystemCode,
Status: privilege.Status || this.Status,
CreatedById: this.CreatedById,
CreatedAt: this.CreatedAt,
UpdatedById: this.UpdatedById,
UpdatedAt: this.UpdatedAt,
};
// Part 2: Record Activity History
// Initialize a variable entityValueBefore to store the current state of the user privilege record before the update.
// Create an instance of the Activity class and set the following properties:
// - ActivityId: Call activity.createId().
// - Action: Set to ActionEnum.Update.
// - Description: Set to Update System Privilege.
// - EntityType: Set to SystemPrivilege.
// - EntityId: Use the ID of the updated user privilege record.
// - EntityValueBefore: Stringify entityValueBefore to capture the state before the update.
// - EntityValueAfter: Stringify the updated user privilege record to capture the new state after the update.
// Call the activity create method with the following parameters:
// - dbTransaction
// - userId: loginUser.UserId
const activity = new Activity();
activity.ActivityId = activity.createId();
activity.Action = ActionEnum.UPDATE;
activity.Description = 'Update System Privilege';
activity.EntityType = 'SystemPrivilege';
activity.EntityId = this.SystemPrivilegeId + '';
activity.EntityValueBefore = JSON.stringify(entityValueBefore);
activity.EntityValueAfter = JSON.stringify(entityValueAfter);
await activity.create(loginUser.ObjectId, dbTransaction);
// Part 3: Return Updated Record
// Retrieve the updated user system access record from the database or return the updated instance as needed.
return entityValueAfter;
} catch (error) {
throw error;
}
}
public async delete(dbTransaction: any, loginUser: LoginUser) {
try {
//Part 1: Privilege Checking
const systemCode: string =
ApplicationConfig.getComponentConfigValue('system-code');
const isPrivileged = await loginUser.checkPrivileges(
systemCode,
'PRIVILEGE_DELETE',
);
if (!isPrivileged) {
throw new ClassError(
'SystemPrivilege',
'SystemPrivilegeErrMsg0X',
'You do not have permission to delete system privileges',
);
}
//Part 2: Validation
//Make sure SystemPrivilegeId is not empty
if (!this.SystemPrivilegeId) {
throw new ClassError(
'SystemPrivilege',
'SystemPrivilegeErrMsg02',
'System Privilege Id is required',
);
}
//Part 3: Delete Privilege
//Call SystemPrivilege._Repo delete method
await SystemPrivilege._Repository.delete(
this.SystemPrivilegeId,
dbTransaction,
);
//Part 4: Record Create Privilege Activity
//Initialise EntityValueBefore variable and set to empty object.
const EntityValueBefore = {
SystemPrivilegeId: this.ObjectId,
PrivilegeCode: this.PrivilegeCode,
SystemCode: this.SystemCode,
Description: this.Description,
Status: this.Status,
CreatedById: this._CreatedById,
UpdatedById: this._UpdatedById,
CreatedAt: this._CreatedAt,
UpdatedAt: this._UpdatedAt,
};
//Initialise EntityValueAfter variable and set to newSystemPrivilege object.
const EntityValueAfter = {};
//Instantiate new activity object and populate
const activity = new Activity();
activity.ActivityId = activity.createId();
activity.Action = ActionEnum.DELETE;
activity.Description = 'Delete System Privilege';
activity.EntityType = 'SystemPrivilege';
activity.EntityId = this.SystemPrivilegeId;
activity.EntityValueBefore = JSON.stringify(EntityValueBefore);
activity.EntityValueAfter = JSON.stringify(EntityValueAfter);
//Call Activity.create method
await activity.create(loginUser.ObjectId, dbTransaction);
return this;
} catch (error) {
throw error;
}
}
}