2023-01-11 21:34:36 -05:00
|
|
|
import { Inject } from '@nestjs/common';
|
2022-11-05 12:28:40 -04:00
|
|
|
import { Command, CommandRunner, InquirerService, Question, QuestionSet } from 'nest-commander';
|
|
|
|
|
import { randomBytes } from 'node:crypto';
|
2023-01-11 21:34:36 -05:00
|
|
|
import { IUserRepository, UserCore } from '@app/domain';
|
2022-11-05 12:28:40 -04:00
|
|
|
|
|
|
|
|
@Command({
|
|
|
|
|
name: 'reset-admin-password',
|
|
|
|
|
description: 'Reset the admin password',
|
|
|
|
|
})
|
|
|
|
|
export class ResetAdminPasswordCommand extends CommandRunner {
|
2023-01-11 21:34:36 -05:00
|
|
|
userCore: UserCore;
|
|
|
|
|
|
|
|
|
|
constructor(private readonly inquirer: InquirerService, @Inject(IUserRepository) userRepository: IUserRepository) {
|
2022-11-05 12:28:40 -04:00
|
|
|
super();
|
2023-01-11 21:34:36 -05:00
|
|
|
|
|
|
|
|
this.userCore = new UserCore(userRepository);
|
2022-11-05 12:28:40 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async run(): Promise<void> {
|
2023-01-11 21:34:36 -05:00
|
|
|
const user = await this.userCore.getAdmin();
|
2022-11-05 12:28:40 -04:00
|
|
|
if (!user) {
|
|
|
|
|
console.log('Unable to reset password: no admin user.');
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
2023-01-11 21:34:36 -05:00
|
|
|
const { password: providedPassword } = await this.inquirer.ask<{ password: string }>('prompt-password', undefined);
|
|
|
|
|
const password = providedPassword || randomBytes(24).toString('base64').replace(/\W/g, '');
|
2022-11-05 12:28:40 -04:00
|
|
|
|
2023-01-11 21:34:36 -05:00
|
|
|
await this.userCore.updateUser(user, user.id, { password });
|
2022-11-05 12:28:40 -04:00
|
|
|
|
2023-01-11 21:34:36 -05:00
|
|
|
if (providedPassword) {
|
|
|
|
|
console.log('The admin password has been updated.');
|
|
|
|
|
} else {
|
|
|
|
|
console.log(`The admin password has been updated to:\n${password}`);
|
|
|
|
|
}
|
2022-11-05 12:28:40 -04:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
@QuestionSet({ name: 'prompt-password' })
|
|
|
|
|
export class PromptPasswordQuestions {
|
|
|
|
|
@Question({
|
|
|
|
|
message: 'Please choose a new password (optional)',
|
|
|
|
|
name: 'password',
|
|
|
|
|
})
|
|
|
|
|
parsePassword(val: string) {
|
|
|
|
|
return val;
|
|
|
|
|
}
|
|
|
|
|
}
|