feat(backend): Auth/Users/Audit-Modul (Modul 1)

AuthModule: Login/Refresh/Logout mit JWT-Access-Token + rotierendem,
gehashtem Refresh-Token (RefreshToken-Tabelle). JwtAuthGuard + RolesGuard
global via APP_GUARD registriert (gilt fuer jeden kuenftigen Endpunkt),
@Public()-Decorator als Ausnahme (Auth-Endpunkte, /health).

UsersModule: CRUD + Deactivate, nur ADMIN-Rolle, Passwoerter mit bcrypt
gehasht, nie im Response enthalten.

AuditModule: AuditLogService (Grundstruktur), wird von UsersService bei
create/update/deactivate injiziert und geschrieben.

Geteilte App-Konfiguration (Prefix/Versioning/Pipes/Helmet) aus main.ts
in src/app.config.ts extrahiert; e2e-Tests nutzten das vorher nicht und
bekamen dadurch 404 auf jede /api/v1/... Route - jetzt ueber
test/utils/create-test-app.ts geteilt, betrifft alle kuenftigen
e2e-Tests gleichermassen.

prisma/seed.ts legt einen Admin-User fuer lokale Entwicklung an.

26 Unit-Tests + 11 e2e-Tests (gegen echte Postgres-Testdatenbank) gruen,
Lint/Typecheck/Build gruen, Login/Refresh/Logout/Rollenpruefung manuell
gegen laufenden Server verifiziert.
This commit is contained in:
Nick Szaunig committed 2026-08-21 08:22:16 +02:00
1 parent eae3fea957
commit ae8f6d4435
46 files changed
+1258 -98

No files matched your search

