fix(auth): restore metadata editing lost to the 3.5.0 library roles

Promote Viewer grants to Editor on book libraries for non-superusers who hold Edit metadata but
can edit nowhere, which is how every such account was left after the upgrade. Accounts with any
Editor or Owner role are left alone. The Users drawer now says where Edit metadata takes effect,
read from a new GET /users/:id/library-access route.

Closes #1902
This commit is contained in:
neon
2026-10-24 03:56:25 +00:00
parent e28f45452d
commit d29b06c6e8
20 changed files with 26199 additions and 44 deletions
+24 -1
View File
@@ -14,11 +14,12 @@ import {
X,
type LucideIcon,
} from '@lucide/vue'
import { Permission, type LibraryType } from '@bookorbit/types'
import { Button } from '@/components/ui/button'
import { Sheet, SheetContent, SheetDescription, SheetTitle } from '@/components/ui/sheet'
import Badge from '@/components/ui/badge/Badge.vue'
import ToggleSwitch from '@/components/ui/ToggleSwitch.vue'
import { formatDate, formatDateTime, formatNumber } from '@/i18n/formatters'
import { formatDate, formatDateTime, formatList, formatNumber } from '@/i18n/formatters'
import StatusPill from './components/StatusPill.vue'
import UserPermissionsSection from './components/UserPermissionsSection.vue'
import UserRestrictionsSection from './components/UserRestrictionsSection.vue'
@@ -27,6 +28,7 @@ import { useUserForm, type UserFormSection, type UserFormTarget } from './compos
interface LibraryOption {
id: number
name: string
type?: LibraryType
bookCount?: number
}
@@ -57,6 +59,7 @@ const {
isSharedAccount,
selectedPermissionNames,
selectedLibraryIds,
editorLibraryIds,
includeTagItems,
excludeTagItems,
includeGenreItems,
@@ -183,6 +186,25 @@ const libraryReach = computed(() => {
return { selected: formatNumber(selected), total: formatNumber(total) }
})
/**
* Edit metadata only works on book libraries where the account is Editor or Owner, which is set on
* each library rather than here. Say so wherever that leaves the permission short of the selection.
*/
const permissionNotes = computed(() => {
if (isSuperuserTarget.value || !selectedPermissionNames.value.has(Permission.LibraryEditMetadata)) return {}
const bookLibraries = props.libraries.filter((library) => library.type !== 'podcasts' && selectedLibraryIds.value.has(library.id))
const viewerOnly = bookLibraries.filter((library) => !editorLibraryIds.value.has(library.id))
if (bookLibraries.length > 0 && viewerOnly.length === 0) return {}
const note =
viewerOnly.length === bookLibraries.length
? { text: t('adminFeature.userForm.permissionNotes.editMetadataNowhere'), warning: true }
: {
text: t('adminFeature.userForm.permissionNotes.editMetadataExcept', { libraries: formatList(viewerOnly.map((library) => library.name)) }),
warning: false,
}
return { [Permission.LibraryEditMetadata]: note }
})
const errorMessage = computed(() => {
if (error.value) return error.value
if (!errorKey.value) return null
@@ -540,6 +562,7 @@ async function handleSubmit() {
:selected="selectedPermissionNames"
:granted="grantedCount"
:total="totalPermissions"
:notes="permissionNotes"
@toggle="togglePermission"
@preset="applyPreset"
/>
@@ -1,6 +1,6 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { flushPromises, mount } from '@vue/test-utils'
import { Permission } from '@bookorbit/types'
import { Permission, type UserLibraryGrant } from '@bookorbit/types'
import UserFormDrawer from '../UserFormDrawer.vue'
import { grantingPermissions } from '../lib/permission-presets'
@@ -20,9 +20,9 @@ vi.mock('@/components/ui/sheet', () => ({
}))
const LIBRARIES = [
{ id: 1, name: 'Novels', bookCount: 120 },
{ id: 2, name: 'Comics', bookCount: 30 },
{ id: 3, name: 'Podcasts', bookCount: 0 },
{ id: 1, name: 'Novels', type: 'books' as const, bookCount: 120 },
{ id: 2, name: 'Comics', type: 'books' as const, bookCount: 30 },
{ id: 3, name: 'Podcasts', type: 'podcasts' as const, bookCount: 0 },
]
const USER = {
@@ -41,9 +41,9 @@ function jsonResponse(body: unknown) {
return { ok: true, json: async () => body }
}
function stubApi(overrides: { libraryIds?: number[]; filters?: unknown } = {}) {
function stubApi(overrides: { grants?: UserLibraryGrant[]; filters?: unknown } = {}) {
apiMock.mockImplementation(async (input: string) => {
if (input.endsWith('/libraries')) return jsonResponse(overrides.libraryIds ?? [1])
if (input.endsWith('/library-access')) return jsonResponse(overrides.grants ?? [{ libraryId: 1, accessLevel: 'viewer' }])
if (input.endsWith('/content-filters')) {
return jsonResponse(overrides.filters ?? { includeTags: [], excludeTags: [], includeGenres: [], excludeGenres: [] })
}
@@ -132,7 +132,7 @@ describe('UserFormDrawer sections', () => {
})
it('warns when no library is selected at all', async () => {
stubApi({ libraryIds: [] })
stubApi({ grants: [] })
const wrapper = await mountDrawer()
await openSection(wrapper, 'Libraries')
@@ -203,6 +203,64 @@ describe('UserFormDrawer permissions', () => {
expect(wrapper.text()).not.toContain('Upload books')
})
describe('Edit metadata note', () => {
const editor = { ...USER, permissions: [Permission.LibraryEditMetadata] }
function noteFor(wrapper: Drawer) {
const id = checkboxFor(wrapper, 'Edit metadata')?.attributes('aria-describedby')
return id ? wrapper.find(`[id="${id}"]`) : undefined
}
it('warns that the permission does nothing while every book library is Viewer only', async () => {
stubApi({
grants: [
{ libraryId: 1, accessLevel: 'viewer' },
{ libraryId: 3, accessLevel: 'owner' },
],
})
const wrapper = await mountDrawer({ user: editor })
await openSection(wrapper, 'Permissions')
expect(noteFor(wrapper)?.text()).toContain('No effect yet')
})
it('names the libraries where the account is still a Viewer', async () => {
stubApi({
grants: [
{ libraryId: 1, accessLevel: 'editor' },
{ libraryId: 2, accessLevel: 'viewer' },
],
})
const wrapper = await mountDrawer({ user: editor })
await openSection(wrapper, 'Permissions')
expect(noteFor(wrapper)?.text()).toContain('Not in Comics, where this account is a Viewer.')
})
it('treats a library ticked in this form as Viewer, since that is how it saves', async () => {
stubApi({ grants: [{ libraryId: 1, accessLevel: 'owner' }] })
const wrapper = await mountDrawer({ user: editor })
await openSection(wrapper, 'Permissions')
expect(noteFor(wrapper)).toBeUndefined()
await openSection(wrapper, 'Libraries')
await checkboxFor(wrapper, 'Comics')?.trigger('change')
await openSection(wrapper, 'Permissions')
expect(noteFor(wrapper)?.text()).toContain('Not in Comics')
})
it('stays quiet without the permission or for a superuser', async () => {
const wrapper = await mountDrawer()
await openSection(wrapper, 'Permissions')
expect(wrapper.text()).not.toContain('No effect yet')
const superuser = await mountDrawer({ user: { ...editor, isSuperuser: true } })
await openSection(superuser, 'Permissions')
expect(superuser.text()).not.toContain('No effect yet')
})
})
it('says so when a filter matches nothing', async () => {
const wrapper = await mountDrawer()
await openSection(wrapper, 'Permissions')
@@ -246,7 +304,7 @@ describe('UserFormDrawer saving', () => {
if (input.endsWith('/permissions') && init?.method === 'PUT') {
return { ok: false, json: async () => ({ message: 'Permission denied' }) }
}
if (input.endsWith('/libraries')) return jsonResponse([1])
if (input.endsWith('/library-access')) return jsonResponse([{ libraryId: 1, accessLevel: 'viewer' }])
if (input.endsWith('/content-filters')) return jsonResponse({})
return jsonResponse({})
})
@@ -1,7 +1,7 @@
<script setup lang="ts">
import { computed, ref } from 'vue'
import { computed, ref, useId } from 'vue'
import { useI18n } from 'vue-i18n'
import { Search } from '@lucide/vue'
import { Search, TriangleAlert } from '@lucide/vue'
import { Permission, PERMISSION_LABELS } from '@bookorbit/types'
import { formatNumber } from '@/i18n/formatters'
import {
@@ -16,6 +16,8 @@ const props = defineProps<{
selected: ReadonlySet<string>
total: number
granted: number
/** Context a permission needs beyond its checkbox, such as where it actually takes effect. */
notes?: Partial<Record<string, { text: string; warning: boolean }>>
}>()
const emit = defineEmits<{
@@ -24,6 +26,7 @@ const emit = defineEmits<{
}>()
const { t } = useI18n()
const noteIdPrefix = `permission-note-${useId()}`
const filter = ref('')
const grantedOnly = ref(false)
@@ -53,6 +56,7 @@ interface PermissionRow {
label: string
manage: boolean
checked: boolean
note?: { id: string; text: string; warning: boolean }
}
interface RenderedGroup {
@@ -77,12 +81,16 @@ const groups = computed<RenderedGroup[]>(() => {
const permissions = permissionsInGroup(group)
const rows = permissions
.map((permission) => ({
name: permission,
label: permissionLabel(permission),
manage: group.manage.includes(permission),
checked: props.selected.has(permission),
}))
.map((permission): PermissionRow => {
const note = props.notes?.[permission]
return {
name: permission,
label: permissionLabel(permission),
manage: group.manage.includes(permission),
checked: props.selected.has(permission),
note: note && { ...note, id: `${noteIdPrefix}-${permission}` },
}
})
.filter((row) => (grantedOnly.value ? row.checked : true))
.filter((row) => (query.length === 0 || groupMatches ? true : row.label.toLowerCase().includes(query)))
@@ -209,25 +217,33 @@ function clearFilters() {
</span>
</div>
<div :class="group.wide ? 'grid gap-x-4 @md:grid-cols-2 @xl:grid-cols-3' : ''">
<label
v-for="row in group.rows"
:key="row.name"
class="flex cursor-pointer items-start gap-2 rounded-xs py-1 focus-within:ring-2 focus-within:ring-ring"
>
<input
type="checkbox"
:checked="row.checked"
class="mt-0.5 size-4 shrink-0 rounded-xs border-input accent-primary"
@change="togglePermission(row.name)"
/>
<span class="text-sm leading-tight text-foreground">{{ row.label }}</span>
<span
v-if="row.manage && !group.manageOnly"
class="ms-auto mt-0.5 shrink-0 rounded-xs bg-muted px-1.5 py-0.5 text-[10px] font-semibold uppercase tracking-wide text-muted-foreground"
<div v-for="row in group.rows" :key="row.name">
<label class="flex cursor-pointer items-start gap-2 rounded-xs py-1 focus-within:ring-2 focus-within:ring-ring">
<input
type="checkbox"
:checked="row.checked"
:aria-describedby="row.note?.id"
class="mt-0.5 size-4 shrink-0 rounded-xs border-input accent-primary"
@change="togglePermission(row.name)"
/>
<span class="text-sm leading-tight text-foreground">{{ row.label }}</span>
<span
v-if="row.manage && !group.manageOnly"
class="ms-auto mt-0.5 shrink-0 rounded-xs bg-muted px-1.5 py-0.5 text-[10px] font-semibold uppercase tracking-wide text-muted-foreground"
>
{{ t('adminFeature.userForm.permissionLevels.manage') }}
</span>
</label>
<p
v-if="row.note"
:id="row.note.id"
class="flex items-start gap-1.5 pb-1 ps-6 text-xs leading-snug"
:class="row.note.warning ? 'text-[var(--pill-warning)]' : 'text-muted-foreground'"
>
{{ t('adminFeature.userForm.permissionLevels.manage') }}
</span>
</label>
<TriangleAlert v-if="row.note.warning" :size="13" class="mt-px shrink-0" aria-hidden="true" />
<span>{{ row.note.text }}</span>
</p>
</div>
</div>
</fieldset>
</div>
@@ -1,5 +1,5 @@
import { computed, ref, watch, type Ref } from 'vue'
import { PERMISSION_REQUIRES, type AuthUser, type Permission } from '@bookorbit/types'
import { PERMISSION_REQUIRES, type AccessLevel, type AuthUser, type Permission, type UserLibraryGrant } from '@bookorbit/types'
import { api } from '@/lib/api'
import { grantingPermissions, isRestrictionPermission, presetPermissions, type PermissionPreset } from '../lib/permission-presets'
@@ -47,6 +47,8 @@ export function useUserForm(user: Ref<UserFormTarget | null>, defaultLibraryIds:
const isSharedAccount = ref(false)
const selectedPermissionNames = ref<Set<string>>(new Set())
const selectedLibraryIds = ref<Set<number>>(new Set())
/** Saved roles only: a library ticked in this form is granted as a Viewer when it saves. */
const savedAccessLevels = ref<Map<number, AccessLevel>>(new Map())
const includeTagItems = ref<NamedItem[]>([])
const excludeTagItems = ref<NamedItem[]>([])
@@ -74,6 +76,17 @@ export function useUserForm(user: Ref<UserFormTarget | null>, defaultLibraryIds:
excludeGenreItems.value.length > 0,
)
/** Selected libraries where the account's role lets Edit metadata take effect. */
const editorLibraryIds = computed(
() =>
new Set(
[...selectedLibraryIds.value].filter((libraryId) => {
const level = savedAccessLevels.value.get(libraryId)
return level === 'editor' || level === 'owner'
}),
),
)
const restrictionPermissionNames = computed(() => [...selectedPermissionNames.value].filter(isRestrictionPermission))
const restrictionState = computed<RestrictionState>(() => {
@@ -175,6 +188,7 @@ export function useUserForm(user: Ref<UserFormTarget | null>, defaultLibraryIds:
isSharedAccount.value = target?.provisioningMethod === 'shared'
selectedPermissionNames.value = new Set(target?.permissions?.filter((permissionName) => permissionName !== '*') ?? [])
selectedLibraryIds.value = target?.id ? new Set() : new Set(defaultLibraryIds.value ?? [])
savedAccessLevels.value = new Map()
includeTagItems.value = []
excludeTagItems.value = []
includeGenreItems.value = []
@@ -195,15 +209,16 @@ export function useUserForm(user: Ref<UserFormTarget | null>, defaultLibraryIds:
}
const [librariesRes, filtersRes] = await Promise.all([
api(`/api/v1/users/${target.id}/libraries`),
api(`/api/v1/users/${target.id}/library-access`),
target.isSuperuser ? Promise.resolve(null) : api(`/api/v1/users/${target.id}/content-filters`),
])
if (user.value?.id !== target.id) return
if (librariesRes.ok) {
const libraryIds: number[] = await librariesRes.json()
selectedLibraryIds.value = new Set(libraryIds)
const grants: UserLibraryGrant[] = await librariesRes.json()
selectedLibraryIds.value = new Set(grants.map((grant) => grant.libraryId))
savedAccessLevels.value = new Map(grants.map((grant) => [grant.libraryId, grant.accessLevel]))
}
if (filtersRes?.ok) {
const filters = await filtersRes.json()
@@ -344,6 +359,7 @@ export function useUserForm(user: Ref<UserFormTarget | null>, defaultLibraryIds:
isSharedAccount,
selectedPermissionNames,
selectedLibraryIds,
editorLibraryIds,
includeTagItems,
excludeTagItems,
includeGenreItems,
@@ -25,7 +25,7 @@ export interface UserRow extends AuthUser {
provisioningMethod: ProvisioningMethod
}
export type UserLibrary = Pick<Library, 'id' | 'name' | 'bookCount'>
export type UserLibrary = Pick<Library, 'id' | 'name' | 'type' | 'bookCount'>
const EMPTY_SUMMARY: UserListSummary = { total: 0, admins: 0, active: 0, inactive: 0, attention: 0 }
+4
View File
@@ -4889,6 +4889,10 @@
"clearAll": "Clear",
"permissionsHint": "What this account is allowed to do. {granted} of {total} granted.",
"groupLegend": "{group}: {granted} of {total} granted",
"permissionNotes": {
"editMetadataNowhere": "No effect yet: it also needs the Editor or Owner role on a library, set in Settings > Libraries > Access.",
"editMetadataExcept": "Not in {libraries}, where this account is a Viewer. Set Editor or Owner in Settings > Libraries > Access."
},
"presets": {
"label": "Permission preset",
"none": "None",