Added backend for Admin Panel

This commit is contained in:
Mutzi 2022-08-25 20:37:10 +02:00
parent 9923593a6f
commit f8ccebc5ad
2 changed files with 94 additions and 0 deletions

89
src/controller/admin.ts Normal file
View File

@ -0,0 +1,89 @@
import {
BadRequestException,
Body,
Controller,
Get,
Post,
Request,
ValidationPipe
} from '@nestjs/common';
import { AuthService } from 'services/auth';
import { Requests, Responses, UserRole } from 'dto';
import { Role } from 'authguards';
import { InjectRepository } from '@nestjs/typeorm';
import { tfaTypes, User } from 'entities';
import { Repository } from 'typeorm';
@Controller('api/admin')
export default class AdminController {
constructor(
@InjectRepository(User)
private userRepo: Repository<User>,
private authService: AuthService
) {}
@Role(UserRole.ADMIN)
@Get('users')
async getUsers(): Promise<Responses.Admin.GetUsers> {
const users = await this.userRepo.find();
const entries = users.map(
(user) =>
new Responses.Admin.GetUsersEntry(
user.id,
user.isGitlabUser,
user.name,
user.role,
this.authService.requiresTfa(user)
)
);
return new Responses.Admin.GetUsers(entries);
}
@Role(UserRole.ADMIN)
@Post('set_role')
async setRole(
@Request() req,
@Body(new ValidationPipe()) data: Requests.Admin.SetUserRole
): Promise<Responses.Admin.SetUserRole> {
const user = await this.authService.getUser(data.user);
if (!user) throw new BadRequestException('Invalid user');
await this.authService.setUserRole(user, data.role);
return new Responses.Admin.SetUserRole();
}
@Role(UserRole.ADMIN)
@Post('logout')
async logout(
@Request() req,
@Body(new ValidationPipe()) data: Requests.Admin.LogoutAll
): Promise<Responses.Admin.LogoutAllUser> {
const user = await this.authService.getUser(data.user);
if (!user) throw new BadRequestException('Invalid user');
await this.authService.revokeAll(user);
return new Responses.Admin.LogoutAllUser();
}
@Role(UserRole.ADMIN)
@Post('delete')
async delete(
@Request() req,
@Body(new ValidationPipe()) data: Requests.Admin.DeleteUser
): Promise<Responses.Admin.DeleteUser> {
const user = await this.authService.getUser(data.user);
if (!user) throw new BadRequestException('Invalid user');
await this.authService.deleteUser(user);
return new Responses.Admin.DeleteUser();
}
@Role(UserRole.ADMIN)
@Post('disable_2fa')
async disableTfa(
@Request() req,
@Body(new ValidationPipe()) data: Requests.Admin.DisableTfa
): Promise<Responses.Admin.DisableTfa> {
const user = await this.authService.getUser(data.user);
if (!user) throw new BadRequestException('Invalid user');
await this.authService.setTfaType(user, tfaTypes.NONE);
return new Responses.Admin.DisableTfa();
}
}

View File

@ -109,4 +109,9 @@ export default class BaseAuthService {
ownerId: user.id ownerId: user.id
}); });
} }
async setUserRole(user: User, role: UserRole) {
user.role = role;
await this.userRepo.save(user);
}
} }