feat(drive): UI: add drive edition for admin
This commit is contained in:
@@ -5,7 +5,7 @@
|
||||
*/
|
||||
import { apiFetch, apiJson } from '$lib/api/client';
|
||||
import { getCsrfHeaders } from '$lib/api/csrf';
|
||||
import type { User } from '$lib/api/types';
|
||||
import type { Drive, DriveMember, DriveMemberSubject, DriveRole, User } from '$lib/api/types';
|
||||
|
||||
const JSON_HEADERS = { 'Content-Type': 'application/json' };
|
||||
|
||||
@@ -69,6 +69,94 @@ export function generateEncryptionKey(): Promise<GeneratedKey> {
|
||||
return postJson<GeneratedKey>('/api/admin/settings/storage/generate-key');
|
||||
}
|
||||
|
||||
// ── Drives ──────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* `GET /api/admin/drives` — every drive on the system, admin-only.
|
||||
*
|
||||
* Distinct from `listDrives()` in `$lib/api/endpoints/drives`, which is
|
||||
* the caller's own listing (filtered through `role_grants`). An admin
|
||||
* who creates a shared drive for someone else has no role on it, so
|
||||
* the user-facing listing would skip it — this endpoint returns
|
||||
* everything for the admin panel's "Drives" tab.
|
||||
*/
|
||||
export function listAllDrives(): Promise<Drive[]> {
|
||||
return apiJson<Drive[]>('/api/admin/drives', { credentials: 'same-origin' });
|
||||
}
|
||||
|
||||
/**
|
||||
* `GET /api/admin/drives/{id}/members` — every role grant on a drive,
|
||||
* admin-only. The user-facing `/api/drives/{id}/members` requires
|
||||
* `Permission::Read` on the drive; an admin who created the drive
|
||||
* for someone else has no role on it and would hit a 404 there. This
|
||||
* endpoint reuses `list_grants_on_resource` with the admin guard at
|
||||
* the route edge, so the same `DriveMember` shape comes back.
|
||||
*/
|
||||
export function listDriveMembersAdmin(driveId: string): Promise<DriveMember[]> {
|
||||
return apiJson<DriveMember[]>(`/api/admin/drives/${encodeURIComponent(driveId)}/members`, {
|
||||
credentials: 'same-origin'
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* `POST /api/admin/drives/{id}/members` — add (or refresh) a member as
|
||||
* an admin, bypassing the per-drive `Manage` check. Personal-drive
|
||||
* guard + last-owner protection still apply. Throws on non-2xx.
|
||||
*/
|
||||
export async function addDriveMemberAdmin(
|
||||
driveId: string,
|
||||
subject: DriveMemberSubject,
|
||||
role: DriveRole,
|
||||
expiresAt?: string | null
|
||||
): Promise<DriveMember> {
|
||||
const res = await apiFetch(`/api/admin/drives/${encodeURIComponent(driveId)}/members`, {
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
headers: { ...JSON_HEADERS, ...getCsrfHeaders() },
|
||||
body: JSON.stringify({ subject, role, expires_at: expiresAt ?? null })
|
||||
});
|
||||
if (!res.ok) {
|
||||
let detail = '';
|
||||
try {
|
||||
const parsed = (await res.json()) as { error?: string; message?: string };
|
||||
detail = parsed.error ?? parsed.message ?? '';
|
||||
} catch {
|
||||
/* response body wasn't JSON */
|
||||
}
|
||||
throw new Error(detail || `add member failed: ${res.status}`);
|
||||
}
|
||||
return (await res.json()) as DriveMember;
|
||||
}
|
||||
|
||||
/**
|
||||
* `DELETE /api/admin/drives/{id}/members/{kind}/{sid}` — remove a
|
||||
* member as an admin. Idempotent (removing a non-member returns 204).
|
||||
* Last-owner protection still applies (400 with `reason='last_owner'`).
|
||||
*/
|
||||
export async function removeDriveMemberAdmin(
|
||||
driveId: string,
|
||||
subject: DriveMemberSubject
|
||||
): Promise<void> {
|
||||
const url =
|
||||
`/api/admin/drives/${encodeURIComponent(driveId)}/members/` +
|
||||
`${encodeURIComponent(subject.type)}/${encodeURIComponent(subject.id)}`;
|
||||
const res = await apiFetch(url, {
|
||||
method: 'DELETE',
|
||||
credentials: 'same-origin',
|
||||
headers: getCsrfHeaders()
|
||||
});
|
||||
if (!res.ok) {
|
||||
let detail = '';
|
||||
try {
|
||||
const parsed = (await res.json()) as { error?: string; message?: string };
|
||||
detail = parsed.error ?? parsed.message ?? '';
|
||||
} catch {
|
||||
/* response body wasn't JSON */
|
||||
}
|
||||
throw new Error(detail || `remove member failed: ${res.status}`);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Users ───────────────────────────────────────────────────────────────
|
||||
|
||||
export interface AdminUsersPage {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* Drives endpoints. D0 ships read-only listing; D2 adds the membership API.
|
||||
* D3 will add the create-shared-drive flow under the same module.
|
||||
* Drives endpoints. D0 ships read-only listing; D2 adds the membership API;
|
||||
* D3a adds the create-shared-drive flow.
|
||||
*
|
||||
* Consumers usually go through the `drives` store (`$lib/stores/drives.svelte`)
|
||||
* which dedupes the request and caches the list — touch this module directly
|
||||
@@ -8,7 +8,13 @@
|
||||
*/
|
||||
import { apiFetch, apiJson } from '$lib/api/client';
|
||||
import { getCsrfHeaders } from '$lib/api/csrf';
|
||||
import type { Drive, DriveMember, DriveMemberSubject, DriveRole } from '$lib/api/types';
|
||||
import type {
|
||||
CreateDriveBody,
|
||||
Drive,
|
||||
DriveMember,
|
||||
DriveMemberSubject,
|
||||
DriveRole
|
||||
} from '$lib/api/types';
|
||||
|
||||
const JSON_HEADERS = { 'Content-Type': 'application/json' };
|
||||
|
||||
@@ -17,6 +23,33 @@ export function listDrives(): Promise<Drive[]> {
|
||||
return apiJson<Drive[]>('/api/drives', { credentials: 'same-origin' });
|
||||
}
|
||||
|
||||
/**
|
||||
* `POST /api/drives` — create a drive (D3a). Today only `kind: 'shared'` is
|
||||
* implemented; `kind: 'personal'` is accepted on the wire but returns 501.
|
||||
* Admin-only at the server; callers should already have gated the UI on
|
||||
* `session.user?.role === 'admin'`. Throws on non-2xx with the server's
|
||||
* error body parsed where possible.
|
||||
*/
|
||||
export async function createDrive(body: CreateDriveBody): Promise<Drive> {
|
||||
const res = await apiFetch('/api/drives', {
|
||||
method: 'POST',
|
||||
headers: { ...JSON_HEADERS, ...getCsrfHeaders() },
|
||||
credentials: 'same-origin',
|
||||
body: JSON.stringify(body)
|
||||
});
|
||||
if (!res.ok) {
|
||||
let detail = '';
|
||||
try {
|
||||
const parsed = (await res.json()) as { error?: string; message?: string };
|
||||
detail = parsed.error ?? parsed.message ?? '';
|
||||
} catch {
|
||||
/* response body wasn't JSON */
|
||||
}
|
||||
throw new Error(detail || `create drive failed: ${res.status}`);
|
||||
}
|
||||
return (await res.json()) as Drive;
|
||||
}
|
||||
|
||||
/** `GET /api/drives/{id}/members` — every role grant on the drive. */
|
||||
export function listDriveMembers(driveId: string): Promise<DriveMember[]> {
|
||||
return apiJson<DriveMember[]>(`/api/drives/${encodeURIComponent(driveId)}/members`, {
|
||||
|
||||
@@ -40,28 +40,45 @@ function looksLikeEmail(q: string): boolean {
|
||||
}
|
||||
|
||||
// The system book lists all users; we filter client-side (matches the original).
|
||||
// Two caches because the backend response differs (default excludes the caller,
|
||||
// `?include_self=1` returns them). Keying by flag avoids one variant overwriting
|
||||
// the other.
|
||||
let contactCache: Contact[] | null = null;
|
||||
let contactCacheWithSelf: Contact[] | null = null;
|
||||
/** `false` once we confirm the system address book is unavailable. */
|
||||
let directoryAvailable: boolean | null = null;
|
||||
|
||||
async function systemContacts(): Promise<Contact[]> {
|
||||
if (contactCache) return contactCache;
|
||||
async function systemContacts(includeSelf = false): Promise<Contact[]> {
|
||||
const cached = includeSelf ? contactCacheWithSelf : contactCache;
|
||||
if (cached) return cached;
|
||||
try {
|
||||
const res = await apiFetch('/api/address-books/system/contacts', {
|
||||
credentials: 'same-origin'
|
||||
});
|
||||
const url = includeSelf
|
||||
? '/api/address-books/system/contacts?include_self=1'
|
||||
: '/api/address-books/system/contacts';
|
||||
const res = await apiFetch(url, { credentials: 'same-origin' });
|
||||
if (!res.ok) {
|
||||
directoryAvailable = false;
|
||||
if (includeSelf) {
|
||||
contactCacheWithSelf = [];
|
||||
return contactCacheWithSelf;
|
||||
}
|
||||
contactCache = [];
|
||||
return contactCache;
|
||||
}
|
||||
directoryAvailable = true;
|
||||
contactCache = (await res.json()) as Contact[];
|
||||
const list = (await res.json()) as Contact[];
|
||||
if (includeSelf) contactCacheWithSelf = list;
|
||||
else contactCache = list;
|
||||
return list;
|
||||
} catch {
|
||||
directoryAvailable = false;
|
||||
if (includeSelf) {
|
||||
contactCacheWithSelf = [];
|
||||
return contactCacheWithSelf;
|
||||
}
|
||||
contactCache = [];
|
||||
return contactCache;
|
||||
}
|
||||
return contactCache;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -135,16 +152,23 @@ export function resolveRecipient(type: 'user' | 'group', id: string): Recipient
|
||||
/**
|
||||
* Combined user + group results matching the query (case-insensitive), plus a
|
||||
* synthetic invite-by-email suggestion when the query is an email that no
|
||||
* contact already owns. The current logged-in user is excluded — you can't
|
||||
* share with yourself. Capped at 8 combined (groups, then users, then email).
|
||||
* contact already owns. Capped at 8 combined (groups, then users, then email).
|
||||
*
|
||||
* `includeSelf` defaults to `false` — the share modal excludes the current
|
||||
* caller from the picker because "you can't share with yourself". The admin
|
||||
* drive-owners surface flips it on: an admin legitimately needs to add
|
||||
* themselves (or anyone) as Owner without that personal-share restriction.
|
||||
*/
|
||||
export async function searchRecipients(query: string): Promise<Recipient[]> {
|
||||
export async function searchRecipients(
|
||||
query: string,
|
||||
{ includeSelf = false }: { includeSelf?: boolean } = {}
|
||||
): Promise<Recipient[]> {
|
||||
const q = query.toLowerCase().trim();
|
||||
if (!q) return [];
|
||||
const currentUserId = session.user?.id ?? null;
|
||||
const [contacts, groups] = await Promise.all([systemContacts(), searchGroups(q)]);
|
||||
const [contacts, groups] = await Promise.all([systemContacts(includeSelf), searchGroups(q)]);
|
||||
const matched = contacts
|
||||
.filter((c) => c.id !== currentUserId)
|
||||
.filter((c) => includeSelf || c.id !== currentUserId)
|
||||
.map((c) => ({ c, ...contactLabel(c) }))
|
||||
.filter(
|
||||
({ label, email }) => label.toLowerCase().includes(q) || email.toLowerCase().includes(q)
|
||||
|
||||
Reference in New Issue
Block a user