add roles to users

This commit is contained in:
rubikscraft
2022-03-10 23:02:27 +01:00
parent 749042cdd5
commit 9b98f3c005
11 changed files with 103 additions and 33 deletions

View File

@@ -1,6 +1,7 @@
import { Logger, Module, OnModuleInit } from '@nestjs/common';
import { JwtModule } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport';
import { HasFailed } from 'picsur-shared/dist/types';
import { SysPreferenceModule } from '../../collections/syspreferencesdb/syspreferencedb.module';
import { UsersModule } from '../../collections/userdb/userdb.module';
import { AuthConfigService } from '../../config/auth.config.service';
@@ -51,7 +52,23 @@ export class AuthManagerModule implements OnModuleInit {
const password = this.authConfigService.getDefaultAdminPassword();
this.logger.debug(`Ensuring admin user "${username}" exists`);
await this.authService.createUser(username, password);
await this.authService.makeAdmin(username);
const exists = await this.authService.userExists(username);
if (exists) return;
const newUser = await this.authService.createUser(username, password);
if (HasFailed(newUser)) {
this.logger.error(
`Failed to create admin user "${username}" because: ${newUser.getReason()}`,
);
return;
}
const result = await this.authService.makeAdmin(newUser);
if (HasFailed(result)) {
this.logger.error(
`Failed to make admin user "${username}" because: ${result.getReason()}`,
);
return;
}
}
}

View File

@@ -30,6 +30,10 @@ export class AuthManagerService {
return this.usersService.findAll();
}
async userExists(username: string): Promise<boolean> {
return this.usersService.exists(username);
}
async authenticate(username: string, password: string): AsyncFailable<EUserBackend> {
const user = await this.usersService.findOne(username, true);
if (HasFailed(user)) return user;
@@ -55,10 +59,10 @@ export class AuthManagerService {
}
async makeAdmin(user: string | EUserBackend): AsyncFailable<true> {
return this.usersService.modifyAdmin(user, true);
return this.usersService.addRoles(user, ['admin']);
}
async revokeAdmin(user: string | EUserBackend): AsyncFailable<true> {
return this.usersService.modifyAdmin(user, false);
return this.usersService.removeRoles(user, ['admin']);
}
}

View File

@@ -26,6 +26,6 @@ export class AdminGuard implements CanActivate {
return false;
}
return user.isAdmin;
return user.roles.includes('admin');
}
}