Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src/assets/icons/edit.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
9 changes: 7 additions & 2 deletions src/assets/main.css
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ a:hover {

.resource-actions {
display: flex;
gap: var(--fdp-space-2);
gap: var(--fdp-space-6);
margin-left: auto;
}

Expand All @@ -139,14 +139,19 @@ a:hover {
padding: 6px 12px;
border: none;
background: none;
color: var(--fdp-color-link);
color: #00518e;
font: inherit;
font-size: 1rem;
line-height: 1.5;
text-decoration: none;
cursor: pointer;
transition: color 0.15s ease-in-out;
}

.resource-action:not(:disabled):hover {
color: #006ec1;
}

.resource-action--danger {
color: #dc3545;
}
Expand Down
10 changes: 9 additions & 1 deletion src/composables/fdpApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,9 @@ export type ResourceMember = {
}

export type ResourceMeta = {
member: { membership: ResourceMember['membership'] | null } | null
member: {
membership: (ResourceMember['membership'] & { permissions: { code: string }[] }) | null
} | null
}

/**
Expand Down Expand Up @@ -56,6 +58,12 @@ export function deleteOperationId(resourceType: string): string {
return `delete${operationName(resourceType)}`
}

/** The operation updating a resource, e.g. putCatalog; null when the root's is not advertised. */
export async function putOperationId(resource: ResourceIdentifier): Promise<string | null> {
if (resource !== null) return `put${operationName(resource.resourceType)}`
return getOperationId('/', 'put').catch(() => null)
}

/**
* Fetches a resource's meta; pass null for the root.
* ResourceMeta describes only the membership fields currently used by the client.
Expand Down
42 changes: 35 additions & 7 deletions src/composables/useMeta.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,27 @@
import { ref, watch, type Ref } from 'vue'
import { fetchMeta, type ResourceIdentifier } from './fdpApi'
import { computed, ref, watch, type Ref } from 'vue'
import { fetchMeta, putOperationId, type ResourceIdentifier } from './fdpApi'
import { isOperationOffered } from './apiDocs'
import { useAuth } from './useAuth'

/** The current user's membership on the resource (null for the root). */
/**
* The current user's membership on the resource (null for the root), and whether they can edit
* it: admins always, others with W on this exact resource, and only if its PUT is advertised.
*/
export function useMeta(resource: Ref<ResourceIdentifier>) {
const { isLoggedIn } = useAuth()
const { isLoggedIn, isAdmin } = useAuth()
const membershipName = ref<string | null>(null)
const hasWrite = ref(false)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
const hasWrite = ref(false)
const hasWritePermission = ref(false)

and so on

const putOperation = ref<string | null>(null)
// Whether meta loaded for the current resource, so canEdit is final.
const loaded = ref(false)
const error = ref<string | null>(null)
const canEdit = computed(
() =>
loaded.value &&
(isAdmin.value || hasWrite.value) &&
putOperation.value !== null &&
isOperationOffered(putOperation.value),
)

watch(
[resource, isLoggedIn],
Expand All @@ -15,18 +31,30 @@ export function useMeta(resource: Ref<ResourceIdentifier>) {
cancelled = true
})
membershipName.value = null
hasWrite.value = false
putOperation.value = null
loaded.value = false
error.value = null
if (!loggedIn) return
try {
const resourceMeta = await fetchMeta(currentResource)
const [resourceMeta, operationId] = await Promise.all([
fetchMeta(currentResource),
putOperationId(currentResource),
])
if (cancelled) return
membershipName.value = resourceMeta.member?.membership?.name ?? null
const membership = resourceMeta.member?.membership
membershipName.value = membership?.name ?? null
hasWrite.value = membership?.permissions.some(({ code }) => code === 'W') ?? false
Comment thread
dennisvang marked this conversation as resolved.
Resolved
putOperation.value = operationId
loaded.value = true
} catch (err) {
// Without meta, only admins still get their membership, from members.
console.warn('Failed to load meta', currentResource, err)
if (!cancelled) error.value = err instanceof Error ? err.message : 'Unable to load meta.'
}
},
{ immediate: true },
)

