feat: add editorial album permissions
This commit is contained in:
1 parent
0fe2c80cda
commit
4af86f6eb9
5 files changed
+633
No files matched your search
@@ -0,0 +1,51 @@
|
|||||||
|
import { expect, test, vi } from "vitest";
|
||||||
|
|
||||||
|
const mocks = vi.hoisted(() => ({
|
||||||
|
grantAlbum: vi.fn(),
|
||||||
|
headers: vi.fn(),
|
||||||
|
requireAdmin: vi.fn(),
|
||||||
|
revalidatePath: vi.fn(),
|
||||||
|
revokeAlbum: vi.fn(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("next/headers", () => ({ headers: mocks.headers }));
|
||||||
|
vi.mock("next/cache", () => ({ revalidatePath: mocks.revalidatePath }));
|
||||||
|
vi.mock("@/modules/auth/principal", () => ({ requireAdmin: mocks.requireAdmin }));
|
||||||
|
vi.mock("@/modules/albums/grants", () => ({
|
||||||
|
albumGrantService: { grantAlbum: mocks.grantAlbum, revokeAlbum: mocks.revokeAlbum },
|
||||||
|
}));
|
||||||
|
|
||||||
|
import { grantAlbumAction } from "./actions";
|
||||||
|
|
||||||
|
test("the grant action rejects unauthenticated callers before accepting submitted identifiers", async () => {
|
||||||
|
mocks.headers.mockResolvedValue(new Headers());
|
||||||
|
mocks.requireAdmin.mockRejectedValue(new Error("ADMIN_REQUIRED"));
|
||||||
|
const formData = new FormData();
|
||||||
|
formData.set("immichAlbumId", "11111111-1111-4111-8111-111111111111");
|
||||||
|
formData.set("adminUserId", "forged-user");
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
grantAlbumAction("00000000-0000-4000-8000-000000000001", formData),
|
||||||
|
).rejects.toThrow("ADMIN_REQUIRED");
|
||||||
|
expect(mocks.grantAlbum).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("the grant action uses the authenticated principal instead of a submitted admin user ID", async () => {
|
||||||
|
mocks.headers.mockResolvedValue(new Headers());
|
||||||
|
mocks.requireAdmin.mockResolvedValue({ userId: "admin-1" });
|
||||||
|
mocks.grantAlbum.mockResolvedValue(undefined);
|
||||||
|
const formData = new FormData();
|
||||||
|
formData.set("immichAlbumId", "11111111-1111-4111-8111-111111111111");
|
||||||
|
formData.set("adminUserId", "forged-user");
|
||||||
|
|
||||||
|
await grantAlbumAction("00000000-0000-4000-8000-000000000001", formData);
|
||||||
|
|
||||||
|
expect(mocks.grantAlbum).toHaveBeenCalledWith({
|
||||||
|
editorialId: "00000000-0000-4000-8000-000000000001",
|
||||||
|
immichAlbumId: "11111111-1111-4111-8111-111111111111",
|
||||||
|
adminUserId: "admin-1",
|
||||||
|
});
|
||||||
|
expect(mocks.revalidatePath).toHaveBeenCalledWith(
|
||||||
|
"/admin/redaktionen/00000000-0000-4000-8000-000000000001/alben",
|
||||||
|
);
|
||||||
|
});
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
"use server";
|
||||||
|
|
||||||
|
import { revalidatePath } from "next/cache";
|
||||||
|
import { headers } from "next/headers";
|
||||||
|
|
||||||
|
import { albumGrantService } from "@/modules/albums/grants";
|
||||||
|
import { requireAdmin } from "@/modules/auth/principal";
|
||||||
|
|
||||||
|
export async function grantAlbumAction(editorialId: string, formData: FormData): Promise<void> {
|
||||||
|
const principal = await getAdminPrincipal();
|
||||||
|
const safeEditorialId = requiredId(editorialId);
|
||||||
|
const immichAlbumId = requiredId(formData.get("immichAlbumId"));
|
||||||
|
await albumGrantService.grantAlbum({
|
||||||
|
editorialId: safeEditorialId,
|
||||||
|
immichAlbumId,
|
||||||
|
adminUserId: principal.userId,
|
||||||
|
});
|
||||||
|
revalidatePath(`/admin/redaktionen/${safeEditorialId}/alben`);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function revokeAlbumAction(editorialId: string, formData: FormData): Promise<void> {
|
||||||
|
const principal = await getAdminPrincipal();
|
||||||
|
const safeEditorialId = requiredId(editorialId);
|
||||||
|
const immichAlbumId = requiredId(formData.get("immichAlbumId"));
|
||||||
|
await albumGrantService.revokeAlbum({
|
||||||
|
editorialId: safeEditorialId,
|
||||||
|
immichAlbumId,
|
||||||
|
adminUserId: principal.userId,
|
||||||
|
});
|
||||||
|
revalidatePath(`/admin/redaktionen/${safeEditorialId}/alben`);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getAdminPrincipal() {
|
||||||
|
return requireAdmin(new Headers(await headers()));
|
||||||
|
}
|
||||||
|
|
||||||
|
function requiredId(value: unknown): string {
|
||||||
|
if (
|
||||||
|
typeof value !== "string" ||
|
||||||
|
!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value)
|
||||||
|
) {
|
||||||
|
throw new Error("INVALID_ID");
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
import Image from "next/image";
|
||||||
|
import Link from "next/link";
|
||||||
|
import { eq } from "drizzle-orm";
|
||||||
|
import { notFound } from "next/navigation";
|
||||||
|
|
||||||
|
import { db } from "@/db/client";
|
||||||
|
import { editorialAccounts } from "@/db/schema";
|
||||||
|
import { albumGrantService } from "@/modules/albums/grants";
|
||||||
|
|
||||||
|
import { grantAlbumAction, revokeAlbumAction } from "./actions";
|
||||||
|
|
||||||
|
export default async function EditorialAlbumsPage({
|
||||||
|
params,
|
||||||
|
}: Readonly<{ params: Promise<{ id: string }> }>) {
|
||||||
|
const { id } = await params;
|
||||||
|
const [editorial] = await db
|
||||||
|
.select({ id: editorialAccounts.id, name: editorialAccounts.name })
|
||||||
|
.from(editorialAccounts)
|
||||||
|
.where(eq(editorialAccounts.id, id))
|
||||||
|
.limit(1);
|
||||||
|
if (!editorial) {
|
||||||
|
notFound();
|
||||||
|
}
|
||||||
|
|
||||||
|
const albumResult = await albumGrantService
|
||||||
|
.listAssignableAlbums(editorial.id)
|
||||||
|
.then((albums) => ({ albums, unavailable: false }))
|
||||||
|
.catch(() => ({ albums: [], unavailable: true }));
|
||||||
|
|
||||||
|
if (albumResult.unavailable) {
|
||||||
|
return (
|
||||||
|
<section className="content-section" aria-labelledby="albums-title">
|
||||||
|
<p className="eyebrow">Redaktion · Albumrechte</p>
|
||||||
|
<h1 id="albums-title">Alben für {editorial.name}</h1>
|
||||||
|
<p role="status">
|
||||||
|
Die Immich-Alben sind momentan nicht erreichbar. Bereits bestehende Zuweisungen bleiben
|
||||||
|
unverändert.
|
||||||
|
</p>
|
||||||
|
<p>
|
||||||
|
<Link href={`/admin/redaktionen/${editorial.id}`}>Zurück zur Redaktion</Link>
|
||||||
|
</p>
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section className="content-section" aria-labelledby="albums-title">
|
||||||
|
<p className="eyebrow">Redaktion · Albumrechte</p>
|
||||||
|
<h1 id="albums-title">Alben für {editorial.name}</h1>
|
||||||
|
<p>
|
||||||
|
Nur Alben, die der technische Immich-Zugang lesen kann, lassen sich zuweisen.
|
||||||
|
</p>
|
||||||
|
<p>
|
||||||
|
<Link href={`/admin/redaktionen/${editorial.id}`}>Zurück zur Redaktion</Link>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
{albumResult.albums.length === 0 ? (
|
||||||
|
<p>Derzeit sind keine zuweisbaren Alben vorhanden.</p>
|
||||||
|
) : (
|
||||||
|
<ul aria-label="Zuweisbare Immich-Alben">
|
||||||
|
{albumResult.albums.map((album) => {
|
||||||
|
const action = album.isGranted ? revokeAlbumAction : grantAlbumAction;
|
||||||
|
return (
|
||||||
|
<li key={album.id}>
|
||||||
|
<article aria-labelledby={`album-${album.id}`}>
|
||||||
|
{album.albumThumbnailAssetId ? (
|
||||||
|
<Image
|
||||||
|
alt={`Titelbild von ${album.albumName}`}
|
||||||
|
height={120}
|
||||||
|
src={`/api/assets/${encodeURIComponent(album.albumThumbnailAssetId)}/thumbnail`}
|
||||||
|
width={160}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<div aria-label="Kein Albumcover verfügbar" role="img">
|
||||||
|
Kein Cover
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<h2 id={`album-${album.id}`}>{album.albumName}</h2>
|
||||||
|
<p>{album.assetCount} Fotos</p>
|
||||||
|
<p>
|
||||||
|
Status: <strong>{album.isGranted ? "Zugewiesen" : "Nicht zugewiesen"}</strong>
|
||||||
|
</p>
|
||||||
|
<form action={action.bind(null, editorial.id)}>
|
||||||
|
<input name="immichAlbumId" type="hidden" value={album.id} />
|
||||||
|
<button type="submit">
|
||||||
|
{album.isGranted ? "Zuweisung aufheben" : "Album zuweisen"}
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
</article>
|
||||||
|
</li>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,182 @@
|
|||||||
|
import { expect, test, vi } from "vitest";
|
||||||
|
|
||||||
|
import {
|
||||||
|
ALBUM_GRANT_LOCK_ORDER,
|
||||||
|
AlbumGrantError,
|
||||||
|
createAlbumGrantService,
|
||||||
|
type AlbumGrantRepository,
|
||||||
|
} from "./grants";
|
||||||
|
import { EDITORIAL_MUTATION_LOCK_ORDER } from "@/modules/editorials/service";
|
||||||
|
|
||||||
|
type Grant = { editorialId: string; albumId: string; revokedAt: Date | null };
|
||||||
|
type Audit = {
|
||||||
|
eventType: string;
|
||||||
|
actorUserId: string;
|
||||||
|
editorialId: string;
|
||||||
|
albumId: string;
|
||||||
|
previousValues: Record<string, unknown>;
|
||||||
|
newValues: Record<string, unknown>;
|
||||||
|
};
|
||||||
|
|
||||||
|
function createRepository(initial: Grant[] = []) {
|
||||||
|
const grants = [...initial];
|
||||||
|
const audit: Audit[] = [];
|
||||||
|
const repository: AlbumGrantRepository = {
|
||||||
|
async listActiveAlbumIds(editorialId) {
|
||||||
|
return grants
|
||||||
|
.filter((grant) => grant.editorialId === editorialId && grant.revokedAt === null)
|
||||||
|
.map((grant) => grant.albumId);
|
||||||
|
},
|
||||||
|
async grant(input) {
|
||||||
|
const active = grants.find(
|
||||||
|
(grant) =>
|
||||||
|
grant.editorialId === input.editorialId &&
|
||||||
|
grant.albumId === input.immichAlbumId &&
|
||||||
|
grant.revokedAt === null,
|
||||||
|
);
|
||||||
|
if (active) return false;
|
||||||
|
|
||||||
|
const revoked = grants.find(
|
||||||
|
(grant) =>
|
||||||
|
grant.editorialId === input.editorialId &&
|
||||||
|
grant.albumId === input.immichAlbumId &&
|
||||||
|
grant.revokedAt !== null,
|
||||||
|
);
|
||||||
|
if (revoked) {
|
||||||
|
revoked.revokedAt = null;
|
||||||
|
} else {
|
||||||
|
grants.push({ editorialId: input.editorialId, albumId: input.immichAlbumId, revokedAt: null });
|
||||||
|
}
|
||||||
|
audit.push({
|
||||||
|
eventType: "album_granted",
|
||||||
|
actorUserId: input.adminUserId,
|
||||||
|
editorialId: input.editorialId,
|
||||||
|
albumId: input.immichAlbumId,
|
||||||
|
previousValues: { granted: false },
|
||||||
|
newValues: { granted: true },
|
||||||
|
});
|
||||||
|
return true;
|
||||||
|
},
|
||||||
|
async revoke(input) {
|
||||||
|
const active = grants.find(
|
||||||
|
(grant) =>
|
||||||
|
grant.editorialId === input.editorialId &&
|
||||||
|
grant.albumId === input.immichAlbumId &&
|
||||||
|
grant.revokedAt === null,
|
||||||
|
);
|
||||||
|
if (!active) return false;
|
||||||
|
active.revokedAt = new Date();
|
||||||
|
audit.push({
|
||||||
|
eventType: "album_revoked",
|
||||||
|
actorUserId: input.adminUserId,
|
||||||
|
editorialId: input.editorialId,
|
||||||
|
albumId: input.immichAlbumId,
|
||||||
|
previousValues: { granted: true },
|
||||||
|
newValues: { granted: false },
|
||||||
|
});
|
||||||
|
return true;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
return { repository, grants, audit };
|
||||||
|
}
|
||||||
|
|
||||||
|
function createService(initial: Grant[] = []) {
|
||||||
|
const { repository, grants, audit } = createRepository(initial);
|
||||||
|
const immich = {
|
||||||
|
getAlbum: vi.fn().mockResolvedValue({
|
||||||
|
id: "album-1",
|
||||||
|
albumName: "Pressefotos",
|
||||||
|
description: null,
|
||||||
|
albumThumbnailAssetId: "cover-1",
|
||||||
|
assetCount: 4,
|
||||||
|
assets: [],
|
||||||
|
}),
|
||||||
|
listAlbums: vi.fn().mockResolvedValue([
|
||||||
|
{
|
||||||
|
id: "album-1",
|
||||||
|
albumName: "Pressefotos",
|
||||||
|
description: null,
|
||||||
|
albumThumbnailAssetId: "cover-1",
|
||||||
|
assetCount: 4,
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
};
|
||||||
|
return {
|
||||||
|
service: createAlbumGrantService({ repository, immich }),
|
||||||
|
immich,
|
||||||
|
grants,
|
||||||
|
audit,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
test("refuses to grant an album that the service user cannot read", async () => {
|
||||||
|
const { service, immich } = createService();
|
||||||
|
immich.getAlbum.mockRejectedValue({ code: "IMMICH_NOT_FOUND" });
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
service.grantAlbum({ editorialId: "e1", immichAlbumId: "hidden", adminUserId: "a1" }),
|
||||||
|
).rejects.toMatchObject({ code: "ALBUM_NOT_ASSIGNABLE" });
|
||||||
|
});
|
||||||
|
|
||||||
|
test("granting an album is idempotent and records one state-change audit event", async () => {
|
||||||
|
const { service, audit } = createService();
|
||||||
|
|
||||||
|
await service.grantAlbum({ editorialId: "e1", immichAlbumId: "album-1", adminUserId: "a1" });
|
||||||
|
await service.grantAlbum({ editorialId: "e1", immichAlbumId: "album-1", adminUserId: "a1" });
|
||||||
|
|
||||||
|
await expect(service.getGrantedAlbumIds("e1")).resolves.toEqual(["album-1"]);
|
||||||
|
expect(audit).toEqual([
|
||||||
|
expect.objectContaining({
|
||||||
|
eventType: "album_granted",
|
||||||
|
actorUserId: "a1",
|
||||||
|
editorialId: "e1",
|
||||||
|
albumId: "album-1",
|
||||||
|
previousValues: { granted: false },
|
||||||
|
newValues: { granted: true },
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a revoked album can be re-granted without creating another current grant", async () => {
|
||||||
|
const { service, grants } = createService([
|
||||||
|
{ editorialId: "e1", albumId: "album-1", revokedAt: new Date("2026-08-08T00:00:00Z") },
|
||||||
|
]);
|
||||||
|
|
||||||
|
await service.grantAlbum({ editorialId: "e1", immichAlbumId: "album-1", adminUserId: "a1" });
|
||||||
|
|
||||||
|
expect(grants).toHaveLength(1);
|
||||||
|
await expect(service.getGrantedAlbumIds("e1")).resolves.toEqual(["album-1"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("revocation immediately removes the album from visible IDs and records the actor", async () => {
|
||||||
|
const { service, audit } = createService([
|
||||||
|
{ editorialId: "e1", albumId: "album-1", revokedAt: null },
|
||||||
|
]);
|
||||||
|
|
||||||
|
await service.revokeAlbum({ editorialId: "e1", immichAlbumId: "album-1", adminUserId: "a1" });
|
||||||
|
|
||||||
|
await expect(service.getGrantedAlbumIds("e1")).resolves.not.toContain("album-1");
|
||||||
|
expect(audit).toContainEqual(
|
||||||
|
expect.objectContaining({
|
||||||
|
eventType: "album_revoked",
|
||||||
|
actorUserId: "a1",
|
||||||
|
editorialId: "e1",
|
||||||
|
albumId: "album-1",
|
||||||
|
previousValues: { granted: true },
|
||||||
|
newValues: { granted: false },
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("uses the same lock order as approval so concurrent approval and revocation serialize", () => {
|
||||||
|
expect(ALBUM_GRANT_LOCK_ORDER).toEqual(EDITORIAL_MUTATION_LOCK_ORDER);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("reports a stable unavailable error when the Immich album list cannot be loaded", async () => {
|
||||||
|
const { service, immich } = createService();
|
||||||
|
immich.listAlbums.mockRejectedValue({ code: "IMMICH_TIMEOUT" });
|
||||||
|
|
||||||
|
await expect(service.listAssignableAlbums("e1")).rejects.toEqual(
|
||||||
|
new AlbumGrantError("IMMICH_UNAVAILABLE"),
|
||||||
|
);
|
||||||
|
});
|
||||||
@@ -0,0 +1,258 @@
|
|||||||
|
import "server-only";
|
||||||
|
|
||||||
|
import { and, eq, isNull, sql } from "drizzle-orm";
|
||||||
|
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
|
||||||
|
|
||||||
|
import { db } from "@/db/client";
|
||||||
|
import { albumGrants, auditEvents, editorialAccounts } from "@/db/schema";
|
||||||
|
import type * as schema from "@/db/schema";
|
||||||
|
import { EDITORIAL_MUTATION_LOCK_ORDER } from "@/modules/editorials/service";
|
||||||
|
import { immichClient } from "@/modules/immich/client";
|
||||||
|
import type { ImmichAlbumSummary, ImmichClient } from "@/modules/immich/types";
|
||||||
|
|
||||||
|
export type AssignableAlbum = ImmichAlbumSummary & { isGranted: boolean };
|
||||||
|
|
||||||
|
export type AlbumGrantInput = {
|
||||||
|
editorialId: string;
|
||||||
|
immichAlbumId: string;
|
||||||
|
adminUserId: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type AlbumGrantRepository = {
|
||||||
|
listActiveAlbumIds(editorialId: string): Promise<string[]>;
|
||||||
|
grant(input: AlbumGrantInput): Promise<boolean>;
|
||||||
|
revoke(input: AlbumGrantInput): Promise<boolean>;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const ALBUM_GRANT_LOCK_ORDER = EDITORIAL_MUTATION_LOCK_ORDER;
|
||||||
|
|
||||||
|
export class AlbumGrantError extends Error {
|
||||||
|
readonly name = "AlbumGrantError";
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
readonly code:
|
||||||
|
| "ALBUM_NOT_ASSIGNABLE"
|
||||||
|
| "IMMICH_UNAVAILABLE"
|
||||||
|
| "EDITORIAL_NOT_FOUND"
|
||||||
|
| "INVALID_ALBUM_GRANT_INPUT",
|
||||||
|
) {
|
||||||
|
super(code);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createAlbumGrantService({
|
||||||
|
repository,
|
||||||
|
immich,
|
||||||
|
}: {
|
||||||
|
repository: AlbumGrantRepository;
|
||||||
|
immich: Pick<ImmichClient, "getAlbum" | "listAlbums">;
|
||||||
|
}) {
|
||||||
|
return {
|
||||||
|
async listAssignableAlbums(editorialId: string): Promise<AssignableAlbum[]> {
|
||||||
|
assertIdentifier(editorialId);
|
||||||
|
const [albums, grantedAlbumIds] = await Promise.all([
|
||||||
|
loadAlbums(immich),
|
||||||
|
repository.listActiveAlbumIds(editorialId),
|
||||||
|
]);
|
||||||
|
const granted = new Set(grantedAlbumIds);
|
||||||
|
return albums.map((album) => ({ ...album, isGranted: granted.has(album.id) }));
|
||||||
|
},
|
||||||
|
|
||||||
|
async grantAlbum(input: AlbumGrantInput): Promise<void> {
|
||||||
|
assertInput(input);
|
||||||
|
try {
|
||||||
|
await immich.getAlbum(input.immichAlbumId);
|
||||||
|
} catch (error) {
|
||||||
|
if (hasCode(error, "IMMICH_NOT_FOUND")) {
|
||||||
|
throw new AlbumGrantError("ALBUM_NOT_ASSIGNABLE");
|
||||||
|
}
|
||||||
|
throw new AlbumGrantError("IMMICH_UNAVAILABLE");
|
||||||
|
}
|
||||||
|
await repository.grant(input);
|
||||||
|
},
|
||||||
|
|
||||||
|
async revokeAlbum(input: AlbumGrantInput): Promise<void> {
|
||||||
|
assertInput(input);
|
||||||
|
await repository.revoke(input);
|
||||||
|
},
|
||||||
|
|
||||||
|
async getGrantedAlbumIds(editorialId: string): Promise<string[]> {
|
||||||
|
assertIdentifier(editorialId);
|
||||||
|
return repository.listActiveAlbumIds(editorialId);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createAlbumGrantRepository(
|
||||||
|
database: NodePgDatabase<typeof schema>,
|
||||||
|
): AlbumGrantRepository {
|
||||||
|
return {
|
||||||
|
async listActiveAlbumIds(editorialId) {
|
||||||
|
const grants = await database
|
||||||
|
.select({ immichAlbumId: albumGrants.immichAlbumId })
|
||||||
|
.from(albumGrants)
|
||||||
|
.where(and(eq(albumGrants.editorialAccountId, editorialId), isNull(albumGrants.revokedAt)));
|
||||||
|
return grants.map((grant) => grant.immichAlbumId);
|
||||||
|
},
|
||||||
|
|
||||||
|
async grant(input) {
|
||||||
|
return database.transaction(async (transaction) => {
|
||||||
|
await lockEditorialAlbumMutation(transaction, input.editorialId);
|
||||||
|
const editorial = await lockEditorial(transaction, input.editorialId);
|
||||||
|
const grants = await lockAlbumGrants(transaction, input.editorialId, input.immichAlbumId);
|
||||||
|
const activeGrant = grants.find((grant) => grant.revokedAt === null);
|
||||||
|
if (activeGrant) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const changedAt = new Date();
|
||||||
|
const previousGrant = grants[0];
|
||||||
|
if (previousGrant) {
|
||||||
|
await transaction
|
||||||
|
.update(albumGrants)
|
||||||
|
.set({
|
||||||
|
grantedAt: changedAt,
|
||||||
|
grantedByUserId: input.adminUserId,
|
||||||
|
revokedAt: null,
|
||||||
|
})
|
||||||
|
.where(eq(albumGrants.id, previousGrant.id));
|
||||||
|
} else {
|
||||||
|
await transaction.insert(albumGrants).values({
|
||||||
|
editorialAccountId: editorial.id,
|
||||||
|
immichAlbumId: input.immichAlbumId,
|
||||||
|
grantedAt: changedAt,
|
||||||
|
grantedByUserId: input.adminUserId,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
await transaction.insert(auditEvents).values({
|
||||||
|
eventType: "album_granted",
|
||||||
|
actorUserId: input.adminUserId,
|
||||||
|
actorType: "admin",
|
||||||
|
entityType: "album_grant",
|
||||||
|
entityId: input.immichAlbumId,
|
||||||
|
previousValues: {
|
||||||
|
editorialId: editorial.id,
|
||||||
|
immichAlbumId: input.immichAlbumId,
|
||||||
|
granted: false,
|
||||||
|
},
|
||||||
|
newValues: {
|
||||||
|
editorialId: editorial.id,
|
||||||
|
immichAlbumId: input.immichAlbumId,
|
||||||
|
granted: true,
|
||||||
|
},
|
||||||
|
occurredAt: changedAt,
|
||||||
|
});
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
},
|
||||||
|
|
||||||
|
async revoke(input) {
|
||||||
|
return database.transaction(async (transaction) => {
|
||||||
|
await lockEditorialAlbumMutation(transaction, input.editorialId);
|
||||||
|
const editorial = await lockEditorial(transaction, input.editorialId);
|
||||||
|
const grants = await lockAlbumGrants(transaction, input.editorialId, input.immichAlbumId);
|
||||||
|
const activeGrant = grants.find((grant) => grant.revokedAt === null);
|
||||||
|
if (!activeGrant) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const changedAt = new Date();
|
||||||
|
await transaction
|
||||||
|
.update(albumGrants)
|
||||||
|
.set({ revokedAt: changedAt })
|
||||||
|
.where(and(eq(albumGrants.id, activeGrant.id), isNull(albumGrants.revokedAt)));
|
||||||
|
await transaction.insert(auditEvents).values({
|
||||||
|
eventType: "album_revoked",
|
||||||
|
actorUserId: input.adminUserId,
|
||||||
|
actorType: "admin",
|
||||||
|
entityType: "album_grant",
|
||||||
|
entityId: input.immichAlbumId,
|
||||||
|
previousValues: {
|
||||||
|
editorialId: editorial.id,
|
||||||
|
immichAlbumId: input.immichAlbumId,
|
||||||
|
granted: true,
|
||||||
|
},
|
||||||
|
newValues: {
|
||||||
|
editorialId: editorial.id,
|
||||||
|
immichAlbumId: input.immichAlbumId,
|
||||||
|
granted: false,
|
||||||
|
},
|
||||||
|
occurredAt: changedAt,
|
||||||
|
});
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadAlbums(immich: Pick<ImmichClient, "listAlbums">): Promise<ImmichAlbumSummary[]> {
|
||||||
|
try {
|
||||||
|
return await immich.listAlbums();
|
||||||
|
} catch {
|
||||||
|
throw new AlbumGrantError("IMMICH_UNAVAILABLE");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function assertInput(input: AlbumGrantInput): void {
|
||||||
|
assertIdentifier(input.editorialId);
|
||||||
|
assertIdentifier(input.immichAlbumId);
|
||||||
|
assertIdentifier(input.adminUserId);
|
||||||
|
}
|
||||||
|
|
||||||
|
function assertIdentifier(value: string): void {
|
||||||
|
if (!value.trim()) {
|
||||||
|
throw new AlbumGrantError("INVALID_ALBUM_GRANT_INPUT");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function hasCode(error: unknown, code: string): boolean {
|
||||||
|
return typeof error === "object" && error !== null && "code" in error && error.code === code;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function lockEditorialAlbumMutation(
|
||||||
|
transaction: NodePgDatabase<typeof schema>,
|
||||||
|
editorialId: string,
|
||||||
|
): Promise<void> {
|
||||||
|
await transaction.execute(
|
||||||
|
sql`select pg_advisory_xact_lock(hashtextextended(${editorialId}, 0))`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function lockEditorial(
|
||||||
|
transaction: NodePgDatabase<typeof schema>,
|
||||||
|
editorialId: string,
|
||||||
|
): Promise<{ id: string }> {
|
||||||
|
const [editorial] = await transaction
|
||||||
|
.select({ id: editorialAccounts.id })
|
||||||
|
.from(editorialAccounts)
|
||||||
|
.where(eq(editorialAccounts.id, editorialId))
|
||||||
|
.for("update")
|
||||||
|
.limit(1);
|
||||||
|
if (!editorial) {
|
||||||
|
throw new AlbumGrantError("EDITORIAL_NOT_FOUND");
|
||||||
|
}
|
||||||
|
return editorial;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function lockAlbumGrants(
|
||||||
|
transaction: NodePgDatabase<typeof schema>,
|
||||||
|
editorialId: string,
|
||||||
|
immichAlbumId: string,
|
||||||
|
) {
|
||||||
|
return transaction
|
||||||
|
.select({ id: albumGrants.id, revokedAt: albumGrants.revokedAt })
|
||||||
|
.from(albumGrants)
|
||||||
|
.where(
|
||||||
|
and(
|
||||||
|
eq(albumGrants.editorialAccountId, editorialId),
|
||||||
|
eq(albumGrants.immichAlbumId, immichAlbumId),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.for("update");
|
||||||
|
}
|
||||||
|
|
||||||
|
export const albumGrantService = createAlbumGrantService({
|
||||||
|
repository: createAlbumGrantRepository(db),
|
||||||
|
immich: immichClient,
|
||||||
|
});
|
||||||
Reference in new issue
Block a user