|
| 1 | +import { Injectable, Logger, OnModuleInit } from '@nestjs/common'; |
| 2 | +import { ConfigService } from '@nestjs/config'; |
| 3 | +import { InjectRepository } from '@nestjs/typeorm'; |
| 4 | +import * as bcrypt from 'bcrypt'; |
| 5 | +import { QueryFailedError } from 'typeorm'; |
| 6 | +import { Repository } from 'typeorm'; |
| 7 | +import { UserRole } from '../../users/domain/user-role.enum'; |
| 8 | +import { User } from '../../users/infrastructure/entities/user.entity'; |
| 9 | + |
| 10 | +@Injectable() |
| 11 | +export class AdminBootstrapService implements OnModuleInit { |
| 12 | + private readonly logger = new Logger(AdminBootstrapService.name); |
| 13 | + |
| 14 | + constructor( |
| 15 | + @InjectRepository(User) |
| 16 | + private readonly usersRepository: Repository<User>, |
| 17 | + private readonly configService: ConfigService, |
| 18 | + ) {} |
| 19 | + |
| 20 | + async onModuleInit(): Promise<void> { |
| 21 | + const seedEnabled = |
| 22 | + this.configService.get<string>('SEED_DEFAULT_ADMIN', 'true') === 'true'; |
| 23 | + |
| 24 | + if (!seedEnabled) { |
| 25 | + this.logger.log('Default admin seed disabled (SEED_DEFAULT_ADMIN=false)'); |
| 26 | + return; |
| 27 | + } |
| 28 | + |
| 29 | + const email = this.configService |
| 30 | + .get<string>('DEFAULT_ADMIN_EMAIL', 'admin@talen.local') |
| 31 | + .trim() |
| 32 | + .toLowerCase(); |
| 33 | + const plainPassword = this.configService.get<string>( |
| 34 | + 'DEFAULT_ADMIN_PASSWORD', |
| 35 | + 'AdminTemp2026!', |
| 36 | + ); |
| 37 | + const forcePasswordSync = |
| 38 | + this.configService.get<string>('DEFAULT_ADMIN_FORCE_SYNC', 'false') === |
| 39 | + 'true'; |
| 40 | + |
| 41 | + if (!email || !plainPassword) { |
| 42 | + this.logger.warn( |
| 43 | + 'Default admin seed skipped: missing DEFAULT_ADMIN_EMAIL or DEFAULT_ADMIN_PASSWORD', |
| 44 | + ); |
| 45 | + return; |
| 46 | + } |
| 47 | + |
| 48 | + const existingUser = await this.usersRepository.findOne({ |
| 49 | + where: { email }, |
| 50 | + }); |
| 51 | + |
| 52 | + if (!existingUser) { |
| 53 | + const hashedPassword = await bcrypt.hash(plainPassword, 10); |
| 54 | + const user = this.usersRepository.create({ |
| 55 | + email, |
| 56 | + password: hashedPassword, |
| 57 | + role: UserRole.ADMIN, |
| 58 | + }); |
| 59 | + try { |
| 60 | + await this.usersRepository.save(user); |
| 61 | + } catch (error) { |
| 62 | + // If multiple instances boot at the same time, another instance may create the user first. |
| 63 | + if (!this.isUniqueViolation(error)) { |
| 64 | + throw error; |
| 65 | + } |
| 66 | + } |
| 67 | + this.logger.log(`Default admin created: ${email}`); |
| 68 | + return; |
| 69 | + } |
| 70 | + |
| 71 | + if (!forcePasswordSync) { |
| 72 | + this.logger.log(`Default admin already exists: ${email}`); |
| 73 | + return; |
| 74 | + } |
| 75 | + |
| 76 | + existingUser.password = await bcrypt.hash(plainPassword, 10); |
| 77 | + existingUser.role = UserRole.ADMIN; |
| 78 | + await this.usersRepository.save(existingUser); |
| 79 | + this.logger.log(`Default admin synchronized: ${email}`); |
| 80 | + } |
| 81 | + |
| 82 | + private isUniqueViolation(error: unknown): boolean { |
| 83 | + if (!(error instanceof QueryFailedError)) { |
| 84 | + return false; |
| 85 | + } |
| 86 | + |
| 87 | + const code = (error as QueryFailedError & { code?: string }).code; |
| 88 | + return code === '23505'; |
| 89 | + } |
| 90 | +} |
0 commit comments