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:
1 parent
eae3fea957
commit
ae8f6d4435
46 files changed
+1258
-98
No files matched your search
@@ -0,0 +1,34 @@
|
||||
import { Body, Controller, HttpCode, HttpStatus, Post } from '@nestjs/common';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { Public } from './decorators/public.decorator';
|
||||
import { LoginDto } from './dto/login.dto';
|
||||
import { RefreshTokenDto } from './dto/refresh-token.dto';
|
||||
import { AuthTokensDto } from './dto/auth-tokens.dto';
|
||||
import { AuthService } from './auth.service';
|
||||
|
||||
@ApiTags('auth')
|
||||
@Controller('auth')
|
||||
export class AuthController {
|
||||
constructor(private readonly authService: AuthService) {}
|
||||
|
||||
@Public()
|
||||
@Post('login')
|
||||
@HttpCode(HttpStatus.OK)
|
||||
login(@Body() dto: LoginDto): Promise<AuthTokensDto> {
|
||||
return this.authService.login(dto.email, dto.password);
|
||||
}
|
||||
|
||||
@Public()
|
||||
@Post('refresh')
|
||||
@HttpCode(HttpStatus.OK)
|
||||
refresh(@Body() dto: RefreshTokenDto): Promise<AuthTokensDto> {
|
||||
return this.authService.refresh(dto.refreshToken);
|
||||
}
|
||||
|
||||
@Public()
|
||||
@Post('logout')
|
||||
@HttpCode(HttpStatus.NO_CONTENT)
|
||||
async logout(@Body() dto: RefreshTokenDto): Promise<void> {
|
||||
await this.authService.logout(dto.refreshToken);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { JwtModule } from '@nestjs/jwt';
|
||||
import { PassportModule } from '@nestjs/passport';
|
||||
import { UsersModule } from '../users/users.module';
|
||||
import { AuthController } from './auth.controller';
|
||||
import { AuthService } from './auth.service';
|
||||
import { JwtStrategy } from './strategies/jwt.strategy';
|
||||
|
||||
@Module({
|
||||
imports: [PassportModule, JwtModule.register({}), UsersModule],
|
||||
controllers: [AuthController],
|
||||
providers: [AuthService, JwtStrategy],
|
||||
})
|
||||
export class AuthModule {}
|
||||
@@ -0,0 +1,150 @@
|
||||
import { UnauthorizedException } from '@nestjs/common';
|
||||
import * as bcrypt from 'bcryptjs';
|
||||
import { AuthService } from './auth.service';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { UsersService } from '../users/users.service';
|
||||
|
||||
describe('AuthService', () => {
|
||||
let authService: AuthService;
|
||||
let usersService: { findByEmail: jest.Mock; findById: jest.Mock };
|
||||
let prisma: {
|
||||
refreshToken: {
|
||||
create: jest.Mock;
|
||||
findUnique: jest.Mock;
|
||||
update: jest.Mock;
|
||||
updateMany: jest.Mock;
|
||||
};
|
||||
};
|
||||
let jwtService: { sign: jest.Mock };
|
||||
|
||||
const activeUser = {
|
||||
id: 'user-1',
|
||||
email: '[email protected]',
|
||||
role: 'STAFF',
|
||||
isActive: true,
|
||||
passwordHash: '',
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
activeUser.passwordHash = await bcrypt.hash('correct-password', 4);
|
||||
usersService = { findByEmail: jest.fn(), findById: jest.fn() };
|
||||
prisma = {
|
||||
refreshToken: {
|
||||
create: jest.fn(),
|
||||
findUnique: jest.fn(),
|
||||
update: jest.fn(),
|
||||
updateMany: jest.fn(),
|
||||
},
|
||||
};
|
||||
jwtService = { sign: jest.fn().mockReturnValue('signed.jwt.token') };
|
||||
|
||||
authService = new AuthService(
|
||||
usersService as unknown as UsersService,
|
||||
prisma as unknown as PrismaService,
|
||||
jwtService as never,
|
||||
);
|
||||
});
|
||||
|
||||
describe('login', () => {
|
||||
it('throws when the user does not exist', async () => {
|
||||
usersService.findByEmail.mockResolvedValue(null);
|
||||
await expect(
|
||||
authService.login('[email protected]', 'x'),
|
||||
).rejects.toBeInstanceOf(UnauthorizedException);
|
||||
});
|
||||
|
||||
it('throws when the user is deactivated', async () => {
|
||||
usersService.findByEmail.mockResolvedValue({
|
||||
...activeUser,
|
||||
isActive: false,
|
||||
});
|
||||
await expect(
|
||||
authService.login(activeUser.email, 'correct-password'),
|
||||
).rejects.toBeInstanceOf(UnauthorizedException);
|
||||
});
|
||||
|
||||
it('throws when the password does not match', async () => {
|
||||
usersService.findByEmail.mockResolvedValue(activeUser);
|
||||
await expect(
|
||||
authService.login(activeUser.email, 'wrong-password'),
|
||||
).rejects.toBeInstanceOf(UnauthorizedException);
|
||||
});
|
||||
|
||||
it('returns tokens and stores a hashed refresh token on success', async () => {
|
||||
usersService.findByEmail.mockResolvedValue(activeUser);
|
||||
prisma.refreshToken.create.mockResolvedValue({});
|
||||
|
||||
const result = await authService.login(
|
||||
activeUser.email,
|
||||
'correct-password',
|
||||
);
|
||||
|
||||
expect(result.accessToken).toBe('signed.jwt.token');
|
||||
expect(result.refreshToken).toEqual(expect.any(String));
|
||||
const [[createArg]] = prisma.refreshToken.create.mock.calls as [
|
||||
[{ data: { userId: string } }],
|
||||
];
|
||||
expect(createArg.data.userId).toBe(activeUser.id);
|
||||
});
|
||||
});
|
||||
|
||||
describe('refresh', () => {
|
||||
it('throws when the refresh token is unknown', async () => {
|
||||
prisma.refreshToken.findUnique.mockResolvedValue(null);
|
||||
await expect(authService.refresh('unknown-token')).rejects.toBeInstanceOf(
|
||||
UnauthorizedException,
|
||||
);
|
||||
});
|
||||
|
||||
it('throws when the refresh token is revoked', async () => {
|
||||
prisma.refreshToken.findUnique.mockResolvedValue({
|
||||
id: 'rt-1',
|
||||
userId: activeUser.id,
|
||||
revokedAt: new Date(),
|
||||
expiresAt: new Date(Date.now() + 1000),
|
||||
});
|
||||
await expect(authService.refresh('revoked-token')).rejects.toBeInstanceOf(
|
||||
UnauthorizedException,
|
||||
);
|
||||
});
|
||||
|
||||
it('throws when the refresh token is expired', async () => {
|
||||
prisma.refreshToken.findUnique.mockResolvedValue({
|
||||
id: 'rt-1',
|
||||
userId: activeUser.id,
|
||||
revokedAt: null,
|
||||
expiresAt: new Date(Date.now() - 1000),
|
||||
});
|
||||
await expect(authService.refresh('expired-token')).rejects.toBeInstanceOf(
|
||||
UnauthorizedException,
|
||||
);
|
||||
});
|
||||
|
||||
it('rotates the refresh token on success', async () => {
|
||||
prisma.refreshToken.findUnique.mockResolvedValue({
|
||||
id: 'rt-1',
|
||||
userId: activeUser.id,
|
||||
revokedAt: null,
|
||||
expiresAt: new Date(Date.now() + 1000),
|
||||
});
|
||||
usersService.findById.mockResolvedValue(activeUser);
|
||||
prisma.refreshToken.update.mockResolvedValue({});
|
||||
prisma.refreshToken.create.mockResolvedValue({});
|
||||
|
||||
const result = await authService.refresh('valid-token');
|
||||
|
||||
expect(result.accessToken).toBe('signed.jwt.token');
|
||||
expect(prisma.refreshToken.update).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ where: { id: 'rt-1' } }),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('logout', () => {
|
||||
it('revokes the matching refresh token', async () => {
|
||||
prisma.refreshToken.updateMany.mockResolvedValue({ count: 1 });
|
||||
await authService.logout('some-token');
|
||||
expect(prisma.refreshToken.updateMany).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,106 @@
|
||||
import { Injectable, UnauthorizedException } from '@nestjs/common';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import * as bcrypt from 'bcryptjs';
|
||||
import * as crypto from 'node:crypto';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { UsersService } from '../users/users.service';
|
||||
import { AuthenticatedUser } from './types/authenticated-user';
|
||||
import { parseDurationToMs } from './util/duration';
|
||||
|
||||
interface AuthTokens {
|
||||
accessToken: string;
|
||||
refreshToken: string;
|
||||
}
|
||||
|
||||
const REFRESH_TOKEN_BYTES = 40;
|
||||
|
||||
@Injectable()
|
||||
export class AuthService {
|
||||
constructor(
|
||||
private readonly usersService: UsersService,
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly jwtService: JwtService,
|
||||
) {}
|
||||
|
||||
private hashRefreshToken(token: string): string {
|
||||
return crypto.createHash('sha256').update(token).digest('hex');
|
||||
}
|
||||
|
||||
private signAccessToken(user: AuthenticatedUser): string {
|
||||
const expiresInSeconds = Math.floor(
|
||||
parseDurationToMs(process.env.JWT_ACCESS_EXPIRES_IN ?? '15m') / 1000,
|
||||
);
|
||||
return this.jwtService.sign(
|
||||
{ sub: user.id, email: user.email, role: user.role },
|
||||
{
|
||||
secret: process.env.JWT_ACCESS_SECRET,
|
||||
expiresIn: expiresInSeconds,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
private async issueRefreshToken(userId: string): Promise<string> {
|
||||
const token = crypto.randomBytes(REFRESH_TOKEN_BYTES).toString('hex');
|
||||
const expiresAt = new Date(
|
||||
Date.now() +
|
||||
parseDurationToMs(process.env.JWT_REFRESH_EXPIRES_IN ?? '7d'),
|
||||
);
|
||||
await this.prisma.refreshToken.create({
|
||||
data: { userId, tokenHash: this.hashRefreshToken(token), expiresAt },
|
||||
});
|
||||
return token;
|
||||
}
|
||||
|
||||
async login(email: string, password: string): Promise<AuthTokens> {
|
||||
const user = await this.usersService.findByEmail(email);
|
||||
if (!user || !user.isActive) {
|
||||
throw new UnauthorizedException('Invalid credentials');
|
||||
}
|
||||
const passwordMatches = await bcrypt.compare(password, user.passwordHash);
|
||||
if (!passwordMatches) {
|
||||
throw new UnauthorizedException('Invalid credentials');
|
||||
}
|
||||
const authenticatedUser: AuthenticatedUser = {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
role: user.role,
|
||||
};
|
||||
const accessToken = this.signAccessToken(authenticatedUser);
|
||||
const refreshToken = await this.issueRefreshToken(user.id);
|
||||
return { accessToken, refreshToken };
|
||||
}
|
||||
|
||||
async refresh(refreshToken: string): Promise<AuthTokens> {
|
||||
const tokenHash = this.hashRefreshToken(refreshToken);
|
||||
const stored = await this.prisma.refreshToken.findUnique({
|
||||
where: { tokenHash },
|
||||
});
|
||||
if (!stored || stored.revokedAt || stored.expiresAt < new Date()) {
|
||||
throw new UnauthorizedException('Invalid refresh token');
|
||||
}
|
||||
const user = await this.usersService.findById(stored.userId);
|
||||
if (!user.isActive) {
|
||||
throw new UnauthorizedException('Invalid refresh token');
|
||||
}
|
||||
await this.prisma.refreshToken.update({
|
||||
where: { id: stored.id },
|
||||
data: { revokedAt: new Date() },
|
||||
});
|
||||
const authenticatedUser: AuthenticatedUser = {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
role: user.role,
|
||||
};
|
||||
const accessToken = this.signAccessToken(authenticatedUser);
|
||||
const newRefreshToken = await this.issueRefreshToken(user.id);
|
||||
return { accessToken, refreshToken: newRefreshToken };
|
||||
}
|
||||
|
||||
async logout(refreshToken: string): Promise<void> {
|
||||
const tokenHash = this.hashRefreshToken(refreshToken);
|
||||
await this.prisma.refreshToken.updateMany({
|
||||
where: { tokenHash, revokedAt: null },
|
||||
data: { revokedAt: new Date() },
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
|
||||
import { AuthenticatedUser } from '../types/authenticated-user';
|
||||
|
||||
interface RequestWithUser {
|
||||
user: AuthenticatedUser;
|
||||
}
|
||||
|
||||
export const CurrentUser = createParamDecorator(
|
||||
(_data: unknown, ctx: ExecutionContext): AuthenticatedUser => {
|
||||
const request = ctx.switchToHttp().getRequest<RequestWithUser>();
|
||||
return request.user;
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,4 @@
|
||||
import { SetMetadata } from '@nestjs/common';
|
||||
|
||||
export const IS_PUBLIC_KEY = 'isPublic';
|
||||
export const Public = () => SetMetadata(IS_PUBLIC_KEY, true);
|
||||
@@ -0,0 +1,5 @@
|
||||
import { SetMetadata } from '@nestjs/common';
|
||||
import { Role } from '../../../generated/prisma';
|
||||
|
||||
export const ROLES_KEY = 'roles';
|
||||
export const Roles = (...roles: Role[]) => SetMetadata(ROLES_KEY, roles);
|
||||
@@ -0,0 +1,9 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
|
||||
export class AuthTokensDto {
|
||||
@ApiProperty()
|
||||
accessToken!: string;
|
||||
|
||||
@ApiProperty()
|
||||
refreshToken!: string;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsEmail, IsString, MinLength } from 'class-validator';
|
||||
|
||||
export class LoginDto {
|
||||
@ApiProperty()
|
||||
@IsEmail()
|
||||
email!: string;
|
||||
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
@MinLength(8)
|
||||
password!: string;
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsString } from 'class-validator';
|
||||
|
||||
export class RefreshTokenDto {
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
refreshToken!: string;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { ExecutionContext, Injectable } from '@nestjs/common';
|
||||
import { Reflector } from '@nestjs/core';
|
||||
import { AuthGuard } from '@nestjs/passport';
|
||||
import { IS_PUBLIC_KEY } from '../decorators/public.decorator';
|
||||
|
||||
@Injectable()
|
||||
export class JwtAuthGuard extends AuthGuard('jwt') {
|
||||
constructor(private readonly reflector: Reflector) {
|
||||
super();
|
||||
}
|
||||
|
||||
canActivate(context: ExecutionContext) {
|
||||
const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
|
||||
context.getHandler(),
|
||||
context.getClass(),
|
||||
]);
|
||||
if (isPublic) {
|
||||
return true;
|
||||
}
|
||||
return super.canActivate(context);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { ExecutionContext } from '@nestjs/common';
|
||||
import { Reflector } from '@nestjs/core';
|
||||
import { RolesGuard } from './roles.guard';
|
||||
import { 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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
|
||||
import { Reflector } from '@nestjs/core';
|
||||
import { 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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { PassportStrategy } from '@nestjs/passport';
|
||||
import { ExtractJwt, Strategy } from 'passport-jwt';
|
||||
import { AuthenticatedUser } from '../types/authenticated-user';
|
||||
|
||||
interface AccessTokenPayload {
|
||||
sub: string;
|
||||
email: string;
|
||||
role: AuthenticatedUser['role'];
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class JwtStrategy extends PassportStrategy(Strategy) {
|
||||
constructor() {
|
||||
super({
|
||||
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
||||
ignoreExpiration: false,
|
||||
secretOrKey: process.env.JWT_ACCESS_SECRET as string,
|
||||
});
|
||||
}
|
||||
|
||||
validate(payload: AccessTokenPayload): AuthenticatedUser {
|
||||
return { id: payload.sub, email: payload.email, role: payload.role };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { Role } from '../../../generated/prisma';
|
||||
|
||||
export interface AuthenticatedUser {
|
||||
id: string;
|
||||
email: string;
|
||||
role: Role;
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { parseDurationToMs } from './duration';
|
||||
|
||||
describe('parseDurationToMs', () => {
|
||||
it.each([
|
||||
['15s', 15_000],
|
||||
['15m', 900_000],
|
||||
['2h', 7_200_000],
|
||||
['7d', 604_800_000],
|
||||
])('parses %s to %i ms', (spec, expected) => {
|
||||
expect(parseDurationToMs(spec)).toBe(expected);
|
||||
});
|
||||
|
||||
it('throws on an invalid spec', () => {
|
||||
expect(() => parseDurationToMs('not-a-duration')).toThrow(
|
||||
'Invalid duration spec',
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,15 @@
|
||||
const UNIT_MS: Record<string, number> = {
|
||||
s: 1000,
|
||||
m: 60_000,
|
||||
h: 3_600_000,
|
||||
d: 86_400_000,
|
||||
};
|
||||
|
||||
export function parseDurationToMs(spec: string): number {
|
||||
const match = /^(\d+)(s|m|h|d)$/.exec(spec.trim());
|
||||
if (!match) {
|
||||
throw new Error(`Invalid duration spec: ${spec}`);
|
||||
}
|
||||
const [, amount, unit] = match;
|
||||
return Number(amount) * UNIT_MS[unit];
|
||||
}
|
||||
Reference in new issue
Block a user