feat(02-03): password reset flow, force-change interceptor, MailModule

- MailModule with SMTP transport configured from ENV variables
- MailService for password reset and welcome emails (plain text, i18n)
- Password reset flow: request-reset (public), reset-password (token-based)
- Change password for logged-in users with current password verification
- Admin reset password endpoint (ADMIN/SUPER_ADMIN only, D-03)
- ForcePasswordChangeInterceptor blocks all routes except change-password,
  logout, me when mustChangePassword=true (D-06, Pitfall 5)
- Frontend: reset-password request page, token reset page, change-password page
- Forgot password link added to login page
- MailHog service added to docker-compose.dev.yml for dev email testing
- SMTP env vars added to docker-compose.yml (defaults to MailHog)
- Complete DE/EN i18n coverage for reset and change password flows
- SUS packages installed: @nestjs-modules/mailer, nodemailer, ldapts

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-06-18 13:48:23 +02:00
parent eaaa9adfa5
commit ac617f4fe5
20 changed files with 4216 additions and 12 deletions
+9 -1
View File
@@ -1,10 +1,12 @@
import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { APP_GUARD } from '@nestjs/core';
import { APP_GUARD, APP_INTERCEPTOR } from '@nestjs/core';
import { AuthModule } from './auth/auth.module';
import { JwtAuthGuard } from './auth/guards/jwt-auth.guard';
import { RolesGuard } from './auth/guards/roles.guard';
import { ForcePasswordChangeInterceptor } from './auth/interceptors/force-password-change.interceptor';
import { HealthModule } from './health/health.module';
import { MailModule } from './mail/mail.module';
import { PrismaModule } from './prisma/prisma.module';
import { TenantMiddleware } from './tenant/tenant.middleware';
import { TenantModule } from './tenant/tenant.module';
@@ -18,6 +20,7 @@ import { UserModule } from './user/user.module';
UserModule,
TenantModule,
HealthModule,
MailModule,
],
providers: [
// Global JWT guard: all routes require auth unless @Public()
@@ -30,6 +33,11 @@ import { UserModule } from './user/user.module';
provide: APP_GUARD,
useClass: RolesGuard,
},
// Global interceptor: forces password change if mustChangePassword=true (D-06 / Pitfall 5)
{
provide: APP_INTERCEPTOR,
useClass: ForcePasswordChangeInterceptor,
},
],
})
export class AppModule implements NestModule {
+75
View File
@@ -1,17 +1,25 @@
import {
Body,
Controller,
Get,
HttpCode,
Param,
Post,
Req,
Res,
UseGuards,
} from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { Role } from '@prisma/client';
import { Request, Response } from 'express';
import { AuthService } from './auth.service';
import { CurrentUser } from './decorators/current-user.decorator';
import { Public } from './decorators/public.decorator';
import { Roles } from './decorators/roles.decorator';
import { AdminResetPasswordDto } from './dto/admin-reset-password.dto';
import { ChangePasswordDto } from './dto/change-password.dto';
import { RequestResetDto, ResetPasswordDto } from './dto/reset-password.dto';
import { RolesGuard } from './guards/roles.guard';
@Controller('auth')
export class AuthController {
@@ -51,4 +59,71 @@ export class AuthController {
me(@CurrentUser() user: any) {
return user;
}
/**
* POST /auth/request-reset
* Request a password reset email (D-03 self-service).
* @Public() -- no authentication required.
* T-02-12: Always returns 200 regardless of email existence.
*/
@Public()
@Post('request-reset')
@HttpCode(200)
async requestReset(@Body() dto: RequestResetDto) {
await this.authService.requestPasswordReset(dto.email);
return { message: 'If an account with this email exists, a reset link has been sent.' };
}
/**
* POST /auth/reset-password
* Reset password using a valid token (D-03 self-service).
* @Public() -- no authentication required (uses token for verification).
*/
@Public()
@Post('reset-password')
@HttpCode(200)
async resetPassword(@Body() dto: ResetPasswordDto) {
await this.authService.resetPassword(dto.token, dto.newPassword);
return { message: 'Password has been reset successfully.' };
}
/**
* POST /auth/change-password
* Change password for the currently logged-in user.
* Requires authentication (not @Public).
*/
@Post('change-password')
@HttpCode(200)
async changePassword(
@CurrentUser() user: any,
@Body() dto: ChangePasswordDto,
) {
await this.authService.changePassword(
user.sub,
dto.currentPassword,
dto.newPassword,
);
return { message: 'Password changed successfully.' };
}
/**
* POST /auth/admin-reset-password/:userId
* Admin resets a user's password (D-03 admin reset).
* T-02-15: Only ADMIN/SUPER_ADMIN via RolesGuard.
*/
@Post('admin-reset-password/:userId')
@Roles(Role.ADMIN, Role.SUPER_ADMIN)
@UseGuards(RolesGuard)
@HttpCode(200)
async adminResetPassword(
@Param('userId') userId: string,
@Body() dto: AdminResetPasswordDto,
) {
await this.authService.adminResetPassword(
userId,
dto.newPassword,
dto.mustChangePassword ?? true,
);
return { message: 'User password has been reset.' };
}
}
+2
View File
@@ -2,6 +2,7 @@ import { Module } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { JwtModule } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport';
import { MailModule } from '../mail/mail.module';
import { AuthController } from './auth.controller';
import { AuthService } from './auth.service';
import { JwtStrategy } from './strategies/jwt.strategy';
@@ -17,6 +18,7 @@ import { LocalStrategy } from './strategies/local.strategy';
}),
inject: [ConfigService],
}),
MailModule,
],
controllers: [AuthController],
providers: [AuthService, LocalStrategy, JwtStrategy],
+155 -1
View File
@@ -1,16 +1,26 @@
import { Injectable } from '@nestjs/common';
import {
BadRequestException,
Injectable,
Logger,
UnauthorizedException,
} from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { JwtService } from '@nestjs/jwt';
import * as argon2 from 'argon2';
import { randomUUID } from 'crypto';
import { Response } from 'express';
import { MailService } from '../mail/mail.service';
import { PrismaService } from '../prisma/prisma.service';
@Injectable()
export class AuthService {
private readonly logger = new Logger(AuthService.name);
constructor(
private prisma: PrismaService,
private jwtService: JwtService,
private configService: ConfigService,
private mailService: MailService,
) {}
/**
@@ -59,6 +69,7 @@ export class AuthService {
username: user.username,
role: user.role,
tenantId: user.tenantId,
mustChangePassword: user.mustChangePassword,
};
const token = this.jwtService.sign(payload);
@@ -92,4 +103,147 @@ export class AuthService {
path: '/',
});
}
/**
* Request a password reset (D-03 self-service).
* T-02-12: Always returns success, even if email not found (prevent enumeration).
* T-02-13: Single-use token with 1-hour expiry.
*/
async requestPasswordReset(email: string): Promise<void> {
const user = await this.prisma.user.findUnique({
where: { email },
});
// Always return success to prevent email enumeration (T-02-12)
if (!user || !user.isActive) {
this.logger.log(
`Password reset requested for unknown/inactive email: ${email}`,
);
return;
}
// Generate a unique reset token
const token = randomUUID();
const expiresAt = new Date(Date.now() + 60 * 60 * 1000); // 1 hour
// Create the reset token record
await this.prisma.passwordResetToken.create({
data: {
token,
userId: user.id,
expiresAt,
},
});
// Send the reset email (fire-and-forget, errors logged by MailService)
await this.mailService.sendPasswordResetEmail(email, token);
}
/**
* Reset password using a valid token (D-03 self-service).
* T-02-13: Validates token not expired, not used. Marks as used after success.
*/
async resetPassword(token: string, newPassword: string): Promise<void> {
const resetToken = await this.prisma.passwordResetToken.findUnique({
where: { token },
include: { user: true },
});
if (!resetToken) {
throw new BadRequestException('Invalid or expired reset token');
}
// Check if token has already been used
if (resetToken.usedAt) {
throw new BadRequestException('Reset token has already been used');
}
// Check if token has expired
if (resetToken.expiresAt < new Date()) {
throw new BadRequestException('Reset token has expired');
}
// Hash the new password and update user
const passwordHash = await argon2.hash(newPassword);
await this.prisma.user.update({
where: { id: resetToken.userId },
data: {
passwordHash,
mustChangePassword: false,
},
});
// Mark token as used (T-02-13)
await this.prisma.passwordResetToken.update({
where: { id: resetToken.id },
data: { usedAt: new Date() },
});
this.logger.log(`Password reset completed for user ${resetToken.userId}`);
}
/**
* Change password for the currently logged-in user.
* Verifies current password before allowing change.
*/
async changePassword(
userId: string,
currentPassword: string,
newPassword: string,
): Promise<void> {
const user = await this.prisma.user.findUnique({
where: { id: userId },
});
if (!user || !user.passwordHash) {
throw new UnauthorizedException('User not found or has no local password');
}
// Verify current password
const isValid = await argon2.verify(user.passwordHash, currentPassword);
if (!isValid) {
throw new UnauthorizedException('Current password is incorrect');
}
// Hash new password and update
const passwordHash = await argon2.hash(newPassword);
await this.prisma.user.update({
where: { id: userId },
data: {
passwordHash,
mustChangePassword: false,
},
});
this.logger.log(`Password changed for user ${userId}`);
}
/**
* Admin reset of a user's password (D-03 admin reset).
* T-02-15: Only ADMIN/SUPER_ADMIN via RolesGuard.
*/
async adminResetPassword(
userId: string,
newPassword: string,
mustChangePassword: boolean = true,
): Promise<void> {
const user = await this.prisma.user.findUnique({
where: { id: userId },
});
if (!user) {
throw new BadRequestException('User not found');
}
const passwordHash = await argon2.hash(newPassword);
await this.prisma.user.update({
where: { id: userId },
data: {
passwordHash,
mustChangePassword,
},
});
this.logger.log(`Admin reset password for user ${userId}`);
}
}
@@ -0,0 +1,15 @@
import { IsBoolean, IsOptional, IsString, MinLength } from 'class-validator';
/**
* DTO for admin password reset.
* POST /auth/admin-reset-password/:userId
*/
export class AdminResetPasswordDto {
@IsString()
@MinLength(8)
newPassword!: string;
@IsBoolean()
@IsOptional()
mustChangePassword?: boolean;
}
@@ -0,0 +1,14 @@
import { IsString, MinLength } from 'class-validator';
/**
* DTO for changing the current user's password.
* POST /auth/change-password
*/
export class ChangePasswordDto {
@IsString()
currentPassword!: string;
@IsString()
@MinLength(8)
newPassword!: string;
}
@@ -0,0 +1,25 @@
import { IsEmail, IsNotEmpty, IsString, MinLength } from 'class-validator';
/**
* DTO for requesting a password reset email.
* POST /auth/request-reset
*/
export class RequestResetDto {
@IsEmail()
@IsNotEmpty()
email!: string;
}
/**
* DTO for resetting a password with a token.
* POST /auth/reset-password
*/
export class ResetPasswordDto {
@IsString()
@IsNotEmpty()
token!: string;
@IsString()
@MinLength(8)
newPassword!: string;
}
@@ -0,0 +1,72 @@
import {
CallHandler,
ExecutionContext,
ForbiddenException,
Injectable,
NestInterceptor,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { Observable } from 'rxjs';
import { IS_PUBLIC_KEY } from '../decorators/public.decorator';
/**
* Global interceptor: forces users with mustChangePassword=true to change
* their password before accessing any other resource (Pitfall 5 / D-06).
*
* Allowed routes when mustChangePassword=true:
* - POST /auth/change-password (the password change endpoint itself)
* - POST /auth/logout (user should always be able to log out)
* - GET /auth/me (so frontend can detect mustChangePassword flag)
*
* All other routes return 403 with FORCE_PASSWORD_CHANGE message.
* T-02-14: Prevents bypass via direct API access.
*/
@Injectable()
export class ForcePasswordChangeInterceptor implements NestInterceptor {
constructor(private reflector: Reflector) {}
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
// Skip public routes (login, health, reset-password)
const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
context.getHandler(),
context.getClass(),
]);
if (isPublic) {
return next.handle();
}
const request = context.switchToHttp().getRequest();
const user = request.user;
// No user on request (shouldn't happen after auth guard, but be defensive)
if (!user) {
return next.handle();
}
// User doesn't need to change password
if (!user.mustChangePassword) {
return next.handle();
}
// Allow specific routes even when password change is required
const path = request.route?.path || request.url;
const method = request.method;
const allowedPaths = [
'/auth/change-password',
'/auth/logout',
'/auth/me',
];
if (allowedPaths.some((allowed) => path.includes(allowed))) {
return next.handle();
}
// Block all other routes
throw new ForbiddenException({
statusCode: 403,
message: 'FORCE_PASSWORD_CHANGE',
error: 'Must change password before continuing',
});
}
}
+32
View File
@@ -0,0 +1,32 @@
import { Module } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { MailerModule } from '@nestjs-modules/mailer';
import { MailService } from './mail.service';
@Module({
imports: [
MailerModule.forRootAsync({
useFactory: (configService: ConfigService) => ({
transport: {
host: configService.get<string>('TESSERA_SMTP_HOST', 'localhost'),
port: configService.get<number>('TESSERA_SMTP_PORT', 1025),
secure: configService.get<string>('TESSERA_SMTP_SECURE', 'false') === 'true',
auth: {
user: configService.get<string>('TESSERA_SMTP_USER', ''),
pass: configService.get<string>('TESSERA_SMTP_PASSWORD', ''),
},
},
defaults: {
from: configService.get<string>(
'TESSERA_SMTP_FROM',
'Tessera <tessera@tessera.local>',
),
},
}),
inject: [ConfigService],
}),
],
providers: [MailService],
exports: [MailService],
})
export class MailModule {}
+134
View File
@@ -0,0 +1,134 @@
import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { MailerService } from '@nestjs-modules/mailer';
@Injectable()
export class MailService {
private readonly logger = new Logger(MailService.name);
private readonly appUrl: string;
constructor(
private mailerService: MailerService,
private configService: ConfigService,
) {
this.appUrl = this.configService.get<string>(
'TESSERA_APP_URL',
'http://localhost:3000',
);
}
/**
* Send a password reset email with a time-limited token link.
* T-02-12: The caller always returns 200 regardless of whether this succeeds
* (no email enumeration).
*/
async sendPasswordResetEmail(
email: string,
token: string,
locale: string = 'de',
): Promise<void> {
const resetLink = `${this.appUrl}/reset-password/${token}`;
const isGerman = locale === 'de';
const subject = isGerman
? 'Passwort zuruecksetzen - Tessera'
: 'Reset your password - Tessera';
const text = isGerman
? [
'Hallo,',
'',
'Sie haben eine Passwortzuruecksetzung fuer Ihren Tessera-Account angefordert.',
'',
`Klicken Sie auf den folgenden Link, um Ihr Passwort zurueckzusetzen:`,
resetLink,
'',
'Dieser Link ist 1 Stunde gueltig und kann nur einmal verwendet werden.',
'',
'Falls Sie diese Anfrage nicht gestellt haben, koennen Sie diese E-Mail ignorieren.',
'',
'Mit freundlichen Gruessen,',
'Ihr Tessera-Team',
].join('\n')
: [
'Hello,',
'',
'You have requested a password reset for your Tessera account.',
'',
'Click the following link to reset your password:',
resetLink,
'',
'This link is valid for 1 hour and can only be used once.',
'',
'If you did not request this, you can safely ignore this email.',
'',
'Best regards,',
'The Tessera Team',
].join('\n');
try {
await this.mailerService.sendMail({
to: email,
subject,
text,
});
this.logger.log(`Password reset email sent to ${email}`);
} catch (error) {
// Log but don't throw -- caller returns 200 regardless (T-02-12)
this.logger.error(
`Failed to send password reset email to ${email}`,
error instanceof Error ? error.stack : String(error),
);
}
}
/**
* Send a welcome email to a newly created user (optional).
*/
async sendWelcomeEmail(
email: string,
username: string,
locale: string = 'de',
): Promise<void> {
const isGerman = locale === 'de';
const subject = isGerman
? 'Willkommen bei Tessera'
: 'Welcome to Tessera';
const text = isGerman
? [
`Hallo ${username},`,
'',
'Ihr Tessera-Account wurde erstellt.',
'',
`Sie koennen sich unter ${this.appUrl}/login anmelden.`,
'',
'Mit freundlichen Gruessen,',
'Ihr Tessera-Team',
].join('\n')
: [
`Hello ${username},`,
'',
'Your Tessera account has been created.',
'',
`You can sign in at ${this.appUrl}/login.`,
'',
'Best regards,',
'The Tessera Team',
].join('\n');
try {
await this.mailerService.sendMail({
to: email,
subject,
text,
});
this.logger.log(`Welcome email sent to ${email}`);
} catch (error) {
this.logger.error(
`Failed to send welcome email to ${email}`,
error instanceof Error ? error.stack : String(error),
);
}
}
}