return { membershipName }
return { membershipName, canEdit, loaded, error }
}
13 changes: 13 additions & 0 deletions src/router/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { createRouter, createWebHistory } from 'vue-router'
import ResourceView from '@/views/ResourceView.vue'
import ResourceEditView from '@/views/ResourceEditView.vue'
import LoginView from '@/views/LoginView.vue'
import SearchView from '@/views/SearchView.vue'
import NotAllowedView from '@/views/NotAllowedView.vue'
Expand All @@ -20,6 +21,18 @@ const router = createRouter({
name: 'resource',
component: ResourceView,
},
{
path: '/edit',
name: 'fdp-root-edit',
component: ResourceEditView,
meta: { requiresAuth: true },
},
{
path: '/:resourceType/:id/edit',
name: 'resource-edit',
component: ResourceEditView,
meta: { requiresAuth: true },
},
{
path: '/login',
name: 'login',
Expand Down
49 changes: 49 additions & 0 deletions src/views/ResourceEditView.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
<script setup lang="ts">
import { computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useResourceView } from '../composables/useResourceView'
import { useMeta } from '../composables/useMeta'
import { internalHref } from '../composables/urlUtils'

const { loading, error, resource, resourceUri, title, breadcrumbs, resourceLabel } =
useResourceView()
const { canEdit, loaded, error: metaError } = useMeta(resource)
const router = useRouter()

const resourcePath = computed(() => internalHref(resourceUri.value))

// Without edit access, go back to the resource, as the legacy client does.
watch(
[loaded, canEdit],
([isLoaded, allowed]) => {
if (isLoaded && !allowed) void router.replace(resourcePath.value)
},
{ immediate: true },
)
</script>

<template>
<div>
<nav v-if="breadcrumbs.length > 0" class="breadcrumbs" aria-label="Breadcrumb">
<div class="breadcrumbs__inner">
<template v-for="item in breadcrumbs" :key="item.uri">
<router-link :to="internalHref(item.uri)" class="breadcrumb-link">{{
item.text
}}</router-link>
<span class="breadcrumb-sep">/</span>
</template>
<span class="breadcrumb-current">Edit</span>
</div>
</nav>

<main class="page-container">
<p v-if="error || metaError" class="alert alert-danger">Error: {{ error ?? metaError }}</p>
<p v-else-if="loading || !loaded">Loading…</p>
<template v-else>
<h1 class="resource-title">Edit {{ title ?? resourceLabel(resourceUri) }}</h1>
<p>Editing is not implemented yet.</p>
</template>
<router-link :to="resourcePath" class="text-link">Cancel</router-link>
</main>
</div>
</template>
13 changes: 11 additions & 2 deletions src/views/ResourceView.vue
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { useRawFormat, formats } from '../composables/useRawFormat'
import { internalHref } from '../composables/urlUtils'
import RdfGraph from '../components/RdfGraph.vue'
import MembershipBadge from '../components/MembershipBadge.vue'
import IconEdit from '../assets/icons/edit.svg?component'
import IconTrashAlt from '../assets/icons/trash-alt.svg?component'

const {
Expand All @@ -33,7 +34,10 @@ const {
resourceLabel,
} = useResourceView()

const { membershipName: metaMembershipName } = useMeta(resource)
const { membershipName: metaMembershipName, canEdit } = useMeta(resource)
const editPath = computed(() =>
resource.value ? `/${resource.value.resourceType}/${resource.value.id}/edit` : '/edit',
)
const {
currentMembershipName,
otherOwnerNames,
Expand Down Expand Up @@ -146,8 +150,13 @@ const {
:resource-type="resource?.resourceType ?? null"
/>
</div>
<div v-if="deleteAvailable" class="resource-actions">
<div v-if="canEdit || deleteAvailable" class="resource-actions">

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we use consistent names here, as in canEdit and canDelete, or is there a specific reason for using deleteAvailable?

<router-link v-if="canEdit" :to="editPath" class="resource-action">
<IconEdit />
Edit
</router-link>
<button
v-if="deleteAvailable"
type="button"
class="resource-action resource-action--danger"
:disabled="deleting"
Expand Down
19 changes: 19 additions & 0 deletions tests/composables/fdpApi.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,25 @@ describe('resource operations', () => {
})
})

it('names the PUT after the prefix, and reads the root PUT from the api-docs', async () => {
vi.stubGlobal('fetch', mockApiFetch(okJson(), resourceApiDocs))
const { putOperationId } = await import('../../src/composables/fdpApi')
expect(await putOperationId({ resourceType: 'catalog', id: 'abc' })).toBe('putCatalog')
// resourceApiDocs advertises no PUT /.
expect(await putOperationId(null)).toBeNull()

vi.resetModules()
vi.stubGlobal(
'fetch',
mockApiFetch(okJson(), {
openapi: '3.0.1',
paths: { '/': { put: { operationId: 'putResearch Hub' } } },

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

'putResearch Hub' makes me wonder what that is about and if it has any meaning in the application code. Could we use a more generic mock operationId value like 'mockOperation' or something like that?

Or perhaps use a variable, also because it is used twice:

const mockOperationId = 'some operation id'

}),
)
const { putOperationId: rootPutOperationId } = await import('../../src/composables/fdpApi')
expect(await rootPutOperationId(null)).toBe('putResearch Hub')
})

it('refuses an unadvertised operation even if a conventional endpoint path exists', async () => {
const handleRequest = vi.fn(okJson(meta))
vi.stubGlobal(
Expand Down
76 changes: 71 additions & 5 deletions tests/composables/useMeta.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,30 @@ import { effectScope, nextTick, ref, type EffectScope } from 'vue'
import { useMeta } from '../../src/composables/useMeta'
import { fetchMeta, type ResourceMeta } from '../../src/composables/fdpApi'

const auth = vi.hoisted(() => ({ isLoggedIn: { value: false } }))

vi.mock('../../src/composables/fdpApi', () => ({ fetchMeta: vi.fn() }))
const auth = vi.hoisted(() => ({ isLoggedIn: { value: false }, isAdmin: { value: false } }))
const offered = vi.hoisted(() => new Set<string>())

vi.mock('../../src/composables/fdpApi', () => ({
fetchMeta: vi.fn(),
putOperationId: async (resource: { resourceType: string } | null) =>
resource ? `put${resource.resourceType}` : null,
}))
vi.mock('../../src/composables/apiDocs', () => ({
isOperationOffered: (operationId: string) => offered.has(operationId),
}))
vi.mock('../../src/composables/useAuth', async () => {
const { ref } = await import('vue')
auth.isLoggedIn = ref(false)
auth.isAdmin = ref(false)
return { useAuth: () => auth }
})

const flushPromises = () => new Promise<void>((resolve) => setTimeout(resolve, 0))

const metaWith = (name: string | null): ResourceMeta => ({
member: { membership: name ? { name } : null },
const metaWith = (name: string | null, codes: string[] = []): ResourceMeta => ({
member: {
membership: name ? { name, permissions: codes.map((code) => ({ code })) } : null,
},
})

let scope: EffectScope
Expand All @@ -24,6 +35,8 @@ beforeEach(() => {
scope = effectScope()
vi.mocked(fetchMeta).mockReset()
auth.isLoggedIn.value = false
auth.isAdmin.value = false
offered.clear()
})

afterEach(() => {
Expand Down Expand Up @@ -118,3 +131,56 @@ describe('useMeta membershipName', () => {
expect(membershipName.value).toBeNull()
})
})

describe('useMeta canEdit', () => {
const catalog = { resourceType: 'catalog', id: 'abc' }

/** Runs useMeta on the catalog, logged in, and waits for meta. */
async function editAccess(meta: ResourceMeta) {
auth.isLoggedIn.value = true
vi.mocked(fetchMeta).mockResolvedValue(meta)
const result = scope.run(() => useMeta(ref(catalog)))!
await flushPromises()
return result
}

it('allows members with W when the PUT is advertised', async () => {
offered.add('putcatalog')
const { canEdit, loaded } = await editAccess(metaWith('Owner', ['C', 'W', 'D', 'A']))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

perhaps we could introduce Enums for the membership name and permission codes (not just here, but in the app code)?

For example:

enum MembershipName {
  Owner = 'Owner',
  DataProvider = 'Data Provider',
}

enum PermissionCode {
  Administration = 'A',
  Create = 'C',
  Delete = 'D',
  Insert = 'I',
  Read = 'R',
  Write = 'W',
}

expect(loaded.value).toBe(true)
expect(canEdit.value).toBe(true)
})

it('denies members without W', async () => {
offered.add('putcatalog')
const { canEdit } = await editAccess(metaWith('Data Provider', ['C']))
expect(canEdit.value).toBe(false)
})

it('allows admins without a membership', async () => {
offered.add('putcatalog')
auth.isAdmin.value = true
const { canEdit } = await editAccess(metaWith(null))
expect(canEdit.value).toBe(true)
})

it('denies everyone when the PUT is not advertised', async () => {
auth.isAdmin.value = true
const { canEdit } = await editAccess(metaWith('Owner', ['W']))
expect(canEdit.value).toBe(false)
})

it('reports a failed meta request instead of denying', async () => {
offered.add('putcatalog')
auth.isAdmin.value = true
auth.isLoggedIn.value = true
vi.mocked(fetchMeta).mockRejectedValue(new Error('HTTP 500'))
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
const { canEdit, loaded, error } = scope.run(() => useMeta(ref(catalog)))!
await flushPromises()
expect(error.value).toBe('HTTP 500')
expect(loaded.value).toBe(false)
expect(canEdit.value).toBe(false)
warn.mockRestore()
})
})
Loading