feat(drive): UI: add drive edition for admin

This commit is contained in:
Edouard Vanbelle
2026-06-24 01:20:44 +02:00
parent a5b24a7453
commit d77846119f
15 changed files with 1448 additions and 45 deletions
+89 -1
View File
@@ -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 {
+36 -3
View File
@@ -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`, {
+36 -12
View File
@@ -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)
+13
View File
@@ -243,6 +243,19 @@ export interface Drive {
caller_role?: DriveRole | null;
}
/**
* Request body for `POST /api/drives` (D3a). Mirrors `CreateDriveDto` in
* `src/interfaces/api/handlers/drive_handler.rs`. `kind: 'personal'` is a
* recognised wire shape but returns 501 today (the authz model + quota
* source for secondary personals are still open product questions).
*/
export interface CreateDriveBody {
kind: DriveKind;
name: string;
owner: DriveMemberSubject;
quota_bytes?: number | null;
}
/**
* One row from `GET /api/drives/{id}/members`. Mirrors `GrantDto` in
* `src/application/dtos/grant_dto.rs` — the shape is the same as any
+2 -12
View File
@@ -62,23 +62,13 @@
onMount(() => {
void drivesStore.load();
});
// Dev/test override — set `localStorage.setItem('oxi-show-drive-picker', '1')`
// from DevTools to force the picker visible even with a single drive (useful
// for testing the UI before D3's shared-drive creation lands). Evaluated once
// at component mount; reload after toggling to apply.
const forceShowPicker = $derived(
typeof localStorage !== 'undefined' && localStorage.getItem('oxi-show-drive-picker') === '1'
);
</script>
<!-- Only show the drive switcher when there's an actual choice to make. With a
single drive (the default personal one) the picker just repeats "Personal"
under the Files nav row, so hide it; it reappears the moment a second drive
(e.g. a shared one) exists.
`forceShowPicker` is the localStorage-driven dev override (see script). -->
{#if drivesStore.loaded && (drivesStore.drives.length > 1 || forceShowPicker)}
(e.g. a shared one created from the admin Drives tab) exists. -->
{#if drivesStore.loaded && drivesStore.drives.length > 1}
<ul class="drive-picker" aria-label={t('drive.picker', 'Drives')}>
{#each sortedDrives as d (d.id)}
<li class="drive-picker__row" class:drive-picker__row--active={isActive(d)}>
@@ -0,0 +1,207 @@
<script lang="ts">
import Icon from '$lib/icons/Icon.svelte';
import { t } from '$lib/i18n/index.svelte';
import { resolveRecipient } from '$lib/api/endpoints/recipients';
import { resolveUser, type ResolvedUser } from '$lib/api/endpoints/users';
import { userInitials, avatarColorIndex } from '$lib/utils/avatar';
import type { DriveMember } from '$lib/api/types';
interface Props {
members: DriveMember[];
max?: number;
}
let { members, max = 6 }: Props = $props();
// Render only Owner-role grants and exclude token subjects (they can't
// own a drive per the service contract; defensive filter so a stray
// row from a future role doesn't render as an avatar).
const owners = $derived(
members.filter(
(m) => m.role === 'owner' && (m.subject.type === 'user' || m.subject.type === 'group')
)
);
const shown = $derived(owners.slice(0, max));
const overflow = $derived(Math.max(0, owners.length - shown.length));
// Per-user profile cache (image + email + real name). The cache itself
// lives in `resolveUser`; this state just mirrors what we've fetched so
// reactive `$derived` recomputes when a lookup lands.
let resolved = $state<Record<string, ResolvedUser | null>>({});
$effect(() => {
// Refresh on every membership change. `resolveUser` dedupes
// concurrent calls and caches per id, so this is cheap when the
// same id reappears across rows.
const users = owners.filter((m) => m.subject.type === 'user');
for (const m of users) {
if (m.subject.id in resolved) continue;
void resolveUser(m.subject.id).then((u) => {
resolved = { ...resolved, [m.subject.id]: u };
});
}
});
function nameFor(m: DriveMember): string {
if (m.subject.type === 'group') return resolveRecipient('group', m.subject.id).label;
return resolved[m.subject.id]?.name ?? resolveRecipient('user', m.subject.id).label;
}
function imageFor(m: DriveMember): string | null {
if (m.subject.type !== 'user') return null;
return resolved[m.subject.id]?.image ?? null;
}
function isExternalFor(m: DriveMember): boolean {
if (m.subject.type !== 'user') return false;
return resolved[m.subject.id]?.isExternal ?? false;
}
// "Name — email" tooltip; group falls back to label only.
function titleFor(m: DriveMember): string {
const name = nameFor(m);
if (m.subject.type === 'group') return name;
const email = resolved[m.subject.id]?.email ?? '';
return email ? `${name} — ${email}` : name;
}
</script>
{#if owners.length === 0}
<span class="owner-stack__empty">{t('admin.drive_no_owners', 'No owners')}</span>
{:else}
<ul class="owner-stack" aria-label={t('admin.drive_owners_aria', 'Drive owners')}>
{#each shown as m (`${m.subject.type}-${m.subject.id}`)}
{@const title = titleFor(m)}
{@const image = imageFor(m)}
<li class="owner-stack__chip" {title}>
{#if m.subject.type === 'group'}
<span class="owner-stack__avatar owner-stack__avatar--group">
<Icon name="users" />
</span>
{:else if image}
<img class="owner-stack__photo" src={image} alt="" />
{:else}
<span class="owner-stack__avatar owner-stack__avatar--c{avatarColorIndex(m.subject.id)}">
{userInitials(nameFor(m))}
</span>
{/if}
{#if isExternalFor(m)}
<span class="owner-stack__ext-badge" title={t('share.externalUser', 'External user')}>
<Icon name="building-circle-xmark" />
</span>
{/if}
</li>
{/each}
{#if overflow > 0}
<li class="owner-stack__chip" title={owners.slice(max).map(titleFor).join('\n')}>
<span class="owner-stack__avatar owner-stack__avatar--more">
+{overflow}
</span>
</li>
{/if}
</ul>
{/if}
<style>
.owner-stack {
display: inline-flex;
flex-direction: row;
list-style: none;
margin: 0;
padding: 0;
}
/* Negative margin = overlap. The chip after this one slides under,
producing the stacked look. First chip keeps full margin so the
leftmost avatar isn't clipped by the container. */
.owner-stack__chip {
position: relative;
margin-left: -0.5rem;
}
.owner-stack__chip:first-child {
margin-left: 0;
}
.owner-stack__avatar,
.owner-stack__photo {
display: inline-flex;
align-items: center;
justify-content: center;
width: 1.75rem;
height: 1.75rem;
border-radius: 50%;
font-size: 0.7rem;
font-weight: var(--weight-semibold, 600);
color: var(--color-text-light);
border: 2px solid var(--color-bg-surface);
box-sizing: border-box;
user-select: none;
object-fit: cover;
overflow: hidden;
}
/* Group icon avatar — neutral background, distinct from the coloured
user buckets so a viewer can tell user-vs-group at a glance. */
.owner-stack__avatar--group {
background: var(--color-bg-muted);
color: var(--color-text);
}
/* "+N" overflow chip mirrors the group neutral palette. */
.owner-stack__avatar--more {
background: var(--color-bg-muted);
color: var(--color-text);
font-weight: var(--weight-semibold, 600);
font-size: 0.65rem;
}
/* Colour buckets mirror UserVignette so the same user gets the same
colour across the app. */
.owner-stack__avatar--c0 {
background: var(--color-badge-indigo-bg);
color: var(--color-badge-indigo-text);
}
.owner-stack__avatar--c1 {
background: var(--color-badge-green-bg);
color: var(--color-badge-green-text);
}
.owner-stack__avatar--c2 {
background: var(--color-badge-orange-bg);
color: var(--color-badge-orange-text);
}
.owner-stack__avatar--c3 {
background: var(--color-badge-blue-bg);
color: var(--color-badge-blue-text);
}
.owner-stack__avatar--c4 {
background: var(--color-badge-amber-bg);
color: var(--color-badge-amber-text);
}
/* External-user marker — small badge in the bottom-right corner. */
.owner-stack__ext-badge {
position: absolute;
right: -2px;
bottom: -2px;
display: inline-flex;
align-items: center;
justify-content: center;
width: 0.85rem;
height: 0.85rem;
border-radius: 50%;
background: var(--color-bg-surface);
color: var(--color-text-muted);
font-size: 0.55rem;
}
.owner-stack__empty {
color: var(--color-text-muted);
font-style: italic;
font-size: 0.8125rem;
}
</style>