Benutzer koennen jetzt selbst Zwei-Faktor-Authentifizierung einrichten
und ihr Profil verwalten (Name, E-Mail, Passwort, Profilbild).
Backend:
- Neues MfaModule (src/auth/mfa/): AES-256-GCM-verschluesselte
TOTP-Secrets (otplib), QR-Code-Erzeugung, kurzlebige Setup-/
Challenge-JWTs fuer den 2-Schritt-Login-Flow
- Neues ProfileModule (src/profile/): PATCH /profile,
POST /profile/password, POST/DELETE/GET /profile/avatar,
POST /profile/mfa/enroll(/confirm), POST /profile/mfa/disable -
alle self-scoped ueber actor.id, ohne @RequirePermission (siehe
ALLOWLIST in authorization-coverage.e2e-spec.ts)
- AuthService.login() zweistufig: bei aktivem MFA erst
{ mfaRequired, mfaToken } statt Tokens, neuer Endpunkt
POST /auth/mfa/verify schliesst den Flow ab
- Admin-Recovery: POST /users/:id/mfa/reset (users:update) fuer
verlorene MFA-Geraete, da es keinen E-Mail-Reset-Flow gibt
Frontend:
- Login-Seite mit zweitem Schritt fuer den TOTP-Code
- Neue Profilseite (/profile, ausserhalb des admin-only
Settings-Bereichs): Profilbild, Name/E-Mail, Passwort, MFA-Ein-/
Ausrichtung mit QR-Code-Dialog
- Header zeigt jetzt Avatar mit Dropdown (Profil/Abmelden) statt
nur E-Mail-Text
- Admin-Users-Tabelle zeigt MFA-Status + Reset-Button
Haertung nach Security-Review (Backend/Frontend-Diff, kein CRITICAL,
mehrere MEDIUM behoben):
- Access-Token wird bei Passwortwechsel sofort ungueltig
(User.passwordChangedAt + JWT-iat-Vergleich in
PermissionResolverService.isTokenValid, vorher isUserActive) statt
erst nach bis zu 15 Minuten
- E-Mail-Aenderung verlangt jetzt aktuelles Passwort
- POST /profile/password und /profile/mfa/disable haben jetzt das
gleiche strikte Throttling wie Login (SENSITIVE_ACTION_THROTTLE)
- Kein stiller leerer Verschluesselungs-Key-Fallback mehr (wirft
jetzt explizit)
Bewusst zurueckgestellt (dokumentiert, kein aktiver Exploit-Pfad):
dedizierter Verschluesselungs-Key fuer MFA-Secrets statt
JWT_ACCESS_SECRET-Ableitung, dedizierte users:mfa-reset-Permission
statt users:update, separate JWT-Secrets pro Token-Zweck.
Verifiziert: tsc/eslint clean, 297/297 Backend- + 31/31
Frontend-Unit-Tests, Build clean auf beiden Projekten. e2e weiterhin
durch bekanntes WSL2/Postgres-Problem blockiert. Unabhaengiges
Security- und Code-Quality-Review durchgefuehrt (0 CRITICAL, 0 HIGH).
244 lines
7.0 KiB
TypeScript
244 lines
7.0 KiB
TypeScript
import {
|
|
ConflictException,
|
|
Injectable,
|
|
NotFoundException,
|
|
} from '@nestjs/common';
|
|
import * as bcrypt from 'bcryptjs';
|
|
import { PrismaService } from '../prisma/prisma.service';
|
|
import { AuditLogService } from '../audit/audit-log.service';
|
|
import { PermissionResolverService } from '../auth/permissions/permission-resolver.service';
|
|
import { Prisma } from '../../generated/prisma';
|
|
import { CreateUserDto } from './dto/create-user.dto';
|
|
import { UpdateUserDto } from './dto/update-user.dto';
|
|
|
|
const BCRYPT_SALT_ROUNDS = 12;
|
|
|
|
const USER_WITH_ROLE = {
|
|
include: { role: true },
|
|
} satisfies { include: Prisma.UserInclude };
|
|
|
|
type UserWithRole = Prisma.UserGetPayload<typeof USER_WITH_ROLE>;
|
|
|
|
export interface UserSummary {
|
|
id: string;
|
|
email: string;
|
|
name: string;
|
|
roleId: string;
|
|
roleKey: string;
|
|
roleName: string;
|
|
isActive: boolean;
|
|
createdAt: Date;
|
|
deactivatedAt: Date | null;
|
|
mfaEnabled: boolean;
|
|
}
|
|
|
|
@Injectable()
|
|
export class UsersService {
|
|
constructor(
|
|
private readonly prisma: PrismaService,
|
|
private readonly auditLog: AuditLogService,
|
|
private readonly permissionResolver: PermissionResolverService,
|
|
) {}
|
|
|
|
private toSummary(user: UserWithRole): UserSummary {
|
|
return {
|
|
id: user.id,
|
|
email: user.email,
|
|
name: user.name,
|
|
roleId: user.roleId,
|
|
roleKey: user.role.key,
|
|
roleName: user.role.name,
|
|
isActive: user.isActive,
|
|
createdAt: user.createdAt,
|
|
deactivatedAt: user.deactivatedAt,
|
|
mfaEnabled: user.mfaEnabled,
|
|
};
|
|
}
|
|
|
|
private async assertActiveRole(roleId: string): Promise<void> {
|
|
const role = await this.prisma.role.findUnique({ where: { id: roleId } });
|
|
if (!role) {
|
|
throw new NotFoundException('Role not found');
|
|
}
|
|
if (role.status !== 'ACTIVE') {
|
|
throw new ConflictException('Role is not active');
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Blocks removing (by deactivation or role reassignment) the last active
|
|
* user still holding a system role (ADMIN). Without this, an operator
|
|
* could lock the app out of user/role management entirely, with no
|
|
* self-service recovery: prisma/seed.ts skips seeding once a user with
|
|
* its configured email already exists, so it cannot restore access to a
|
|
* merely demoted/deactivated account.
|
|
*/
|
|
private async assertNotLastSystemRoleUser(userId: string): Promise<void> {
|
|
const user = await this.prisma.user.findUnique({
|
|
where: { id: userId },
|
|
select: { roleId: true, role: { select: { isSystem: true } } },
|
|
});
|
|
if (!user || !user.role.isSystem) {
|
|
return;
|
|
}
|
|
const activeCount = await this.prisma.user.count({
|
|
where: { roleId: user.roleId, isActive: true },
|
|
});
|
|
if (activeCount <= 1) {
|
|
throw new ConflictException(
|
|
'Cannot remove the last active user holding a system role',
|
|
);
|
|
}
|
|
}
|
|
|
|
async findAll(): Promise<UserSummary[]> {
|
|
const users = await this.prisma.user.findMany({
|
|
...USER_WITH_ROLE,
|
|
orderBy: { createdAt: 'asc' },
|
|
});
|
|
return users.map((user) => this.toSummary(user));
|
|
}
|
|
|
|
async findById(id: string): Promise<UserWithRole> {
|
|
const user = await this.prisma.user.findUnique({
|
|
where: { id },
|
|
...USER_WITH_ROLE,
|
|
});
|
|
if (!user) {
|
|
throw new NotFoundException('User not found');
|
|
}
|
|
return user;
|
|
}
|
|
|
|
async findSummaryById(id: string): Promise<UserSummary> {
|
|
return this.toSummary(await this.findById(id));
|
|
}
|
|
|
|
async findByEmail(email: string): Promise<UserWithRole | null> {
|
|
return this.prisma.user.findUnique({ where: { email }, ...USER_WITH_ROLE });
|
|
}
|
|
|
|
async create(
|
|
dto: CreateUserDto,
|
|
actingUserId?: string,
|
|
): Promise<UserSummary> {
|
|
const existing = await this.findByEmail(dto.email);
|
|
if (existing) {
|
|
throw new ConflictException('Email already in use');
|
|
}
|
|
await this.assertActiveRole(dto.roleId);
|
|
const passwordHash = await bcrypt.hash(dto.password, BCRYPT_SALT_ROUNDS);
|
|
const user = await this.prisma.user.create({
|
|
data: {
|
|
email: dto.email,
|
|
passwordHash,
|
|
name: dto.name,
|
|
roleId: dto.roleId,
|
|
},
|
|
...USER_WITH_ROLE,
|
|
});
|
|
await this.auditLog.record({
|
|
entityType: 'User',
|
|
entityId: user.id,
|
|
action: 'CREATE',
|
|
userId: actingUserId,
|
|
afterData: this.toSummary(user),
|
|
});
|
|
return this.toSummary(user);
|
|
}
|
|
|
|
async update(
|
|
id: string,
|
|
dto: UpdateUserDto,
|
|
actingUserId?: string,
|
|
): Promise<UserSummary> {
|
|
const before = await this.findById(id);
|
|
const roleChanged = Boolean(dto.roleId) && dto.roleId !== before.roleId;
|
|
if (dto.roleId) {
|
|
await this.assertActiveRole(dto.roleId);
|
|
}
|
|
if (roleChanged) {
|
|
await this.assertNotLastSystemRoleUser(id);
|
|
}
|
|
const user = await this.prisma.user.update({
|
|
where: { id },
|
|
data: {
|
|
name: dto.name,
|
|
roleId: dto.roleId,
|
|
},
|
|
...USER_WITH_ROLE,
|
|
});
|
|
if (roleChanged) {
|
|
this.permissionResolver.invalidateUser(id);
|
|
}
|
|
await this.auditLog.record({
|
|
entityType: 'User',
|
|
entityId: id,
|
|
action: 'UPDATE',
|
|
userId: actingUserId,
|
|
beforeData: this.toSummary(before),
|
|
afterData: this.toSummary(user),
|
|
});
|
|
return this.toSummary(user);
|
|
}
|
|
|
|
async deactivate(id: string, actingUserId?: string): Promise<UserSummary> {
|
|
const before = await this.findById(id);
|
|
await this.assertNotLastSystemRoleUser(id);
|
|
const user = await this.prisma.user.update({
|
|
where: { id },
|
|
data: { isActive: false, deactivatedAt: new Date() },
|
|
...USER_WITH_ROLE,
|
|
});
|
|
this.permissionResolver.invalidateUser(id);
|
|
await this.auditLog.record({
|
|
entityType: 'User',
|
|
entityId: id,
|
|
action: 'DEACTIVATE',
|
|
userId: actingUserId,
|
|
beforeData: this.toSummary(before),
|
|
afterData: this.toSummary(user),
|
|
});
|
|
return this.toSummary(user);
|
|
}
|
|
|
|
/** Recovery path for a user who lost their MFA device (no email-reset flow exists in this project). */
|
|
async resetMfa(id: string, actingUserId?: string): Promise<UserSummary> {
|
|
await this.findById(id);
|
|
const user = await this.prisma.user.update({
|
|
where: { id },
|
|
data: { mfaEnabled: false, mfaSecret: null },
|
|
...USER_WITH_ROLE,
|
|
});
|
|
await this.auditLog.record({
|
|
entityType: 'User',
|
|
entityId: id,
|
|
action: 'MFA_DISABLED',
|
|
userId: actingUserId,
|
|
});
|
|
return this.toSummary(user);
|
|
}
|
|
|
|
async activate(id: string, actingUserId?: string): Promise<UserSummary> {
|
|
const before = await this.findById(id);
|
|
if (before.isActive) {
|
|
throw new ConflictException('User is already active');
|
|
}
|
|
const user = await this.prisma.user.update({
|
|
where: { id },
|
|
data: { isActive: true, deactivatedAt: null },
|
|
...USER_WITH_ROLE,
|
|
});
|
|
this.permissionResolver.invalidateUser(id);
|
|
await this.auditLog.record({
|
|
entityType: 'User',
|
|
entityId: id,
|
|
action: 'UPDATE',
|
|
userId: actingUserId,
|
|
beforeData: this.toSummary(before),
|
|
afterData: this.toSummary(user),
|
|
});
|
|
return this.toSummary(user);
|
|
}
|
|
}
|