import { ConflictException, ForbiddenException, NotFoundException, } from '@nestjs/common'; import { UsersService } from './users.service'; import { PrismaService } from '../prisma/prisma.service'; import { AuditLogService } from '../audit/audit-log.service'; import { PermissionResolverService } from '../auth/permissions/permission-resolver.service'; describe('UsersService', () => { let usersService: UsersService; let prisma: { user: { findMany: jest.Mock; findUnique: jest.Mock; create: jest.Mock; update: jest.Mock; count: jest.Mock; }; role: { findUnique: jest.Mock; }; refreshToken: { updateMany: jest.Mock }; }; let auditLog: { record: jest.Mock }; let permissionResolver: { invalidateUser: jest.Mock; invalidateAll: jest.Mock; hasAny: jest.Mock; }; const staffRole = { id: 'role-staff', key: 'STAFF', name: 'Mitarbeiter', status: 'ACTIVE', isSystem: false, }; const adminRole = { id: 'role-admin', key: 'ADMIN', name: 'Administrator', status: 'ACTIVE', isSystem: true, }; const existingUser = { id: 'user-1', email: 'existing@example.com', passwordHash: 'hashed', name: 'Existing User', roleId: staffRole.id, role: staffRole, isActive: true, createdAt: new Date(), deactivatedAt: null, }; const adminUser = { ...existingUser, id: 'user-admin', email: 'admin@example.com', roleId: adminRole.id, role: adminRole, }; beforeEach(() => { prisma = { user: { findMany: jest.fn(), findUnique: jest.fn(), create: jest.fn(), update: jest.fn(), count: jest.fn(), }, role: { findUnique: jest.fn().mockResolvedValue(staffRole), }, refreshToken: { updateMany: jest.fn() }, }; auditLog = { record: jest.fn().mockResolvedValue(undefined) }; permissionResolver = { invalidateUser: jest.fn(), invalidateAll: jest.fn(), hasAny: jest.fn().mockResolvedValue(true), }; usersService = new UsersService( prisma as unknown as PrismaService, auditLog as unknown as AuditLogService, permissionResolver as unknown as PermissionResolverService, ); }); it('findAll returns summaries without the password hash', async () => { prisma.user.findMany.mockResolvedValue([existingUser]); const result = await usersService.findAll(); expect(result).toEqual([ { id: existingUser.id, email: existingUser.email, name: existingUser.name, roleId: staffRole.id, roleKey: staffRole.key, roleName: staffRole.name, isActive: existingUser.isActive, createdAt: existingUser.createdAt, deactivatedAt: existingUser.deactivatedAt, }, ]); expect(result[0]).not.toHaveProperty('passwordHash'); }); it('findById throws NotFoundException when the user is missing', async () => { prisma.user.findUnique.mockResolvedValue(null); await expect(usersService.findById('missing')).rejects.toBeInstanceOf( NotFoundException, ); }); it('create throws ConflictException when the email is already in use', async () => { prisma.user.findUnique.mockResolvedValue(existingUser); await expect( usersService.create({ email: existingUser.email, password: 'password123', name: 'New', roleId: staffRole.id, }), ).rejects.toBeInstanceOf(ConflictException); }); it('create throws NotFoundException when the role does not exist', async () => { prisma.user.findUnique.mockResolvedValue(null); prisma.role.findUnique.mockResolvedValue(null); await expect( usersService.create({ email: 'new@example.com', password: 'password123', name: 'New User', roleId: 'missing-role', }), ).rejects.toBeInstanceOf(NotFoundException); }); it('create throws ConflictException when the role is not active', async () => { prisma.user.findUnique.mockResolvedValue(null); prisma.role.findUnique.mockResolvedValue({ ...staffRole, status: 'INACTIVE', }); await expect( usersService.create({ email: 'new@example.com', password: 'password123', name: 'New User', roleId: staffRole.id, }), ).rejects.toBeInstanceOf(ConflictException); }); it('create hashes the password, persists the user, and records an audit entry', async () => { prisma.user.findUnique.mockResolvedValue(null); prisma.user.create.mockResolvedValue({ ...existingUser, id: 'user-2', email: 'new@example.com', }); const result = await usersService.create({ email: 'new@example.com', password: 'password123', name: 'New User', roleId: staffRole.id, }); expect(result.id).toBe('user-2'); const [[createArg]] = prisma.user.create.mock.calls as [ [{ data: { email: string; passwordHash: string } }], ]; expect(createArg.data.email).toBe('new@example.com'); expect(createArg.data.passwordHash).not.toBe('password123'); expect(auditLog.record).toHaveBeenCalledWith( expect.objectContaining({ entityType: 'User', action: 'CREATE' }), ); }); it('deactivate sets isActive to false, invalidates the permission cache, and records an audit entry', async () => { prisma.user.findUnique.mockResolvedValue(existingUser); prisma.user.update.mockResolvedValue({ ...existingUser, isActive: false, deactivatedAt: new Date(), }); const result = await usersService.deactivate(existingUser.id); expect(result.isActive).toBe(false); expect(result.deactivatedAt).not.toBeNull(); expect(permissionResolver.invalidateUser).toHaveBeenCalledWith( existingUser.id, ); expect(auditLog.record).toHaveBeenCalledWith( expect.objectContaining({ entityType: 'User', action: 'DEACTIVATE' }), ); }); it('deactivate throws ConflictException when deactivating the last active user of a system role', async () => { prisma.user.findUnique.mockResolvedValue(adminUser); prisma.user.count.mockResolvedValue(1); await expect(usersService.deactivate(adminUser.id)).rejects.toBeInstanceOf( ConflictException, ); expect(prisma.user.update).not.toHaveBeenCalled(); expect(permissionResolver.invalidateUser).not.toHaveBeenCalled(); }); it('deactivate succeeds for a system-role user when another active user shares that role', async () => { prisma.user.findUnique.mockResolvedValue(adminUser); prisma.user.count.mockResolvedValue(2); prisma.user.update.mockResolvedValue({ ...adminUser, isActive: false, deactivatedAt: new Date(), }); const result = await usersService.deactivate(adminUser.id); expect(result.isActive).toBe(false); }); it('activate throws ConflictException when already active', async () => { prisma.user.findUnique.mockResolvedValue(existingUser); await expect(usersService.activate(existingUser.id)).rejects.toBeInstanceOf( ConflictException, ); }); it('activate sets isActive to true, invalidates the permission cache, and clears deactivatedAt', async () => { prisma.user.findUnique.mockResolvedValue({ ...existingUser, isActive: false, deactivatedAt: new Date(), }); prisma.user.update.mockResolvedValue({ ...existingUser, isActive: true, deactivatedAt: null, }); const result = await usersService.activate(existingUser.id); expect(result.isActive).toBe(true); expect(result.deactivatedAt).toBeNull(); expect(permissionResolver.invalidateUser).toHaveBeenCalledWith( existingUser.id, ); expect(auditLog.record).toHaveBeenCalledWith( expect.objectContaining({ entityType: 'User', action: 'UPDATE' }), ); }); it('update invalidates the permission cache when the role changes', async () => { prisma.user.findUnique.mockResolvedValue(existingUser); prisma.user.update.mockResolvedValue({ ...existingUser, roleId: adminRole.id, role: adminRole, }); await usersService.update(existingUser.id, { roleId: adminRole.id }); expect(permissionResolver.invalidateUser).toHaveBeenCalledWith( existingUser.id, ); }); it('update does not touch the permission cache when the role is unchanged', async () => { prisma.user.findUnique.mockResolvedValue(existingUser); prisma.user.update.mockResolvedValue({ ...existingUser, name: 'Renamed' }); await usersService.update(existingUser.id, { name: 'Renamed' }); expect(permissionResolver.invalidateUser).not.toHaveBeenCalled(); }); it('resetMfa clears mfaEnabled/mfaSecret and records a MFA_DISABLED audit entry', async () => { prisma.user.findUnique.mockResolvedValue(existingUser); prisma.user.update.mockResolvedValue({ ...existingUser, mfaEnabled: false, mfaSecret: null, }); await usersService.resetMfa(existingUser.id, adminUser.id); expect(prisma.user.update).toHaveBeenCalledWith( expect.objectContaining({ where: { id: existingUser.id }, data: { mfaEnabled: false, mfaSecret: null }, }), ); expect(auditLog.record).toHaveBeenCalledWith( expect.objectContaining({ entityType: 'User', entityId: existingUser.id, action: 'MFA_DISABLED', userId: adminUser.id, }), ); }); it('resetMfa throws NotFoundException when the user does not exist', async () => { prisma.user.findUnique.mockResolvedValue(null); await expect( usersService.resetMfa('missing', adminUser.id), ).rejects.toBeInstanceOf(NotFoundException); expect(prisma.user.update).not.toHaveBeenCalled(); }); it('update throws ConflictException when reassigning the last active user away from a system role', async () => { prisma.user.findUnique.mockResolvedValue(adminUser); prisma.role.findUnique.mockResolvedValue(staffRole); prisma.user.count.mockResolvedValue(1); await expect( usersService.update(adminUser.id, { roleId: staffRole.id }), ).rejects.toBeInstanceOf(ConflictException); expect(prisma.user.update).not.toHaveBeenCalled(); }); it('update throws ForbiddenException when the caller tries to change their own role', async () => { prisma.user.findUnique.mockResolvedValue(adminUser); await expect( usersService.update(adminUser.id, { roleId: staffRole.id }, adminUser.id), ).rejects.toBeInstanceOf(ForbiddenException); expect(prisma.user.update).not.toHaveBeenCalled(); }); it('update throws ForbiddenException when the caller lacks users:assign-role', async () => { prisma.user.findUnique.mockResolvedValue(existingUser); prisma.role.findUnique.mockResolvedValue(adminRole); permissionResolver.hasAny.mockResolvedValue(false); await expect( usersService.update( existingUser.id, { roleId: adminRole.id }, adminUser.id, ), ).rejects.toBeInstanceOf(ForbiddenException); expect(prisma.user.update).not.toHaveBeenCalled(); }); it('create throws ForbiddenException when the caller lacks users:assign-role', async () => { prisma.user.findUnique.mockResolvedValue(null); permissionResolver.hasAny.mockResolvedValue(false); await expect( usersService.create( { email: 'new@example.com', password: 'password123', name: 'New User', roleId: staffRole.id, }, adminUser.id, ), ).rejects.toBeInstanceOf(ForbiddenException); expect(prisma.user.create).not.toHaveBeenCalled(); }); it('resetMfa throws ForbiddenException when targeting your own account', async () => { await expect( usersService.resetMfa(adminUser.id, adminUser.id), ).rejects.toBeInstanceOf(ForbiddenException); expect(prisma.user.update).not.toHaveBeenCalled(); }); describe('resetPassword', () => { it('revokes every refresh token and clears the permission cache', async () => { prisma.user.findUnique.mockResolvedValue(existingUser); prisma.user.update.mockResolvedValue(existingUser); await usersService.resetPassword( 'user-1', { password: 'neuesPasswort1' }, 'user-admin', ); expect(prisma.refreshToken.updateMany).toHaveBeenCalledWith({ where: { userId: 'user-1', revokedAt: null }, data: { revokedAt: expect.any(Date) as Date }, }); expect(permissionResolver.invalidateUser).toHaveBeenCalledWith('user-1'); }); it('stores a hash, never the password itself', async () => { prisma.user.findUnique.mockResolvedValue(existingUser); prisma.user.update.mockResolvedValue(existingUser); await usersService.resetPassword( 'user-1', { password: 'neuesPasswort1' }, 'user-admin', ); const [[updateArgs]] = prisma.user.update.mock.calls as [ [{ data: { passwordHash: string } }], ]; expect(updateArgs.data.passwordHash).not.toBe('neuesPasswort1'); expect(updateArgs.data.passwordHash).toMatch(/^\$2[aby]\$/); }); it('refuses to reset your own password, which belongs to /profile/password', async () => { prisma.user.findUnique.mockResolvedValue(existingUser); await expect( usersService.resetPassword( 'user-1', { password: 'neuesPasswort1' }, 'user-1', ), ).rejects.toBeInstanceOf(ForbiddenException); expect(prisma.user.update).not.toHaveBeenCalled(); }); }); });