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:
1 parent
0284077d3b
commit
ae53f7889e
51 files changed
+125
-224
No files matched your search
@@ -38,7 +38,6 @@ import { PublicModule } from './public/public.module';
|
||||
import { TaskTemplatesModule } from './task-templates/task-templates.module';
|
||||
import { SwarmControlModule } from './swarm-control/swarm-control.module';
|
||||
import { JwtAuthGuard } from './auth/guards/jwt-auth.guard';
|
||||
import { RolesGuard } from './auth/guards/roles.guard';
|
||||
import { PermissionsGuard } from './auth/guards/permissions.guard';
|
||||
import { PermissionsModule } from './auth/permissions/permissions.module';
|
||||
|
||||
@@ -86,7 +85,6 @@ import { PermissionsModule } from './auth/permissions/permissions.module';
|
||||
controllers: [],
|
||||
providers: [
|
||||
{ provide: APP_GUARD, useClass: JwtAuthGuard },
|
||||
{ provide: APP_GUARD, useClass: RolesGuard },
|
||||
{ provide: APP_GUARD, useClass: PermissionsGuard },
|
||||
{ provide: APP_GUARD, useClass: ThrottlerGuard },
|
||||
],
|
||||
|
||||
@@ -23,7 +23,6 @@ describe('AuthService', () => {
|
||||
const activeUser = {
|
||||
id: 'user-1',
|
||||
email: '[email protected]',
|
||||
legacyRole: 'STAFF',
|
||||
isActive: true,
|
||||
passwordHash: '',
|
||||
};
|
||||
|
||||
@@ -18,7 +18,6 @@ export interface CurrentUserProfile {
|
||||
id: string;
|
||||
email: string;
|
||||
name: string;
|
||||
role: string;
|
||||
roleKey: string;
|
||||
roleName: string;
|
||||
permissions: string[];
|
||||
@@ -46,7 +45,6 @@ export class AuthService {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
name: user.name,
|
||||
role: user.legacyRole,
|
||||
roleKey: user.role.key,
|
||||
roleName: user.role.name,
|
||||
permissions: Array.from(permissions),
|
||||
@@ -62,7 +60,7 @@ export class AuthService {
|
||||
parseDurationToMs(process.env.JWT_ACCESS_EXPIRES_IN ?? '15m') / 1000,
|
||||
);
|
||||
return this.jwtService.sign(
|
||||
{ sub: user.id, email: user.email, role: user.role },
|
||||
{ sub: user.id, email: user.email },
|
||||
{
|
||||
secret: process.env.JWT_ACCESS_SECRET,
|
||||
expiresIn: expiresInSeconds,
|
||||
@@ -106,7 +104,6 @@ export class AuthService {
|
||||
const authenticatedUser: AuthenticatedUser = {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
role: user.legacyRole,
|
||||
};
|
||||
const accessToken = this.signAccessToken(authenticatedUser);
|
||||
const refreshToken = await this.issueRefreshToken(user.id);
|
||||
@@ -138,7 +135,6 @@ export class AuthService {
|
||||
const authenticatedUser: AuthenticatedUser = {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
role: user.legacyRole,
|
||||
};
|
||||
const accessToken = this.signAccessToken(authenticatedUser);
|
||||
const newRefreshToken = await this.issueRefreshToken(user.id);
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
import { SetMetadata } from '@nestjs/common';
|
||||
import { LegacyRole as Role } from '../../../generated/prisma';
|
||||
|
||||
export const ROLES_KEY = 'roles';
|
||||
export const Roles = (...roles: Role[]) => SetMetadata(ROLES_KEY, roles);
|
||||
@@ -1,48 +0,0 @@
|
||||
import { ExecutionContext } from '@nestjs/common';
|
||||
import { Reflector } from '@nestjs/core';
|
||||
import { RolesGuard } from './roles.guard';
|
||||
import { LegacyRole as Role } from '../../../generated/prisma';
|
||||
|
||||
function createContext(user: { role: Role } | undefined): ExecutionContext {
|
||||
return {
|
||||
getHandler: () => ({}),
|
||||
getClass: () => ({}),
|
||||
switchToHttp: () => ({
|
||||
getRequest: () => ({ user }),
|
||||
}),
|
||||
} as unknown as ExecutionContext;
|
||||
}
|
||||
|
||||
describe('RolesGuard', () => {
|
||||
it('allows access when no roles are required', () => {
|
||||
const reflector = {
|
||||
getAllAndOverride: () => undefined,
|
||||
} as unknown as Reflector;
|
||||
const guard = new RolesGuard(reflector);
|
||||
expect(guard.canActivate(createContext(undefined))).toBe(true);
|
||||
});
|
||||
|
||||
it('denies access when the user role does not match', () => {
|
||||
const reflector = {
|
||||
getAllAndOverride: () => [Role.ADMIN],
|
||||
} as unknown as Reflector;
|
||||
const guard = new RolesGuard(reflector);
|
||||
expect(guard.canActivate(createContext({ role: Role.STAFF }))).toBe(false);
|
||||
});
|
||||
|
||||
it('allows access when the user role matches', () => {
|
||||
const reflector = {
|
||||
getAllAndOverride: () => [Role.ADMIN],
|
||||
} as unknown as Reflector;
|
||||
const guard = new RolesGuard(reflector);
|
||||
expect(guard.canActivate(createContext({ role: Role.ADMIN }))).toBe(true);
|
||||
});
|
||||
|
||||
it('denies access when no user is attached to the request', () => {
|
||||
const reflector = {
|
||||
getAllAndOverride: () => [Role.ADMIN],
|
||||
} as unknown as Reflector;
|
||||
const guard = new RolesGuard(reflector);
|
||||
expect(guard.canActivate(createContext(undefined))).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,27 +0,0 @@
|
||||
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
|
||||
import { Reflector } from '@nestjs/core';
|
||||
import { LegacyRole as Role } from '../../../generated/prisma';
|
||||
import { ROLES_KEY } from '../decorators/roles.decorator';
|
||||
import { AuthenticatedUser } from '../types/authenticated-user';
|
||||
|
||||
interface RequestWithUser {
|
||||
user?: AuthenticatedUser;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class RolesGuard implements CanActivate {
|
||||
constructor(private readonly reflector: Reflector) {}
|
||||
|
||||
canActivate(context: ExecutionContext): boolean {
|
||||
const requiredRoles = this.reflector.getAllAndOverride<Role[]>(ROLES_KEY, [
|
||||
context.getHandler(),
|
||||
context.getClass(),
|
||||
]);
|
||||
if (!requiredRoles || requiredRoles.length === 0) {
|
||||
return true;
|
||||
}
|
||||
const request = context.switchToHttp().getRequest<RequestWithUser>();
|
||||
const user = request.user;
|
||||
return !!user && requiredRoles.includes(user.role);
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,6 @@ import { AuthenticatedUser } from '../types/authenticated-user';
|
||||
interface AccessTokenPayload {
|
||||
sub: string;
|
||||
email: string;
|
||||
role: AuthenticatedUser['role'];
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
@@ -20,6 +19,6 @@ export class JwtStrategy extends PassportStrategy(Strategy) {
|
||||
}
|
||||
|
||||
validate(payload: AccessTokenPayload): AuthenticatedUser {
|
||||
return { id: payload.sub, email: payload.email, role: payload.role };
|
||||
return { id: payload.sub, email: payload.email };
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,4 @@
|
||||
import { LegacyRole as Role } from '../../../generated/prisma';
|
||||
|
||||
export interface AuthenticatedUser {
|
||||
id: string;
|
||||
email: string;
|
||||
role: Role;
|
||||
}
|
||||
@@ -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');
|
||||
|
||||
@@ -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',
|
||||
|
||||
Reference in new issue
Block a user