Refactor user role handling to use single role object

This commit is contained in:
faris Aljohari
2024-12-16 00:16:24 -06:00
parent 37d016ea43
commit 852299a273
13 changed files with 43 additions and 96 deletions

View File

@ -1,7 +1,6 @@
import { Injectable } from '@nestjs/common';
import { UserRepository } from '@app/common/modules/user/repositories';
import { RoleType } from '@app/common/constants/role.type.enum';
import { UserRoleRepository } from '@app/common/modules/user/repositories';
import { RoleTypeRepository } from '@app/common/modules/role-type/repositories';
import { ConfigService } from '@nestjs/config';
import { HelperHashService } from '../../helper/services';
@ -11,19 +10,23 @@ export class SuperAdminSeeder {
constructor(
private readonly configService: ConfigService,
private readonly userRepository: UserRepository,
private readonly userRoleRepository: UserRoleRepository,
private readonly roleTypeRepository: RoleTypeRepository,
private readonly helperHashService: HelperHashService,
) {}
async createSuperAdminIfNotFound(): Promise<void> {
try {
const superAdminData = await this.userRoleRepository.find({
where: { roleType: { type: RoleType.SUPER_ADMIN } },
const superAdmin = await this.userRepository.findOne({
where: {
roleType: { type: RoleType.SUPER_ADMIN },
email: this.configService.get<string>(
'super-admin.SUPER_ADMIN_EMAIL',
),
},
relations: ['roleType'],
});
if (superAdminData.length <= 0) {
if (!superAdmin) {
// Create the super admin user if not found
console.log('Creating super admin user...');
@ -48,20 +51,16 @@ export class SuperAdminSeeder {
salt,
);
try {
const user = await this.userRepository.save({
const defaultUserRoleUuid = await this.getRoleUuidByRoleType(
RoleType.SUPER_ADMIN,
);
await this.userRepository.save({
email: this.configService.get<string>('super-admin.SUPER_ADMIN_EMAIL'),
password: hashedPassword,
firstName: 'Super',
lastName: 'Admin',
isUserVerified: true,
isActive: true,
});
const defaultUserRoleUuid = await this.getRoleUuidByRoleType(
RoleType.SUPER_ADMIN,
);
await this.userRoleRepository.save({
user: { uuid: user.uuid },
roleType: { uuid: defaultUserRoleUuid },
});
} catch (err) {