feat: RBAC Phase 3 - LegacyRole-Enum, RolesGuard und @Roles vollstaendig entfernt

Letzte Phase des RBAC-Umbaus: die transitionale Rollen-Infrastruktur,
die seit Phase 1 parallel zum neuen Role/Permission-System mitlief,
ist jetzt komplett weg.

- Prisma-Migration: User.legacyRole-Spalte und LegacyRole-Enum
  gedroppt (nichts liest die Spalte mehr, seit Phase 2 jeder Controller
  auf @RequirePermission laeuft).
- roles.guard.ts, roles.guard.spec.ts, roles.decorator.ts geloescht;
  RolesGuard aus den APP_GUARD-Providern entfernt.
- AuthenticatedUser/JWT-Payload verlieren das role-Feld (permissions
  werden ohnehin frisch pro Request aus der DB aufgeloest, nicht aus
  dem Claim).
- Users-API: CreateUserDto/UpdateUserDto akzeptieren jetzt roleId
  (eine echte Role.id) statt der alten role-Enum-Werte; UsersService
  validiert, dass die Rolle existiert und aktiv ist, bevor sie
  zugewiesen wird.
- Alle 34 e2e-Fixtures und der Seed-Script folgen dem neuen Schema.

Verifiziert: tsc, lint, build, unit (220/220), volle e2e-Suite
159/159 gruen - keine uebersprungenen Tests.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
This commit is contained in:
Nick SzaunigandClaude Sonnet 5 committed 2026-08-26 09:01:13 +02:00
1 parent 0284077d3b
commit ae53f7889e
51 files changed
+125 -224

No files matched your search

