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:
@@ -9,6 +9,7 @@
|
|||||||
"type-check": "tsc --noEmit"
|
"type-check": "tsc --noEmit"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@nestjs-modules/mailer": "^2.3.7",
|
||||||
"@nestjs/common": "^11.0.0",
|
"@nestjs/common": "^11.0.0",
|
||||||
"@nestjs/config": "^4.0.0",
|
"@nestjs/config": "^4.0.0",
|
||||||
"@nestjs/core": "^11.0.0",
|
"@nestjs/core": "^11.0.0",
|
||||||
@@ -22,6 +23,8 @@
|
|||||||
"class-transformer": "^0.5.1",
|
"class-transformer": "^0.5.1",
|
||||||
"class-validator": "^0.15.1",
|
"class-validator": "^0.15.1",
|
||||||
"cookie-parser": "^1.4.7",
|
"cookie-parser": "^1.4.7",
|
||||||
|
"ldapts": "^8.1.8",
|
||||||
|
"nodemailer": "^9.0.1",
|
||||||
"passport": "^0.7.0",
|
"passport": "^0.7.0",
|
||||||
"passport-jwt": "^4.0.1",
|
"passport-jwt": "^4.0.1",
|
||||||
"passport-local": "^1.0.0",
|
"passport-local": "^1.0.0",
|
||||||
@@ -33,6 +36,7 @@
|
|||||||
"@types/cookie-parser": "^1.4.10",
|
"@types/cookie-parser": "^1.4.10",
|
||||||
"@types/express": "^5.0.0",
|
"@types/express": "^5.0.0",
|
||||||
"@types/node": "^22.0.0",
|
"@types/node": "^22.0.0",
|
||||||
|
"@types/nodemailer": "^8.0.1",
|
||||||
"@types/passport-jwt": "^4.0.1",
|
"@types/passport-jwt": "^4.0.1",
|
||||||
"@types/passport-local": "^1.0.38",
|
"@types/passport-local": "^1.0.38",
|
||||||
"prisma": "^6.0.0",
|
"prisma": "^6.0.0",
|
||||||
|
|||||||
@@ -1,10 +1,12 @@
|
|||||||
import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
|
import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
|
||||||
import { ConfigModule } from '@nestjs/config';
|
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 { AuthModule } from './auth/auth.module';
|
||||||
import { JwtAuthGuard } from './auth/guards/jwt-auth.guard';
|
import { JwtAuthGuard } from './auth/guards/jwt-auth.guard';
|
||||||
import { RolesGuard } from './auth/guards/roles.guard';
|
import { RolesGuard } from './auth/guards/roles.guard';
|
||||||
|
import { ForcePasswordChangeInterceptor } from './auth/interceptors/force-password-change.interceptor';
|
||||||
import { HealthModule } from './health/health.module';
|
import { HealthModule } from './health/health.module';
|
||||||
|
import { MailModule } from './mail/mail.module';
|
||||||
import { PrismaModule } from './prisma/prisma.module';
|
import { PrismaModule } from './prisma/prisma.module';
|
||||||
import { TenantMiddleware } from './tenant/tenant.middleware';
|
import { TenantMiddleware } from './tenant/tenant.middleware';
|
||||||
import { TenantModule } from './tenant/tenant.module';
|
import { TenantModule } from './tenant/tenant.module';
|
||||||
@@ -18,6 +20,7 @@ import { UserModule } from './user/user.module';
|
|||||||
UserModule,
|
UserModule,
|
||||||
TenantModule,
|
TenantModule,
|
||||||
HealthModule,
|
HealthModule,
|
||||||
|
MailModule,
|
||||||
],
|
],
|
||||||
providers: [
|
providers: [
|
||||||
// Global JWT guard: all routes require auth unless @Public()
|
// Global JWT guard: all routes require auth unless @Public()
|
||||||
@@ -30,6 +33,11 @@ import { UserModule } from './user/user.module';
|
|||||||
provide: APP_GUARD,
|
provide: APP_GUARD,
|
||||||
useClass: RolesGuard,
|
useClass: RolesGuard,
|
||||||
},
|
},
|
||||||
|
// Global interceptor: forces password change if mustChangePassword=true (D-06 / Pitfall 5)
|
||||||
|
{
|
||||||
|
provide: APP_INTERCEPTOR,
|
||||||
|
useClass: ForcePasswordChangeInterceptor,
|
||||||
|
},
|
||||||
],
|
],
|
||||||
})
|
})
|
||||||
export class AppModule implements NestModule {
|
export class AppModule implements NestModule {
|
||||||
|
|||||||
@@ -1,17 +1,25 @@
|
|||||||
import {
|
import {
|
||||||
|
Body,
|
||||||
Controller,
|
Controller,
|
||||||
Get,
|
Get,
|
||||||
HttpCode,
|
HttpCode,
|
||||||
|
Param,
|
||||||
Post,
|
Post,
|
||||||
Req,
|
Req,
|
||||||
Res,
|
Res,
|
||||||
UseGuards,
|
UseGuards,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { AuthGuard } from '@nestjs/passport';
|
import { AuthGuard } from '@nestjs/passport';
|
||||||
|
import { Role } from '@prisma/client';
|
||||||
import { Request, Response } from 'express';
|
import { Request, Response } from 'express';
|
||||||
import { AuthService } from './auth.service';
|
import { AuthService } from './auth.service';
|
||||||
import { CurrentUser } from './decorators/current-user.decorator';
|
import { CurrentUser } from './decorators/current-user.decorator';
|
||||||
import { Public } from './decorators/public.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')
|
@Controller('auth')
|
||||||
export class AuthController {
|
export class AuthController {
|
||||||
@@ -51,4 +59,71 @@ export class AuthController {
|
|||||||
me(@CurrentUser() user: any) {
|
me(@CurrentUser() user: any) {
|
||||||
return user;
|
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,6 +2,7 @@ import { Module } from '@nestjs/common';
|
|||||||
import { ConfigService } from '@nestjs/config';
|
import { ConfigService } from '@nestjs/config';
|
||||||
import { JwtModule } from '@nestjs/jwt';
|
import { JwtModule } from '@nestjs/jwt';
|
||||||
import { PassportModule } from '@nestjs/passport';
|
import { PassportModule } from '@nestjs/passport';
|
||||||
|
import { MailModule } from '../mail/mail.module';
|
||||||
import { AuthController } from './auth.controller';
|
import { AuthController } from './auth.controller';
|
||||||
import { AuthService } from './auth.service';
|
import { AuthService } from './auth.service';
|
||||||
import { JwtStrategy } from './strategies/jwt.strategy';
|
import { JwtStrategy } from './strategies/jwt.strategy';
|
||||||
@@ -17,6 +18,7 @@ import { LocalStrategy } from './strategies/local.strategy';
|
|||||||
}),
|
}),
|
||||||
inject: [ConfigService],
|
inject: [ConfigService],
|
||||||
}),
|
}),
|
||||||
|
MailModule,
|
||||||
],
|
],
|
||||||
controllers: [AuthController],
|
controllers: [AuthController],
|
||||||
providers: [AuthService, LocalStrategy, JwtStrategy],
|
providers: [AuthService, LocalStrategy, JwtStrategy],
|
||||||
|
|||||||
@@ -1,16 +1,26 @@
|
|||||||
import { Injectable } from '@nestjs/common';
|
import {
|
||||||
|
BadRequestException,
|
||||||
|
Injectable,
|
||||||
|
Logger,
|
||||||
|
UnauthorizedException,
|
||||||
|
} from '@nestjs/common';
|
||||||
import { ConfigService } from '@nestjs/config';
|
import { ConfigService } from '@nestjs/config';
|
||||||
import { JwtService } from '@nestjs/jwt';
|
import { JwtService } from '@nestjs/jwt';
|
||||||
import * as argon2 from 'argon2';
|
import * as argon2 from 'argon2';
|
||||||
|
import { randomUUID } from 'crypto';
|
||||||
import { Response } from 'express';
|
import { Response } from 'express';
|
||||||
|
import { MailService } from '../mail/mail.service';
|
||||||
import { PrismaService } from '../prisma/prisma.service';
|
import { PrismaService } from '../prisma/prisma.service';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class AuthService {
|
export class AuthService {
|
||||||
|
private readonly logger = new Logger(AuthService.name);
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private prisma: PrismaService,
|
private prisma: PrismaService,
|
||||||
private jwtService: JwtService,
|
private jwtService: JwtService,
|
||||||
private configService: ConfigService,
|
private configService: ConfigService,
|
||||||
|
private mailService: MailService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -59,6 +69,7 @@ export class AuthService {
|
|||||||
username: user.username,
|
username: user.username,
|
||||||
role: user.role,
|
role: user.role,
|
||||||
tenantId: user.tenantId,
|
tenantId: user.tenantId,
|
||||||
|
mustChangePassword: user.mustChangePassword,
|
||||||
};
|
};
|
||||||
|
|
||||||
const token = this.jwtService.sign(payload);
|
const token = this.jwtService.sign(payload);
|
||||||
@@ -92,4 +103,147 @@ export class AuthService {
|
|||||||
path: '/',
|
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',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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 {}
|
||||||
@@ -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),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@
|
|||||||
import { useState, useTransition } from 'react';
|
import { useState, useTransition } from 'react';
|
||||||
import { useTranslations } from 'next-intl';
|
import { useTranslations } from 'next-intl';
|
||||||
import { useRouter } from 'next/navigation';
|
import { useRouter } from 'next/navigation';
|
||||||
|
import Link from 'next/link';
|
||||||
import { login } from '@/lib/auth-actions';
|
import { login } from '@/lib/auth-actions';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -154,6 +155,16 @@ export default function LoginPage() {
|
|||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Forgot password link (D-03) */}
|
||||||
|
<div className="flex justify-end">
|
||||||
|
<Link
|
||||||
|
href="/reset-password"
|
||||||
|
className="text-sm text-muted-foreground hover:text-foreground transition-colors"
|
||||||
|
>
|
||||||
|
{t('forgotPassword')}
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
|
||||||
{/* Submit button */}
|
{/* Submit button */}
|
||||||
<button
|
<button
|
||||||
type="submit"
|
type="submit"
|
||||||
|
|||||||
@@ -0,0 +1,211 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useState, useTransition, useEffect } from 'react';
|
||||||
|
import { useTranslations } from 'next-intl';
|
||||||
|
import { useParams, useRouter } from 'next/navigation';
|
||||||
|
import Link from 'next/link';
|
||||||
|
|
||||||
|
const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Password reset form with token validation (D-03 self-service).
|
||||||
|
* User arrives here from the reset email link.
|
||||||
|
* On success, redirects to /login after 3 seconds.
|
||||||
|
* Part of (auth) route group -- no sidebar/header (D-04).
|
||||||
|
*/
|
||||||
|
export default function ResetPasswordTokenPage() {
|
||||||
|
const t = useTranslations('auth');
|
||||||
|
const router = useRouter();
|
||||||
|
const params = useParams();
|
||||||
|
const token = params.token as string;
|
||||||
|
|
||||||
|
const [isPending, startTransition] = useTransition();
|
||||||
|
const [success, setSuccess] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [passwordMismatch, setPasswordMismatch] = useState(false);
|
||||||
|
|
||||||
|
// Redirect to login after successful reset
|
||||||
|
useEffect(() => {
|
||||||
|
if (!success) return;
|
||||||
|
const timer = setTimeout(() => {
|
||||||
|
router.push('/login');
|
||||||
|
}, 3000);
|
||||||
|
return () => clearTimeout(timer);
|
||||||
|
}, [success, router]);
|
||||||
|
|
||||||
|
async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
|
||||||
|
e.preventDefault();
|
||||||
|
setError(null);
|
||||||
|
setPasswordMismatch(false);
|
||||||
|
|
||||||
|
const formData = new FormData(e.currentTarget);
|
||||||
|
const newPassword = formData.get('newPassword') as string;
|
||||||
|
const confirmPassword = formData.get('confirmPassword') as string;
|
||||||
|
|
||||||
|
if (newPassword !== confirmPassword) {
|
||||||
|
setPasswordMismatch(true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
startTransition(async () => {
|
||||||
|
try {
|
||||||
|
const response = await fetch(`${API_URL}/auth/reset-password`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ token, newPassword }),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
const data = await response.json().catch(() => null);
|
||||||
|
const message = data?.message || '';
|
||||||
|
|
||||||
|
if (message.includes('expired')) {
|
||||||
|
setError('tokenExpired');
|
||||||
|
} else if (message.includes('used')) {
|
||||||
|
setError('tokenUsed');
|
||||||
|
} else {
|
||||||
|
setError('tokenInvalid');
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setSuccess(true);
|
||||||
|
} catch {
|
||||||
|
setError('networkError');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex min-h-screen items-center justify-center bg-background px-4 py-8">
|
||||||
|
<div className="w-full max-w-sm space-y-8">
|
||||||
|
{/* Heading */}
|
||||||
|
<div className="text-center">
|
||||||
|
<h1 className="text-3xl font-extrabold text-primary tracking-tight">
|
||||||
|
Tessera
|
||||||
|
</h1>
|
||||||
|
<h2 className="mt-4 text-2xl font-bold text-foreground">
|
||||||
|
{t('resetPassword.newPasswordTitle')}
|
||||||
|
</h2>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{success ? (
|
||||||
|
/* Success message with redirect notice */
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div className="rounded-md bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 px-4 py-3 text-sm text-green-800 dark:text-green-200">
|
||||||
|
{t('resetPassword.resetSuccess')}
|
||||||
|
</div>
|
||||||
|
<p className="text-sm text-muted-foreground text-center">
|
||||||
|
{t('resetPassword.redirecting')}
|
||||||
|
</p>
|
||||||
|
<Link
|
||||||
|
href="/login"
|
||||||
|
className="flex w-full items-center justify-center rounded-md bg-primary px-4 py-2.5 text-sm font-medium text-primary-foreground hover:opacity-90 transition-opacity"
|
||||||
|
>
|
||||||
|
{t('resetPassword.backToLogin')}
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
{/* Error message */}
|
||||||
|
{error && (
|
||||||
|
<div className="rounded-md bg-destructive/10 border border-destructive/20 px-4 py-3 text-sm text-destructive">
|
||||||
|
{t(`resetPassword.${error}`)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Password mismatch */}
|
||||||
|
{passwordMismatch && (
|
||||||
|
<div className="rounded-md bg-destructive/10 border border-destructive/20 px-4 py-3 text-sm text-destructive">
|
||||||
|
{t('resetPassword.passwordMismatch')}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<form onSubmit={handleSubmit} className="space-y-5">
|
||||||
|
{/* New password */}
|
||||||
|
<div className="space-y-2">
|
||||||
|
<label
|
||||||
|
htmlFor="newPassword"
|
||||||
|
className="text-sm font-medium text-foreground"
|
||||||
|
>
|
||||||
|
{t('resetPassword.newPassword')}
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
id="newPassword"
|
||||||
|
name="newPassword"
|
||||||
|
type="password"
|
||||||
|
required
|
||||||
|
minLength={8}
|
||||||
|
autoComplete="new-password"
|
||||||
|
autoFocus
|
||||||
|
className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
|
||||||
|
placeholder={t('resetPassword.newPassword')}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Confirm password */}
|
||||||
|
<div className="space-y-2">
|
||||||
|
<label
|
||||||
|
htmlFor="confirmPassword"
|
||||||
|
className="text-sm font-medium text-foreground"
|
||||||
|
>
|
||||||
|
{t('resetPassword.confirmPassword')}
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
id="confirmPassword"
|
||||||
|
name="confirmPassword"
|
||||||
|
type="password"
|
||||||
|
required
|
||||||
|
minLength={8}
|
||||||
|
autoComplete="new-password"
|
||||||
|
className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
|
||||||
|
placeholder={t('resetPassword.confirmPassword')}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={isPending}
|
||||||
|
className="flex w-full items-center justify-center rounded-md bg-primary px-4 py-2.5 text-sm font-medium text-primary-foreground hover:opacity-90 transition-opacity disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{isPending ? (
|
||||||
|
<svg
|
||||||
|
className="animate-spin h-4 w-4"
|
||||||
|
xmlns="http://www.w3.org/2000/svg"
|
||||||
|
fill="none"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
>
|
||||||
|
<circle
|
||||||
|
className="opacity-25"
|
||||||
|
cx="12"
|
||||||
|
cy="12"
|
||||||
|
r="10"
|
||||||
|
stroke="currentColor"
|
||||||
|
strokeWidth="4"
|
||||||
|
/>
|
||||||
|
<path
|
||||||
|
className="opacity-75"
|
||||||
|
fill="currentColor"
|
||||||
|
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"
|
||||||
|
/>
|
||||||
|
</svg>
|
||||||
|
) : (
|
||||||
|
t('resetPassword.submitReset')
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<div className="text-center">
|
||||||
|
<Link
|
||||||
|
href="/login"
|
||||||
|
className="text-sm text-muted-foreground hover:text-foreground transition-colors"
|
||||||
|
>
|
||||||
|
{t('resetPassword.backToLogin')}
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,151 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useState, useTransition } from 'react';
|
||||||
|
import { useTranslations } from 'next-intl';
|
||||||
|
import Link from 'next/link';
|
||||||
|
|
||||||
|
const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Password reset request page (D-03 self-service).
|
||||||
|
* Simple form with email input. Always shows success message
|
||||||
|
* regardless of whether email exists (T-02-12: prevent enumeration).
|
||||||
|
* Part of (auth) route group -- no sidebar/header (D-04).
|
||||||
|
*/
|
||||||
|
export default function ResetPasswordPage() {
|
||||||
|
const t = useTranslations('auth');
|
||||||
|
const [isPending, startTransition] = useTransition();
|
||||||
|
const [submitted, setSubmitted] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
|
||||||
|
e.preventDefault();
|
||||||
|
setError(null);
|
||||||
|
|
||||||
|
const formData = new FormData(e.currentTarget);
|
||||||
|
const email = formData.get('email') as string;
|
||||||
|
|
||||||
|
if (!email) return;
|
||||||
|
|
||||||
|
startTransition(async () => {
|
||||||
|
try {
|
||||||
|
const response = await fetch(`${API_URL}/auth/request-reset`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ email }),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
setError('networkError');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setSubmitted(true);
|
||||||
|
} catch {
|
||||||
|
setError('networkError');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex min-h-screen items-center justify-center bg-background px-4 py-8">
|
||||||
|
<div className="w-full max-w-sm space-y-8">
|
||||||
|
{/* Heading */}
|
||||||
|
<div className="text-center">
|
||||||
|
<h1 className="text-3xl font-extrabold text-primary tracking-tight">
|
||||||
|
Tessera
|
||||||
|
</h1>
|
||||||
|
<h2 className="mt-4 text-2xl font-bold text-foreground">
|
||||||
|
{t('resetPassword.title')}
|
||||||
|
</h2>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{submitted ? (
|
||||||
|
/* Success message -- always shown, prevents email enumeration */
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div className="rounded-md bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 px-4 py-3 text-sm text-green-800 dark:text-green-200">
|
||||||
|
{t('resetPassword.success')}
|
||||||
|
</div>
|
||||||
|
<Link
|
||||||
|
href="/login"
|
||||||
|
className="flex w-full items-center justify-center rounded-md bg-primary px-4 py-2.5 text-sm font-medium text-primary-foreground hover:opacity-90 transition-opacity"
|
||||||
|
>
|
||||||
|
{t('resetPassword.backToLogin')}
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
/* Email form */
|
||||||
|
<>
|
||||||
|
{/* Error message */}
|
||||||
|
{error && (
|
||||||
|
<div className="rounded-md bg-destructive/10 border border-destructive/20 px-4 py-3 text-sm text-destructive">
|
||||||
|
{t(`error.${error}`)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<form onSubmit={handleSubmit} className="space-y-5">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<label
|
||||||
|
htmlFor="email"
|
||||||
|
className="text-sm font-medium text-foreground"
|
||||||
|
>
|
||||||
|
{t('resetPassword.email')}
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
id="email"
|
||||||
|
name="email"
|
||||||
|
type="email"
|
||||||
|
required
|
||||||
|
autoComplete="email"
|
||||||
|
autoFocus
|
||||||
|
className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
|
||||||
|
placeholder={t('resetPassword.email')}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={isPending}
|
||||||
|
className="flex w-full items-center justify-center rounded-md bg-primary px-4 py-2.5 text-sm font-medium text-primary-foreground hover:opacity-90 transition-opacity disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{isPending ? (
|
||||||
|
<svg
|
||||||
|
className="animate-spin h-4 w-4"
|
||||||
|
xmlns="http://www.w3.org/2000/svg"
|
||||||
|
fill="none"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
>
|
||||||
|
<circle
|
||||||
|
className="opacity-25"
|
||||||
|
cx="12"
|
||||||
|
cy="12"
|
||||||
|
r="10"
|
||||||
|
stroke="currentColor"
|
||||||
|
strokeWidth="4"
|
||||||
|
/>
|
||||||
|
<path
|
||||||
|
className="opacity-75"
|
||||||
|
fill="currentColor"
|
||||||
|
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"
|
||||||
|
/>
|
||||||
|
</svg>
|
||||||
|
) : (
|
||||||
|
t('resetPassword.submit')
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<div className="text-center">
|
||||||
|
<Link
|
||||||
|
href="/login"
|
||||||
|
className="text-sm text-muted-foreground hover:text-foreground transition-colors"
|
||||||
|
>
|
||||||
|
{t('resetPassword.backToLogin')}
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,207 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useState, useTransition, useEffect } from 'react';
|
||||||
|
import { useTranslations } from 'next-intl';
|
||||||
|
import { useRouter } from 'next/navigation';
|
||||||
|
import { fetchCurrentUser } from '@/lib/auth-actions';
|
||||||
|
import { useAuthStore } from '@/lib/stores/auth-store';
|
||||||
|
|
||||||
|
const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Change password page (D-06 force-change + voluntary change).
|
||||||
|
* Inside (portal) route group -- has sidebar/header.
|
||||||
|
* Shows a notice when user was forced here by mustChangePassword flag.
|
||||||
|
* On success, redirects to dashboard.
|
||||||
|
*/
|
||||||
|
export default function ChangePasswordPage() {
|
||||||
|
const t = useTranslations('auth');
|
||||||
|
const router = useRouter();
|
||||||
|
const { user, setUser } = useAuthStore();
|
||||||
|
const [isPending, startTransition] = useTransition();
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [passwordMismatch, setPasswordMismatch] = useState(false);
|
||||||
|
const [isForced, setIsForced] = useState(false);
|
||||||
|
|
||||||
|
// Detect if this is a forced password change
|
||||||
|
useEffect(() => {
|
||||||
|
async function checkForceChange() {
|
||||||
|
const currentUser = await fetchCurrentUser();
|
||||||
|
if (currentUser?.mustChangePassword) {
|
||||||
|
setIsForced(true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
checkForceChange();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
|
||||||
|
e.preventDefault();
|
||||||
|
setError(null);
|
||||||
|
setPasswordMismatch(false);
|
||||||
|
|
||||||
|
const formData = new FormData(e.currentTarget);
|
||||||
|
const currentPassword = formData.get('currentPassword') as string;
|
||||||
|
const newPassword = formData.get('newPassword') as string;
|
||||||
|
const confirmPassword = formData.get('confirmPassword') as string;
|
||||||
|
|
||||||
|
if (newPassword !== confirmPassword) {
|
||||||
|
setPasswordMismatch(true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
startTransition(async () => {
|
||||||
|
try {
|
||||||
|
// Get the session cookie to send with the request
|
||||||
|
const response = await fetch(`${API_URL}/auth/change-password`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ currentPassword, newPassword }),
|
||||||
|
credentials: 'include',
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
const data = await response.json().catch(() => null);
|
||||||
|
if (data?.message === 'Current password is incorrect') {
|
||||||
|
setError('wrongCurrentPassword');
|
||||||
|
} else {
|
||||||
|
setError('networkError');
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update auth store to clear mustChangePassword
|
||||||
|
if (user) {
|
||||||
|
setUser({ ...user });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Redirect to dashboard
|
||||||
|
router.push('/');
|
||||||
|
router.refresh();
|
||||||
|
} catch {
|
||||||
|
setError('networkError');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="mx-auto max-w-md py-8 px-4">
|
||||||
|
<h1 className="text-2xl font-bold text-foreground mb-6">
|
||||||
|
{t('changePassword.title')}
|
||||||
|
</h1>
|
||||||
|
|
||||||
|
{/* Force-change notice (D-06) */}
|
||||||
|
{isForced && (
|
||||||
|
<div className="rounded-md bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 px-4 py-3 text-sm text-yellow-800 dark:text-yellow-200 mb-6">
|
||||||
|
{t('changePassword.forceChangeNotice')}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Error message */}
|
||||||
|
{error && (
|
||||||
|
<div className="rounded-md bg-destructive/10 border border-destructive/20 px-4 py-3 text-sm text-destructive mb-6">
|
||||||
|
{t(`changePassword.${error}`)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Password mismatch */}
|
||||||
|
{passwordMismatch && (
|
||||||
|
<div className="rounded-md bg-destructive/10 border border-destructive/20 px-4 py-3 text-sm text-destructive mb-6">
|
||||||
|
{t('changePassword.passwordMismatch')}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<form onSubmit={handleSubmit} className="space-y-5">
|
||||||
|
{/* Current password */}
|
||||||
|
<div className="space-y-2">
|
||||||
|
<label
|
||||||
|
htmlFor="currentPassword"
|
||||||
|
className="text-sm font-medium text-foreground"
|
||||||
|
>
|
||||||
|
{t('changePassword.currentPassword')}
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
id="currentPassword"
|
||||||
|
name="currentPassword"
|
||||||
|
type="password"
|
||||||
|
required
|
||||||
|
autoComplete="current-password"
|
||||||
|
autoFocus
|
||||||
|
className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
|
||||||
|
placeholder={t('changePassword.currentPassword')}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* New password */}
|
||||||
|
<div className="space-y-2">
|
||||||
|
<label
|
||||||
|
htmlFor="newPassword"
|
||||||
|
className="text-sm font-medium text-foreground"
|
||||||
|
>
|
||||||
|
{t('changePassword.newPassword')}
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
id="newPassword"
|
||||||
|
name="newPassword"
|
||||||
|
type="password"
|
||||||
|
required
|
||||||
|
minLength={8}
|
||||||
|
autoComplete="new-password"
|
||||||
|
className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
|
||||||
|
placeholder={t('changePassword.newPassword')}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Confirm new password */}
|
||||||
|
<div className="space-y-2">
|
||||||
|
<label
|
||||||
|
htmlFor="confirmPassword"
|
||||||
|
className="text-sm font-medium text-foreground"
|
||||||
|
>
|
||||||
|
{t('changePassword.confirmPassword')}
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
id="confirmPassword"
|
||||||
|
name="confirmPassword"
|
||||||
|
type="password"
|
||||||
|
required
|
||||||
|
minLength={8}
|
||||||
|
autoComplete="new-password"
|
||||||
|
className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
|
||||||
|
placeholder={t('changePassword.confirmPassword')}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={isPending}
|
||||||
|
className="flex w-full items-center justify-center rounded-md bg-primary px-4 py-2.5 text-sm font-medium text-primary-foreground hover:opacity-90 transition-opacity disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{isPending ? (
|
||||||
|
<svg
|
||||||
|
className="animate-spin h-4 w-4"
|
||||||
|
xmlns="http://www.w3.org/2000/svg"
|
||||||
|
fill="none"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
>
|
||||||
|
<circle
|
||||||
|
className="opacity-25"
|
||||||
|
cx="12"
|
||||||
|
cy="12"
|
||||||
|
r="10"
|
||||||
|
stroke="currentColor"
|
||||||
|
strokeWidth="4"
|
||||||
|
/>
|
||||||
|
<path
|
||||||
|
className="opacity-75"
|
||||||
|
fill="currentColor"
|
||||||
|
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"
|
||||||
|
/>
|
||||||
|
</svg>
|
||||||
|
) : (
|
||||||
|
t('changePassword.submit')
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -23,12 +23,42 @@
|
|||||||
"password": "Passwort",
|
"password": "Passwort",
|
||||||
"rememberMe": "Angemeldet bleiben",
|
"rememberMe": "Angemeldet bleiben",
|
||||||
"submit": "Anmelden",
|
"submit": "Anmelden",
|
||||||
|
"forgotPassword": "Passwort vergessen?",
|
||||||
"error": {
|
"error": {
|
||||||
"invalidCredentials": "Benutzername oder Passwort ungueltig",
|
"invalidCredentials": "Benutzername oder Passwort ungueltig",
|
||||||
"networkError": "Verbindungsfehler. Bitte versuchen Sie es erneut."
|
"networkError": "Verbindungsfehler. Bitte versuchen Sie es erneut."
|
||||||
},
|
},
|
||||||
"branding": {
|
"branding": {
|
||||||
"tagline": "Modulare Workflow-Plattform fuer Ihr Unternehmen"
|
"tagline": "Modulare Workflow-Plattform fuer Ihr Unternehmen"
|
||||||
|
},
|
||||||
|
"resetPassword": {
|
||||||
|
"title": "Passwort zuruecksetzen",
|
||||||
|
"email": "E-Mail-Adresse",
|
||||||
|
"submit": "Link senden",
|
||||||
|
"success": "Falls ein Konto mit dieser E-Mail existiert, wurde ein Link zum Zuruecksetzen gesendet.",
|
||||||
|
"backToLogin": "Zurueck zur Anmeldung",
|
||||||
|
"newPasswordTitle": "Neues Passwort festlegen",
|
||||||
|
"newPassword": "Neues Passwort",
|
||||||
|
"confirmPassword": "Passwort bestaetigen",
|
||||||
|
"submitReset": "Passwort zuruecksetzen",
|
||||||
|
"resetSuccess": "Ihr Passwort wurde erfolgreich zurueckgesetzt.",
|
||||||
|
"redirecting": "Sie werden in wenigen Sekunden zur Anmeldung weitergeleitet...",
|
||||||
|
"tokenExpired": "Der Link zum Zuruecksetzen ist abgelaufen. Bitte fordern Sie einen neuen an.",
|
||||||
|
"tokenUsed": "Dieser Link wurde bereits verwendet. Bitte fordern Sie einen neuen an.",
|
||||||
|
"tokenInvalid": "Der Link zum Zuruecksetzen ist ungueltig.",
|
||||||
|
"passwordMismatch": "Die Passwoerter stimmen nicht ueberein."
|
||||||
|
},
|
||||||
|
"changePassword": {
|
||||||
|
"title": "Passwort aendern",
|
||||||
|
"currentPassword": "Aktuelles Passwort",
|
||||||
|
"newPassword": "Neues Passwort",
|
||||||
|
"confirmPassword": "Neues Passwort bestaetigen",
|
||||||
|
"submit": "Passwort aendern",
|
||||||
|
"success": "Ihr Passwort wurde erfolgreich geaendert.",
|
||||||
|
"forceChangeNotice": "Aus Sicherheitsgruenden muessen Sie Ihr Passwort aendern, bevor Sie fortfahren koennen.",
|
||||||
|
"wrongCurrentPassword": "Das aktuelle Passwort ist falsch.",
|
||||||
|
"networkError": "Verbindungsfehler. Bitte versuchen Sie es erneut.",
|
||||||
|
"passwordMismatch": "Die Passwoerter stimmen nicht ueberein."
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"header": {
|
"header": {
|
||||||
|
|||||||
@@ -23,12 +23,42 @@
|
|||||||
"password": "Password",
|
"password": "Password",
|
||||||
"rememberMe": "Remember me",
|
"rememberMe": "Remember me",
|
||||||
"submit": "Sign In",
|
"submit": "Sign In",
|
||||||
|
"forgotPassword": "Forgot password?",
|
||||||
"error": {
|
"error": {
|
||||||
"invalidCredentials": "Invalid username or password",
|
"invalidCredentials": "Invalid username or password",
|
||||||
"networkError": "Connection error. Please try again."
|
"networkError": "Connection error. Please try again."
|
||||||
},
|
},
|
||||||
"branding": {
|
"branding": {
|
||||||
"tagline": "Modular workflow platform for your organization"
|
"tagline": "Modular workflow platform for your organization"
|
||||||
|
},
|
||||||
|
"resetPassword": {
|
||||||
|
"title": "Reset Password",
|
||||||
|
"email": "Email address",
|
||||||
|
"submit": "Send Reset Link",
|
||||||
|
"success": "If an account with this email exists, a reset link has been sent.",
|
||||||
|
"backToLogin": "Back to Sign In",
|
||||||
|
"newPasswordTitle": "Set New Password",
|
||||||
|
"newPassword": "New Password",
|
||||||
|
"confirmPassword": "Confirm Password",
|
||||||
|
"submitReset": "Reset Password",
|
||||||
|
"resetSuccess": "Your password has been reset successfully.",
|
||||||
|
"redirecting": "You will be redirected to the sign in page in a few seconds...",
|
||||||
|
"tokenExpired": "This reset link has expired. Please request a new one.",
|
||||||
|
"tokenUsed": "This reset link has already been used. Please request a new one.",
|
||||||
|
"tokenInvalid": "This reset link is invalid.",
|
||||||
|
"passwordMismatch": "Passwords do not match."
|
||||||
|
},
|
||||||
|
"changePassword": {
|
||||||
|
"title": "Change Password",
|
||||||
|
"currentPassword": "Current Password",
|
||||||
|
"newPassword": "New Password",
|
||||||
|
"confirmPassword": "Confirm New Password",
|
||||||
|
"submit": "Change Password",
|
||||||
|
"success": "Your password has been changed successfully.",
|
||||||
|
"forceChangeNotice": "For security reasons, you must change your password before continuing.",
|
||||||
|
"wrongCurrentPassword": "The current password is incorrect.",
|
||||||
|
"networkError": "Connection error. Please try again.",
|
||||||
|
"passwordMismatch": "Passwords do not match."
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"header": {
|
"header": {
|
||||||
|
|||||||
@@ -14,4 +14,19 @@ services:
|
|||||||
TESSERA_ADMIN_EMAIL: ${TESSERA_ADMIN_EMAIL:-admin@tessera.local}
|
TESSERA_ADMIN_EMAIL: ${TESSERA_ADMIN_EMAIL:-admin@tessera.local}
|
||||||
TESSERA_ADMIN_PASSWORD: ${TESSERA_ADMIN_PASSWORD:-admin123}
|
TESSERA_ADMIN_PASSWORD: ${TESSERA_ADMIN_PASSWORD:-admin123}
|
||||||
TESSERA_FORCE_CHANGE: ${TESSERA_FORCE_CHANGE:-false}
|
TESSERA_FORCE_CHANGE: ${TESSERA_FORCE_CHANGE:-false}
|
||||||
|
TESSERA_SMTP_HOST: mailhog
|
||||||
|
TESSERA_SMTP_PORT: 1025
|
||||||
|
TESSERA_SMTP_SECURE: "false"
|
||||||
|
TESSERA_SMTP_USER: ""
|
||||||
|
TESSERA_SMTP_PASSWORD: ""
|
||||||
|
TESSERA_SMTP_FROM: "Tessera <tessera@tessera.local>"
|
||||||
|
TESSERA_APP_URL: http://localhost:3000
|
||||||
command: ["pnpm", "--filter", "@tessera/api", "start:dev"]
|
command: ["pnpm", "--filter", "@tessera/api", "start:dev"]
|
||||||
|
|
||||||
|
mailhog:
|
||||||
|
image: mailhog/mailhog
|
||||||
|
ports:
|
||||||
|
- "1025:1025"
|
||||||
|
- "8025:8025"
|
||||||
|
networks:
|
||||||
|
- backend-net
|
||||||
|
|||||||
@@ -34,6 +34,13 @@ services:
|
|||||||
TESSERA_ADMIN_EMAIL: ${TESSERA_ADMIN_EMAIL:-admin@tessera.local}
|
TESSERA_ADMIN_EMAIL: ${TESSERA_ADMIN_EMAIL:-admin@tessera.local}
|
||||||
TESSERA_ADMIN_PASSWORD: ${TESSERA_ADMIN_PASSWORD:-admin123}
|
TESSERA_ADMIN_PASSWORD: ${TESSERA_ADMIN_PASSWORD:-admin123}
|
||||||
TESSERA_FORCE_CHANGE: ${TESSERA_FORCE_CHANGE:-false}
|
TESSERA_FORCE_CHANGE: ${TESSERA_FORCE_CHANGE:-false}
|
||||||
|
TESSERA_SMTP_HOST: ${TESSERA_SMTP_HOST:-mailhog}
|
||||||
|
TESSERA_SMTP_PORT: ${TESSERA_SMTP_PORT:-1025}
|
||||||
|
TESSERA_SMTP_SECURE: ${TESSERA_SMTP_SECURE:-false}
|
||||||
|
TESSERA_SMTP_USER: ${TESSERA_SMTP_USER:-}
|
||||||
|
TESSERA_SMTP_PASSWORD: ${TESSERA_SMTP_PASSWORD:-}
|
||||||
|
TESSERA_SMTP_FROM: ${TESSERA_SMTP_FROM:-Tessera <tessera@tessera.local>}
|
||||||
|
TESSERA_APP_URL: ${TESSERA_APP_URL:-http://localhost:3000}
|
||||||
healthcheck:
|
healthcheck:
|
||||||
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:3001/health"]
|
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:3001/health"]
|
||||||
interval: 10s
|
interval: 10s
|
||||||
|
|||||||
Generated
+3017
-10
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user