forked from Shared/esg
initial commit
This commit is contained in:
66
src/cli/create-super-admin.service.ts
Normal file
66
src/cli/create-super-admin.service.ts
Normal file
@@ -0,0 +1,66 @@
|
||||
import { ConflictException, Injectable, Logger } from '@nestjs/common';
|
||||
import { InjectModel } from '@nestjs/mongoose';
|
||||
import { Model } from 'mongoose';
|
||||
import { randomBytes } from 'crypto';
|
||||
import { ClientType } from '../common/enums/client-type.enum';
|
||||
import { Role } from '../common/enums/role.enum';
|
||||
import { PasswordService } from '../auth/services/password.service';
|
||||
import { User, UserDocument } from '../users/schemas/user.schema';
|
||||
import { UserMapper } from '../users/mappers/user.mapper';
|
||||
import { UserResponseDto } from '../users/dto/user-response.dto';
|
||||
|
||||
export interface CreateSuperAdminInput {
|
||||
fullName: string;
|
||||
username: string;
|
||||
email: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class CreateSuperAdminService {
|
||||
private readonly logger = new Logger(CreateSuperAdminService.name);
|
||||
|
||||
constructor(
|
||||
@InjectModel(User.name) private readonly userModel: Model<UserDocument>,
|
||||
private readonly passwordService: PasswordService,
|
||||
) {}
|
||||
|
||||
async create(input: CreateSuperAdminInput): Promise<UserResponseDto> {
|
||||
if (input.password.length < 8) {
|
||||
throw new ConflictException('Password must be at least 8 characters');
|
||||
}
|
||||
|
||||
const username = input.username.toLowerCase().trim();
|
||||
const email = input.email.toLowerCase().trim();
|
||||
|
||||
const existing = await this.userModel.findOne({ $or: [{ username }, { email }] });
|
||||
if (existing) {
|
||||
throw new ConflictException('Username or email already exists');
|
||||
}
|
||||
|
||||
const superAdminExists = await this.userModel.exists({ role: Role.SUPER_ADMIN });
|
||||
if (superAdminExists) {
|
||||
this.logger.warn('A SUPER_ADMIN already exists; creating another.');
|
||||
}
|
||||
|
||||
const passwordHash = await this.passwordService.hash(input.password);
|
||||
|
||||
const user = await this.userModel.create({
|
||||
fullName: input.fullName.trim(),
|
||||
username,
|
||||
email,
|
||||
password: passwordHash,
|
||||
role: Role.SUPER_ADMIN,
|
||||
clientType: ClientType.INTERNAL,
|
||||
appName: 'inquiry-gateway',
|
||||
clientName: 'Internal',
|
||||
isActive: true,
|
||||
isBlocked: false,
|
||||
allowedInquiries: [],
|
||||
apiKey: `esg_${randomBytes(32).toString('hex')}`,
|
||||
passwordChangedAt: new Date(),
|
||||
});
|
||||
|
||||
return UserMapper.toResponseDto(user);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user