mirror of
https://github.com/SyncrowIOT/backend.git
synced 2025-07-10 15:17:41 +00:00
76 lines
2.4 KiB
TypeScript
76 lines
2.4 KiB
TypeScript
import { Injectable } from '@nestjs/common';
|
|
import { UserRepository } from '@app/common/modules/user/repositories';
|
|
import { RoleType } from '@app/common/constants/role.type.enum';
|
|
import { RoleTypeRepository } from '@app/common/modules/role-type/repositories';
|
|
import { ConfigService } from '@nestjs/config';
|
|
import { HelperHashService } from '../../helper/services';
|
|
|
|
@Injectable()
|
|
export class SuperAdminSeeder {
|
|
constructor(
|
|
private readonly configService: ConfigService,
|
|
private readonly userRepository: UserRepository,
|
|
private readonly roleTypeRepository: RoleTypeRepository,
|
|
private readonly helperHashService: HelperHashService,
|
|
) {}
|
|
|
|
async createSuperAdminIfNotFound(): Promise<void> {
|
|
try {
|
|
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 (!superAdmin) {
|
|
// Create the super admin user if not found
|
|
console.log('Creating super admin user...');
|
|
|
|
await this.createSuperAdmin();
|
|
}
|
|
} catch (err) {
|
|
console.error('Error while checking super admin:', err);
|
|
throw err;
|
|
}
|
|
}
|
|
private async getRoleUuidByRoleType(roleType: string) {
|
|
const role = await this.roleTypeRepository.findOne({
|
|
where: { type: roleType },
|
|
});
|
|
|
|
return role.uuid;
|
|
}
|
|
private async createSuperAdmin(): Promise<void> {
|
|
const salt = this.helperHashService.randomSalt(10); // Hash the password using bcrypt
|
|
const hashedPassword = await this.helperHashService.bcrypt(
|
|
this.configService.get<string>('super-admin.SUPER_ADMIN_PASSWORD'),
|
|
salt,
|
|
);
|
|
try {
|
|
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,
|
|
hasAcceptedAppAgreement: true,
|
|
hasAcceptedWebAgreement: true,
|
|
appAgreementAcceptedAt: new Date(),
|
|
webAgreementAcceptedAt: new Date(),
|
|
roleType: { uuid: defaultUserRoleUuid },
|
|
});
|
|
} catch (err) {
|
|
console.error('Error while creating super admin:', err);
|
|
throw err;
|
|
}
|
|
}
|
|
}
|