@@ -0,0 +1,22 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsEmail, IsEnum, IsString, MinLength } from 'class-validator';
import { Role } from '../../../generated/prisma';
export class CreateUserDto {
@ApiProperty()
@IsEmail()
email!: string;
@ApiProperty()
@IsString()
@MinLength(8)
password!: string;
@ApiProperty()
@IsString()
name!: string;
@ApiProperty({ enum: Role })
@IsEnum(Role)
role!: Role;
}
@@ -0,0 +1,15 @@
import { ApiPropertyOptional } from '@nestjs/swagger';
import { IsEnum, IsOptional, IsString } from 'class-validator';
import { Role } from '../../../generated/prisma';
export class UpdateUserDto {
@ApiPropertyOptional()
@IsOptional()
@IsString()
name?: string;
@ApiPropertyOptional({ enum: Role })
@IsOptional()
@IsEnum(Role)
role?: Role;
}
@@ -0,0 +1,46 @@
import { Body, Controller, Get, Param, Patch, Post } from '@nestjs/common';
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
import { Role } from '../../generated/prisma';
import { Roles } from '../auth/decorators/roles.decorator';
import { CurrentUser } from '../auth/decorators/current-user.decorator';
import type { AuthenticatedUser } from '../auth/types/authenticated-user';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { UsersService } from './users.service';
@ApiTags('users')
@ApiBearerAuth()
@Controller('users')
@Roles(Role.ADMIN)
export class UsersController {
constructor(private readonly usersService: UsersService) {}
@Get()
findAll() {
return this.usersService.findAll();
}
@Post()
create(@Body() dto: CreateUserDto, @CurrentUser() actor: AuthenticatedUser) {
return this.usersService.create(dto, actor.id);
}
@Get(':id')
findOne(@Param('id') id: string) {
return this.usersService.findSummaryById(id);
}
@Patch(':id')
update(
@Param('id') id: string,
@Body() dto: UpdateUserDto,
@CurrentUser() actor: AuthenticatedUser,
) {
return this.usersService.update(id, dto, actor.id);
}
@Post(':id/deactivate')
deactivate(@Param('id') id: string, @CurrentUser() actor: AuthenticatedUser) {
return this.usersService.deactivate(id, actor.id);
}
}
+10
View File
@@ -0,0 +1,10 @@
import { Module } from '@nestjs/common';
import { UsersController } from './users.controller';
import { UsersService } from './users.service';
@Module({
controllers: [UsersController],
providers: [UsersService],
exports: [UsersService],
})
export class UsersModule {}
@@ -0,0 +1,125 @@
import { ConflictException, NotFoundException } from '@nestjs/common';
import { UsersService } from './users.service';
import { PrismaService } from '../prisma/prisma.service';
import { AuditLogService } from '../audit/audit-log.service';
describe('UsersService', () => {
let usersService: UsersService;
let prisma: {
user: {
findMany: jest.Mock;
findUnique: jest.Mock;
create: jest.Mock;
update: jest.Mock;
};
};
let auditLog: { record: jest.Mock };
const existingUser = {
id: 'user-1',
email: '[email protected]',
passwordHash: 'hashed',
name: 'Existing User',
role: 'STAFF',
isActive: true,
createdAt: new Date(),
deactivatedAt: null,
};
beforeEach(() => {
prisma = {
user: {
findMany: jest.fn(),
findUnique: jest.fn(),
create: jest.fn(),
update: jest.fn(),
},
};
auditLog = { record: jest.fn().mockResolvedValue(undefined) };
usersService = new UsersService(
prisma as unknown as PrismaService,
auditLog as unknown as AuditLogService,
);
});
it('findAll returns summaries without the password hash', async () => {
prisma.user.findMany.mockResolvedValue([existingUser]);
const result = await usersService.findAll();
expect(result).toEqual([
{
id: existingUser.id,
email: existingUser.email,
name: existingUser.name,
role: existingUser.role,
isActive: existingUser.isActive,
createdAt: existingUser.createdAt,
deactivatedAt: existingUser.deactivatedAt,
},
]);
expect(result[0]).not.toHaveProperty('passwordHash');
});
it('findById throws NotFoundException when the user is missing', async () => {
prisma.user.findUnique.mockResolvedValue(null);
await expect(usersService.findById('missing')).rejects.toBeInstanceOf(
NotFoundException,
);
});
it('create throws ConflictException when the email is already in use', async () => {
prisma.user.findUnique.mockResolvedValue(existingUser);
await expect(
usersService.create({
email: existingUser.email,
password: 'password123',
name: 'New',
role: 'STAFF',
}),
).rejects.toBeInstanceOf(ConflictException);
});
it('create hashes the password, persists the user, and records an audit entry', async () => {
prisma.user.findUnique.mockResolvedValue(null);
prisma.user.create.mockResolvedValue({
...existingUser,
id: 'user-2',
email: '[email protected]',
});
const result = await usersService.create({
email: '[email protected]',
password: 'password123',
name: 'New User',
role: 'STAFF',
});
expect(result.id).toBe('user-2');
const [[createArg]] = prisma.user.create.mock.calls as [
[{ data: { email: string; passwordHash: string } }],
];
expect(createArg.data.email).toBe('[email protected]');
expect(createArg.data.passwordHash).not.toBe('password123');
expect(auditLog.record).toHaveBeenCalledWith(
expect.objectContaining({ entityType: 'User', action: 'CREATE' }),
);
});
it('deactivate sets isActive to false and records an audit entry', async () => {
prisma.user.findUnique.mockResolvedValue(existingUser);
prisma.user.update.mockResolvedValue({
...existingUser,
isActive: false,
deactivatedAt: new Date(),
});
const result = await usersService.deactivate(existingUser.id);
expect(result.isActive).toBe(false);
expect(result.deactivatedAt).not.toBeNull();
expect(auditLog.record).toHaveBeenCalledWith(
expect.objectContaining({ entityType: 'User', action: 'DEACTIVATE' }),
);
});
});
+119
View File
@@ -0,0 +1,119 @@
import {
ConflictException,
Injectable,
NotFoundException,
} from '@nestjs/common';
import * as bcrypt from 'bcryptjs';
import { PrismaService } from '../prisma/prisma.service';
import { AuditLogService } from '../audit/audit-log.service';
import { User } from '../../generated/prisma';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
const BCRYPT_SALT_ROUNDS = 12;
export interface UserSummary {
id: string;
email: string;
name: string;
role: string;
isActive: boolean;
createdAt: Date;
deactivatedAt: Date | null;
}
@Injectable()
export class UsersService {
constructor(
private readonly prisma: PrismaService,
private readonly auditLog: AuditLogService,
) {}
private toSummary(user: User): UserSummary {
const { id, email, name, role, isActive, createdAt, deactivatedAt } = user;
return { id, email, name, role, isActive, createdAt, deactivatedAt };
}
async findAll(): Promise<UserSummary[]> {
const users = await this.prisma.user.findMany({
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 } });
if (!user) {
throw new NotFoundException('User not found');
}
return user;
}
async findSummaryById(id: string): Promise<UserSummary> {
return this.toSummary(await this.findById(id));
}
async findByEmail(email: string): Promise<User | null> {
return this.prisma.user.findUnique({ where: { email } });
}
async create(
dto: CreateUserDto,
actingUserId?: string,
): Promise<UserSummary> {
const existing = await this.findByEmail(dto.email);
if (existing) {
throw new ConflictException('Email already in use');
}
const passwordHash = await bcrypt.hash(dto.password, BCRYPT_SALT_ROUNDS);
const user = await this.prisma.user.create({
data: { email: dto.email, passwordHash, name: dto.name, role: dto.role },
});
await this.auditLog.record({
entityType: 'User',
entityId: user.id,
action: 'CREATE',
userId: actingUserId,
afterData: this.toSummary(user),
});
return this.toSummary(user);
}
async update(
id: string,
dto: UpdateUserDto,
actingUserId?: string,
): Promise<UserSummary> {
const before = await this.findById(id);
const user = await this.prisma.user.update({
where: { id },
data: { ...dto },
});
await this.auditLog.record({
entityType: 'User',
entityId: id,
action: 'UPDATE',
userId: actingUserId,
beforeData: this.toSummary(before),
afterData: this.toSummary(user),
});
return this.toSummary(user);
}
async deactivate(id: string, actingUserId?: string): Promise<UserSummary> {
const before = await this.findById(id);
const user = await this.prisma.user.update({
where: { id },
data: { isActive: false, deactivatedAt: new Date() },
});
await this.auditLog.record({
entityType: 'User',
entityId: id,
action: 'DEACTIVATE',
userId: actingUserId,
beforeData: this.toSummary(before),
afterData: this.toSummary(user),
});
return this.toSummary(user);
}
}