refactor(shared): extract hasWriteAll(locals) permission helper

The locals.user.groups.some(...WRITE_ALL) derivation was copy-pasted across
the persons directory, persons review and the two document loaders touched by
this PR. Extract a single tested hasWriteAll(locals) helper in
$lib/shared/server and reuse it, removing the ad-hoc casts.

Refs #667

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
Marcel
2026-05-27 14:14:00 +02:00
parent 1a0be4130e
commit 3a758393bf
6 changed files with 52 additions and 18 deletions

View File

@@ -0,0 +1,30 @@
import { describe, expect, it } from 'vitest';
import { hasWriteAll } from './permissions';
type Locals = { user?: { groups?: { permissions: string[] }[] } };
const localsWith = (permissions: string[][]): Locals => ({
user: { groups: permissions.map((p) => ({ permissions: p })) }
});
describe('hasWriteAll', () => {
it('returns true when a group grants WRITE_ALL', () => {
expect(hasWriteAll(localsWith([['READ_ALL', 'WRITE_ALL']]))).toBe(true);
});
it('returns true when WRITE_ALL is in any of several groups', () => {
expect(hasWriteAll(localsWith([['READ_ALL'], ['WRITE_ALL']]))).toBe(true);
});
it('returns false when no group grants WRITE_ALL', () => {
expect(hasWriteAll(localsWith([['READ_ALL'], ['ANNOTATE_ALL']]))).toBe(false);
});
it('returns false for an anonymous user (no locals.user)', () => {
expect(hasWriteAll({})).toBe(false);
});
it('returns false when the user has no groups', () => {
expect(hasWriteAll({ user: {} })).toBe(false);
});
});

View File

@@ -0,0 +1,14 @@
/**
* Server-side permission predicates derived from the authenticated user in `locals`.
*
* The user shape is intentionally narrowed to the only field these checks read
* (`groups[].permissions`) so the helper works against `App.Locals` without importing it.
*/
type PermissionLocals = {
user?: { groups?: { permissions: string[] }[] } | null;
};
/** True when any of the user's groups grants WRITE_ALL. False for anonymous users. */
export function hasWriteAll(locals: PermissionLocals): boolean {
return locals.user?.groups?.some((group) => group.permissions.includes('WRITE_ALL')) ?? false;
}