Files
Picsur/backend/src/collections/userdb/userdb.module.ts

79 lines
2.2 KiB
TypeScript
Raw Normal View History

2022-03-12 15:10:22 +01:00
import { Logger, Module, OnModuleInit } from '@nestjs/common';
2022-02-21 14:53:21 +01:00
import { TypeOrmModule } from '@nestjs/typeorm';
2022-03-12 15:10:22 +01:00
import { HasFailed } from 'picsur-shared/dist/types';
2022-03-23 20:40:31 +01:00
import { generateRandomString } from 'picsur-shared/dist/util/random';
2022-03-12 15:10:22 +01:00
import { AuthConfigService } from '../../config/auth.config.service';
import { PicsurConfigModule } from '../../config/config.module';
2022-03-03 22:48:03 +01:00
import { EUserBackend } from '../../models/entities/user.entity';
2022-03-12 15:10:22 +01:00
import { RolesModule } from '../roledb/roledb.module';
2022-02-21 22:36:47 +01:00
import { UsersService } from './userdb.service';
2022-03-23 17:17:39 +01:00
import { UserRolesService } from './userrolesdb.service';
2022-02-21 14:53:21 +01:00
@Module({
2022-03-12 15:10:22 +01:00
imports: [
PicsurConfigModule,
RolesModule,
TypeOrmModule.forFeature([EUserBackend]),
],
2022-03-23 17:17:39 +01:00
providers: [UsersService, UserRolesService],
exports: [UsersService, UserRolesService],
2022-02-21 14:53:21 +01:00
})
2022-03-12 15:10:22 +01:00
export class UsersModule implements OnModuleInit {
private readonly logger = new Logger('UsersModule');
constructor(
private usersService: UsersService,
2022-03-23 17:17:39 +01:00
private userRolesService: UserRolesService,
2022-03-12 15:10:22 +01:00
private authConfigService: AuthConfigService,
) {}
async onModuleInit() {
2022-03-23 20:40:31 +01:00
await this.ensureGuestExists();
2022-03-12 15:10:22 +01:00
await this.ensureAdminExists();
}
2022-03-23 20:40:31 +01:00
private async ensureGuestExists() {
const username = 'guest';
const password = generateRandomString(128);
this.logger.debug(`Ensuring guest user exists`);
2022-03-12 15:10:22 +01:00
const exists = await this.usersService.exists(username);
if (exists) return;
2022-03-23 20:40:31 +01:00
const newUser = await this.usersService.create(
username,
password,
['guest'],
true,
);
2022-03-12 15:10:22 +01:00
if (HasFailed(newUser)) {
this.logger.error(
2022-03-23 20:40:31 +01:00
`Failed to create guest user because: ${newUser.getReason()}`,
2022-03-12 15:10:22 +01:00
);
return;
}
2022-03-23 20:40:31 +01:00
}
private async ensureAdminExists() {
const username = 'admin';
const password = this.authConfigService.getDefaultAdminPassword();
this.logger.debug(`Ensuring admin user exists`);
2022-03-12 15:10:22 +01:00
2022-03-23 20:40:31 +01:00
const exists = await this.usersService.exists(username);
if (exists) return;
const newUser = await this.usersService.create(
username,
password,
['user', 'admin'],
true,
);
if (HasFailed(newUser)) {
2022-03-12 15:10:22 +01:00
this.logger.error(
2022-03-23 20:40:31 +01:00
`Failed to create admin user because: ${newUser.getReason()}`,
2022-03-12 15:10:22 +01:00
);
return;
}
}
}