Files
ApiCore/ApiCore-Backend/src/users/users.service.spec.ts
T
Nick SzaunigandClaude Opus 5 b0e05daa42 feat: open the last locked fields for editing, keeping their history intact
Four fields were still frozen because changing them would have bypassed the
record that makes the change traceable, and a user's login data could not be
corrected at all. Locking a field is the wrong trade: a wrong value stays in
the system forever. The fix is to let the edit write the same history entry the
dedicated endpoint writes.

- A colony's apiary is editable through PATCH and writes the same
  ColonyApiaryHistory entry POST /colonies/:id/move writes, so the location
  history never skips a stand the colony was recorded on.
- A honey batch's storage container is editable through PATCH and writes the
  same HoneyBatchRelocation entry POST /honey-batches/:id/relocate writes.
- A stock item's quantity is editable and books the difference as an ADJUSTMENT
  movement, so the stored level stays the sum of its movements.
- A role's key is editable (system roles were already rejected outright by
  RolesService.update, which keeps the seed's ADMIN lookup intact).
- A user's e-mail - the login identity - is editable. A typo there previously
  locked the account out for good.
- New POST /users/:id/reset-password lets an administrator set someone else's
  password: there is no self-service reset flow, so a forgotten password was
  the one thing no edit could repair. It revokes every refresh token and clears
  the permission cache exactly as a self-service change does, refuses to act on
  your own account (that goes through /profile/password, which proves ownership
  by asking for the current one), and never writes the password to the log.

Frontend:
- Users had no edit UI at all, although PATCH /users/:id existed. New
  EditUserDialog covers name, e-mail, role and an optional new password.
- Colony, honey batch and stock item forms gained the newly editable fields,
  each with a note saying the correction is recorded as a move, a relocation
  or a stock adjustment.
- The role dialog gained the key field.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-19 08:13:00 +02:00

434 lines
13 KiB
TypeScript

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: '[email protected]',
passwordHash: 'hashed',
name: 'Existing User',
roleId: staffRole.id,
role: staffRole,
isActive: true,
createdAt: new Date(),
deactivatedAt: null,
};
const adminUser = {
...existingUser,
id: 'user-admin',
email: '[email protected]',
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: '[email protected]',
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: '[email protected]',
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: '[email protected]',
});
const result = await usersService.create({
email: '[email protected]',
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('[email protected]');
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: '[email protected]',
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();
});
});
});