feat(auth): implement role-based access control and user management features

This commit is contained in:
Nils-Johan Gynther
2026-04-18 09:34:22 +02:00
parent 20330f6410
commit c5ccef2313
22 changed files with 358 additions and 10 deletions
@@ -0,0 +1,54 @@
import { Injectable, OnApplicationBootstrap, Logger } from '@nestjs/common';
import * as bcrypt from 'bcryptjs';
import { PrismaService } from '../prisma/prisma.service';
type SeedUser = {
username: string;
email: string;
passwordEnvKey: string;
role: string;
};
const SEED_USERS: SeedUser[] = [
{ username: 'Nadmin', email: 'nadmin@localhost', passwordEnvKey: 'ADMIN_NADMIN_PASSWORD', role: 'admin' },
{ username: 'Padmin', email: 'padmin@localhost', passwordEnvKey: 'ADMIN_PADMIN_PASSWORD', role: 'admin' },
{ username: 'user1', email: 'user1@localhost', passwordEnvKey: 'SEED_USER1_PASSWORD', role: 'user' },
{ username: 'user2', email: 'user2@localhost', passwordEnvKey: 'SEED_USER2_PASSWORD', role: 'user' },
];
@Injectable()
export class AdminBootstrapService implements OnApplicationBootstrap {
private readonly logger = new Logger(AdminBootstrapService.name);
constructor(private readonly prisma: PrismaService) {}
async onApplicationBootstrap() {
for (const seed of SEED_USERS) {
const password = process.env[seed.passwordEnvKey];
if (!password) {
this.logger.warn(`${seed.passwordEnvKey} not set — skipping ${seed.username}`);
continue;
}
const existing = await this.prisma.user.findUnique({ where: { username: seed.username } });
if (existing) {
if (existing.role !== seed.role) {
await this.prisma.user.update({ where: { id: existing.id }, data: { role: seed.role } });
this.logger.log(`Updated role for ${seed.username}${seed.role}`);
}
} else {
const passwordHash = await bcrypt.hash(password, 12);
await this.prisma.user.create({
data: {
username: seed.username,
email: seed.email,
passwordHash,
role: seed.role,
},
});
this.logger.log(`Created ${seed.role} user: ${seed.username}`);
}
}
}
}
+27 -2
View File
@@ -1,7 +1,13 @@
import { Controller, Get, Patch, Body } from '@nestjs/common';
import { IsEmail, IsOptional, IsString, MaxLength } from 'class-validator';
import { Controller, Get, Patch, Body, Param, ParseIntPipe, BadRequestException } from '@nestjs/common';
import { IsEmail, IsIn, IsOptional, IsString, MaxLength } from 'class-validator';
import { UsersService } from './users.service';
import { CurrentUser } from '../auth/decorators/current-user.decorator';
import { Roles } from '../auth/decorators/roles.decorator';
class SetRoleDto {
@IsIn(['admin', 'user'])
role: string;
}
class UpdateProfileDto {
@IsOptional()
@@ -32,6 +38,7 @@ export class UsersController {
email: found?.email,
firstName: found?.firstName,
lastName: found?.lastName,
role: found?.role,
};
}
@@ -49,4 +56,22 @@ export class UsersController {
lastName: updated.lastName,
};
}
@Roles('admin')
@Get()
listUsers() {
return this.usersService.findAll();
}
@Roles('admin')
@Patch(':id/role')
async setRole(
@Param('id', ParseIntPipe) id: number,
@CurrentUser() caller: { userId: number; username: string; role: string },
@Body() dto: SetRoleDto,
) {
if (caller.userId === id) throw new BadRequestException('Du kan inte ändra din egen roll');
const updated = await this.usersService.setRole(id, dto.role);
return { id: updated.id, username: updated.username, role: updated.role };
}
}
+2 -1
View File
@@ -1,11 +1,12 @@
import { Module } from '@nestjs/common';
import { UsersService } from './users.service';
import { UsersController } from './users.controller';
import { AdminBootstrapService } from './admin-bootstrap.service';
import { PrismaModule } from '../prisma/prisma.module';
@Module({
imports: [PrismaModule],
providers: [UsersService],
providers: [UsersService, AdminBootstrapService],
controllers: [UsersController],
exports: [UsersService],
})
+11
View File
@@ -20,4 +20,15 @@ export class UsersService {
updateProfile(id: number, data: { firstName?: string; lastName?: string; email?: string }) {
return this.prisma.user.update({ where: { id }, data });
}
findAll() {
return this.prisma.user.findMany({
select: { id: true, username: true, email: true, firstName: true, lastName: true, role: true, createdAt: true },
orderBy: { username: 'asc' },
});
}
setRole(id: number, role: string) {
return this.prisma.user.update({ where: { id }, data: { role } });
}
}