@@ -1,6 +1,5 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsEmail, IsEnum, IsString, MinLength } from 'class-validator';
import { LegacyRole as Role } from '../../../generated/prisma';
import { IsEmail, IsString, MinLength } from 'class-validator';
export class CreateUserDto {
@ApiProperty()
@@ -16,7 +15,8 @@ export class CreateUserDto {
@IsString()
name!: string;
@ApiProperty({ enum: Role })
@IsEnum(Role)
role!: Role;
@ApiProperty({ description: 'Id of an active Role' })
@IsString()
@MinLength(1)
roleId!: string;
}
@@ -1,6 +1,5 @@
import { ApiPropertyOptional } from '@nestjs/swagger';
import { IsEnum, IsOptional, IsString } from 'class-validator';
import { LegacyRole as Role } from '../../../generated/prisma';
import { IsOptional, IsString, MinLength } from 'class-validator';
export class UpdateUserDto {
@ApiPropertyOptional()
@@ -8,8 +7,9 @@ export class UpdateUserDto {
@IsString()
name?: string;
@ApiPropertyOptional({ enum: Role })
@ApiPropertyOptional({ description: 'Id of an active Role' })
@IsOptional()
@IsEnum(Role)
role?: Role;
@IsString()
@MinLength(1)
roleId?: string;
}
@@ -13,18 +13,25 @@ describe('UsersService', () => {
update: jest.Mock;
};
role: {
findUniqueOrThrow: jest.Mock;
findUnique: jest.Mock;
};
};
let auditLog: { record: jest.Mock };
const staffRole = {
id: 'role-staff',
key: 'STAFF',
name: 'Mitarbeiter',
status: 'ACTIVE',
};
const existingUser = {
id: 'user-1',
email: '[email protected]',
passwordHash: 'hashed',
name: 'Existing User',
legacyRole: 'STAFF',
roleId: 'role-staff',
roleId: staffRole.id,
role: staffRole,
isActive: true,
createdAt: new Date(),
deactivatedAt: null,
@@ -39,9 +46,7 @@ describe('UsersService', () => {
update: jest.fn(),
},
role: {
findUniqueOrThrow: jest
.fn()
.mockResolvedValue({ id: 'role-staff', key: 'STAFF' }),
findUnique: jest.fn().mockResolvedValue(staffRole),
},
};
auditLog = { record: jest.fn().mockResolvedValue(undefined) };
@@ -61,7 +66,9 @@ describe('UsersService', () => {
id: existingUser.id,
email: existingUser.email,
name: existingUser.name,
role: existingUser.legacyRole,
roleId: staffRole.id,
roleKey: staffRole.key,
roleName: staffRole.name,
isActive: existingUser.isActive,
createdAt: existingUser.createdAt,
deactivatedAt: existingUser.deactivatedAt,
@@ -84,7 +91,36 @@ describe('UsersService', () => {
email: existingUser.email,
password: 'password123',
name: 'New',
role: 'STAFF',
roleId: staffRole.id,
}),
).rejects.toBeInstanceOf(ConflictException);
});
it('create throws NotFoundException when the role does not exist', async () => {
prisma.user.findUnique.mockResolvedValue(null);
prisma.role.findUnique.mockResolvedValue(null);
await expect(
usersService.create({
email: '[email protected]',
password: 'password123',
name: 'New User',
roleId: 'missing-role',
}),
).rejects.toBeInstanceOf(NotFoundException);
});
it('create throws ConflictException when the role is not active', async () => {
prisma.user.findUnique.mockResolvedValue(null);
prisma.role.findUnique.mockResolvedValue({
...staffRole,
status: 'INACTIVE',
});
await expect(
usersService.create({
email: '[email protected]',
password: 'password123',
name: 'New User',
roleId: staffRole.id,
}),
).rejects.toBeInstanceOf(ConflictException);
});
@@ -101,7 +137,7 @@ describe('UsersService', () => {
email: '[email protected]',
password: 'password123',
name: 'New User',
role: 'STAFF',
roleId: staffRole.id,
});
expect(result.id).toBe('user-2');
+46 -32
View File
@@ -6,17 +6,25 @@ import {
import * as bcrypt from 'bcryptjs';
import { PrismaService } from '../prisma/prisma.service';
import { AuditLogService } from '../audit/audit-log.service';
import { User } from '../../generated/prisma';
import { Prisma } from '../../generated/prisma';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
const BCRYPT_SALT_ROUNDS = 12;
const USER_WITH_ROLE = {
include: { role: true },
} satisfies { include: Prisma.UserInclude };
type UserWithRole = Prisma.UserGetPayload<typeof USER_WITH_ROLE>;
export interface UserSummary {
id: string;
email: string;
name: string;
role: string;
roleId: string;
roleKey: string;
roleName: string;
isActive: boolean;
createdAt: Date;
deactivatedAt: Date | null;
@@ -29,41 +37,43 @@ export class UsersService {
private readonly auditLog: AuditLogService,
) {}
private toSummary(user: User): UserSummary {
const { id, email, name, legacyRole, isActive, createdAt, deactivatedAt } =
user;
private toSummary(user: UserWithRole): UserSummary {
return {
id,
email,
name,
role: legacyRole,
isActive,
createdAt,
deactivatedAt,
id: user.id,
email: user.email,
name: user.name,
roleId: user.roleId,
roleKey: user.role.key,
roleName: user.role.name,
isActive: user.isActive,
createdAt: user.createdAt,
deactivatedAt: user.deactivatedAt,
};
}
/**
* Resolves the RBAC roleId that corresponds to a legacy role key, so
* User.roleId stays in sync while callers still speak in terms of the
* legacy enum (Phase 1 of the RBAC rollout; see Role/Permission models).
*/
private async resolveRoleId(legacyRole: string): Promise<string> {
const role = await this.prisma.role.findUniqueOrThrow({
where: { key: legacyRole },
});
return role.id;
private async assertActiveRole(roleId: string): Promise<void> {
const role = await this.prisma.role.findUnique({ where: { id: roleId } });
if (!role) {
throw new NotFoundException('Role not found');
}
if (role.status !== 'ACTIVE') {
throw new ConflictException('Role is not active');
}
}
async findAll(): Promise<UserSummary[]> {
const users = await this.prisma.user.findMany({
...USER_WITH_ROLE,
orderBy: { createdAt: 'asc' },
});
return users.map((user) => this.toSummary(user));
}
async findById(id: string): Promise<User> {
const user = await this.prisma.user.findUnique({ where: { id } });
async findById(id: string): Promise<UserWithRole> {
const user = await this.prisma.user.findUnique({
where: { id },
...USER_WITH_ROLE,
});
if (!user) {
throw new NotFoundException('User not found');
}
@@ -74,8 +84,8 @@ export class UsersService {
return this.toSummary(await this.findById(id));
}
async findByEmail(email: string): Promise<User | null> {
return this.prisma.user.findUnique({ where: { email } });
async findByEmail(email: string): Promise<UserWithRole | null> {
return this.prisma.user.findUnique({ where: { email }, ...USER_WITH_ROLE });
}
async create(
@@ -86,16 +96,16 @@ export class UsersService {
if (existing) {
throw new ConflictException('Email already in use');
}
await this.assertActiveRole(dto.roleId);
const passwordHash = await bcrypt.hash(dto.password, BCRYPT_SALT_ROUNDS);
const roleId = await this.resolveRoleId(dto.role);
const user = await this.prisma.user.create({
data: {
email: dto.email,
passwordHash,
name: dto.name,
legacyRole: dto.role,
roleId,
roleId: dto.roleId,
},
...USER_WITH_ROLE,
});
await this.auditLog.record({
entityType: 'User',
@@ -113,14 +123,16 @@ export class UsersService {
actingUserId?: string,
): Promise<UserSummary> {
const before = await this.findById(id);
const roleId = dto.role ? await this.resolveRoleId(dto.role) : undefined;
if (dto.roleId) {
await this.assertActiveRole(dto.roleId);
}
const user = await this.prisma.user.update({
where: { id },
data: {
name: dto.name,
legacyRole: dto.role,
roleId,
roleId: dto.roleId,
},
...USER_WITH_ROLE,
});
await this.auditLog.record({
entityType: 'User',
@@ -138,6 +150,7 @@ export class UsersService {
const user = await this.prisma.user.update({
where: { id },
data: { isActive: false, deactivatedAt: new Date() },
...USER_WITH_ROLE,
});
await this.auditLog.record({
entityType: 'User',
@@ -158,6 +171,7 @@ export class UsersService {
const user = await this.prisma.user.update({
where: { id },
data: { isActive: true, deactivatedAt: null },
...USER_WITH_ROLE,
});
await this.auditLog.record({
entityType: 'User',