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,2 @@
-- Add role field to User
ALTER TABLE `User` ADD COLUMN `role` VARCHAR(191) NOT NULL DEFAULT 'user';
+1
View File
@@ -14,6 +14,7 @@ model User {
firstName String?
lastName String?
passwordHash String
role String @default("user")
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
+5
View File
@@ -15,6 +15,7 @@ import { UsersModule } from './users/users.module';
import { UserProductsModule } from './user-products/user-products.module';
import { CategoriesModule } from './categories/categories.module';
import { JwtAuthGuard } from './auth/jwt-auth.guard';
import { RolesGuard } from './auth/roles.guard';
@Module({
@@ -39,6 +40,10 @@ import { JwtAuthGuard } from './auth/jwt-auth.guard';
provide: APP_GUARD,
useClass: JwtAuthGuard,
},
{
provide: APP_GUARD,
useClass: RolesGuard,
},
],
})
export class AppModule {}
+5 -4
View File
@@ -27,7 +27,7 @@ export class AuthService {
passwordHash,
});
return this.issueToken(user.id, user.username);
return this.issueToken(user.id, user.username, user.role);
}
async login(dto: LoginDto) {
@@ -37,15 +37,16 @@ export class AuthService {
const valid = await bcrypt.compare(dto.password, user.passwordHash);
if (!valid) throw new UnauthorizedException('Felaktigt användarnamn eller lösenord');
return this.issueToken(user.id, user.username);
return this.issueToken(user.id, user.username, user.role);
}
private issueToken(userId: number, username: string) {
const payload = { sub: userId, username };
private issueToken(userId: number, username: string, role: string) {
const payload = { sub: userId, username, role };
return {
accessToken: this.jwtService.sign(payload),
userId,
username,
role,
};
}
}
@@ -0,0 +1,4 @@
import { SetMetadata } from '@nestjs/common';
export const ROLES_KEY = 'roles';
export const Roles = (...roles: string[]) => SetMetadata(ROLES_KEY, roles);
+2 -2
View File
@@ -12,7 +12,7 @@ export class JwtStrategy extends PassportStrategy(Strategy) {
});
}
async validate(payload: { sub: number; username: string }) {
return { userId: payload.sub, username: payload.username };
async validate(payload: { sub: number; username: string; role: string }) {
return { userId: payload.sub, username: payload.username, role: payload.role ?? 'user' };
}
}
+24
View File
@@ -0,0 +1,24 @@
import { Injectable, CanActivate, ExecutionContext, ForbiddenException } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { ROLES_KEY } from './decorators/roles.decorator';
@Injectable()
export class RolesGuard implements CanActivate {
constructor(private reflector: Reflector) {}
canActivate(context: ExecutionContext): boolean {
const requiredRoles = this.reflector.getAllAndOverride<string[]>(ROLES_KEY, [
context.getHandler(),
context.getClass(),
]);
// No @Roles() decorator — allow any authenticated user
if (!requiredRoles || requiredRoles.length === 0) return true;
const { user } = context.switchToHttp().getRequest();
if (!user?.role || !requiredRoles.includes(user.role)) {
throw new ForbiddenException('Åtkomst nekad — admin-behörighet krävs');
}
return true;
}
}
@@ -19,6 +19,7 @@ import { UpdateCanonicalNameDto } from './dto/update-canonical-name.dto';
import { SetTagsDto } from './dto/set-tags.dto';
import { UpsertNutritionDto } from './dto/upsert-nutrition.dto';
import { BulkUpdateProductsDto } from './dto/bulk-update-products.dto';
import { Roles } from '../auth/decorators/roles.decorator';
@Controller('products')
export class ProductsController {
@@ -50,6 +51,7 @@ export class ProductsController {
return this.productsService.previewMerge(sourceProductId, targetProductId);
}
@Roles('admin')
@Post('backfill-canonical')
backfillCanonical() {
return this.productsService.backfillCanonicalNames();
@@ -65,6 +67,7 @@ export class ProductsController {
return this.productsService.create(body);
}
@Roles('admin')
@Post('merge')
merge(@Body() body: MergeProductsDto) {
return this.productsService.merge(body.sourceProductId, body.targetProductId);
@@ -102,22 +105,26 @@ export class ProductsController {
return this.productsService.update(id, body);
}
@Roles('admin')
@Delete(':id')
remove(@Param('id', ParseIntPipe) id: number) {
return this.productsService.remove(id);
}
@Roles('admin')
@Post(':id/restore')
restore(@Param('id', ParseIntPipe) id: number) {
return this.productsService.restore(id);
}
@Roles('admin')
@Post('reset-all')
@HttpCode(200)
resetAll() {
return this.productsService.resetAll();
}
@Roles('admin')
@Post('bulk-update')
@HttpCode(200)
bulkUpdate(@Body() body: BulkUpdateProductsDto) {
@@ -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 } });
}
}