Skip to content

Commit

Permalink
fix: Hide download action when file does not provide download permiss…
Browse files Browse the repository at this point in the history
…ions

This is not only a possibility for public shares but also for internal shares,
the current code only "checked" public shares.
This adds the same logic we use in the files app. Probably something to move to
`@nextcloud/sharing` but for the moment lets just reuse here.

Signed-off-by: Ferdinand Thiessen <[email protected]>
  • Loading branch information
susnux committed Sep 8, 2024
1 parent c334739 commit 2520adb
Show file tree
Hide file tree
Showing 6 changed files with 174 additions and 53 deletions.
70 changes: 70 additions & 0 deletions cypress/e2e/download-forbidden.cy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
/**
* SPDX-License: AGPL-3.0-or-later
* SPDX-: Nextcloud GmbH and Nextcloud contributors
*/

import type { User } from "@nextcloud/cypress"

Check failure on line 6 in cypress/e2e/download-forbidden.cy.ts

View workflow job for this annotation

GitHub Actions / NPM lint

Strings must use singlequote
import { ShareType } from "@nextcloud/sharing"

Check failure on line 7 in cypress/e2e/download-forbidden.cy.ts

View workflow job for this annotation

GitHub Actions / NPM lint

Strings must use singlequote

const fileName = 'image1.jpg'

Check failure on line 9 in cypress/e2e/download-forbidden.cy.ts

View workflow job for this annotation

GitHub Actions / NPM lint

'fileName' is assigned a value but never used

describe('Disable download button if forbidden', { testIsolation: true }, () => {
let sharee: User
let shareToken: string

Check failure on line 13 in cypress/e2e/download-forbidden.cy.ts

View workflow job for this annotation

GitHub Actions / NPM lint

'shareToken' is assigned a value but never used

before(() => {
cy.createRandomUser().then((user) => { sharee = user })
cy.createRandomUser().then((user) => {
// Upload test files
cy.createFolder(user, '/Photos')
cy.uploadFile(user, 'image1.jpg', 'image/jpeg', '/Photos/image1.jpg')

cy.login(user)
cy.createShare('/Photos',
{ shareWith: sharee.userId, shareType: ShareType.User, attributes: [{ scope: 'permissions', key: 'download', value: false }] },
).then((token: string) => { shareToken = token })
cy.logout()
})
})

beforeEach(() => {
cy.login(sharee)
cy.visit('/apps/files')
cy.openFile('Photos')
})

it('See the shared folder and images in files list', () => {
cy.getFile('image1.jpg', { timeout: 10000 })
.should('contain', 'image1 .jpg')
})

// TODO: Fix no-download files on server
it.skip('See the image can be shown', () => {
cy.getFile('image1.jpg').should('be.visible')
cy.openFile('image1.jpg')
cy.get('body > .viewer').should('be.visible')

cy.get('body > .viewer', { timeout: 10000 })
.should('be.visible')
.and('have.class', 'modal-mask')
.and('not.have.class', 'icon-loading')
})

it('See the title on the viewer header but not the Download nor the menu button', () => {
cy.getFile('image1.jpg').should('be.visible')
cy.openFile('image1.jpg')
cy.get('body > .viewer .modal-header__name').should('contain', 'image1.jpg')

cy.get('[role="dialog"]')
.should('be.visible')
.find('button[aria-label="Actions"]')
.click()

cy.get('[role="menu"]:visible')
.find('button')
.should('have.length', 2)
.each(($el) => {
expect($el.text()).to.match(/(Full screen|Open sidebar)/i)
})
})
})
58 changes: 38 additions & 20 deletions cypress/support/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,9 @@
*
*/

import { addCommands, User } from '@nextcloud/cypress'
import { addCommands } from '@nextcloud/cypress'
import { Permission } from '@nextcloud/files'
import { ShareType } from '@nextcloud/sharing'
import { basename } from 'path'
import axios from '@nextcloud/axios'

Check failure on line 27 in cypress/support/commands.ts

View workflow job for this annotation

GitHub Actions / NPM lint

'axios' is defined but never used
import { addCompareSnapshotCommand } from 'cypress-visual-regression/dist/command'
Expand Down Expand Up @@ -127,32 +129,48 @@ Cypress.Commands.add(
},
)

interface ShareOptions {
shareType: number
shareWith?: string
permissions: number
attributes?: { value: boolean, key: string, scope: string}[]
}

Cypress.Commands.add('createShare', (path: string, shareOptions?: ShareOptions) => {
return cy.request('/csrftoken').then(({ body }) => {
const requesttoken = body.token

return cy.request({
method: 'POST',
url: '../ocs/v2.php/apps/files_sharing/api/v1/shares?format=json',
headers: {
requesttoken,
},
body: {
path,
permissions: Permission.READ,
...shareOptions,
attributes: shareOptions?.attributes && JSON.stringify(shareOptions.attributes),
},
}).then(({ body }) => {
const shareToken = body.ocs?.data?.token
if (shareToken === undefined) {
throw new Error('Invalid OCS response')
}
cy.log('Share link created', shareToken)
return shareToken
})
})
})

/**
* Create a share link and return the share url
*
* @param {string} path the file/folder path
* @return {string} the share link url
*/
Cypress.Commands.add('createLinkShare', path => {
return cy.window().then(async window => {
try {
const request = await axios.post(`${Cypress.env('baseUrl')}/ocs/v2.php/apps/files_sharing/api/v1/shares`, {
path,
shareType: window.OC.Share.SHARE_TYPE_LINK,
}, {
headers: {
requesttoken: window.OC.requestToken,
},
})
if (!('ocs' in request.data) || !('token' in request.data.ocs.data && request.data.ocs.data.token.length > 0)) {
throw request
}
cy.log('Share link created', request.data.ocs.data.token)
return cy.wrap(request.data.ocs.data.token)
} catch (error) {
console.error(error)
}
}).should('have.length', 15)
return cy.createShare(path, { shareType: ShareType.Link })
})

Cypress.Commands.overwrite('compareSnapshot', (originalFn, subject, name, options) => {
Expand Down
25 changes: 0 additions & 25 deletions src/utils/canDownload.js

This file was deleted.

24 changes: 24 additions & 0 deletions src/utils/canDownload.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/*!
* SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

import type { FileInfo } from './fileUtils'

/**
* Check if download permissions are granted for a file
* @param fileInfo The file info to check
*/
export function canDownload(fileInfo: FileInfo) {
// TODO: This should probably be part of `@nextcloud/sharing`
// check share attributes
const shareAttributes = JSON.parse(fileInfo.shareAttributes || '[]')

if (shareAttributes && shareAttributes.length > 0) {
const downloadAttribute = shareAttributes.find(({ scope, key }) => scope === 'permissions' && key === 'download')
// We only forbid download if the attribute is *explicitly* set to 'false'
return downloadAttribute?.value !== false
}
// otherwise return true (as the file needs read permission otherwise we would not have opened it)
return true
}
17 changes: 17 additions & 0 deletions src/utils/fileUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ import camelcase from 'camelcase'
import { isNumber } from './numberUtil'

export interface FileInfo {
/** ID of the file (not unique if shared, use source instead) */
fileid?: number
/** Filename (name with path) */
filename: string
/** Basename of the file */
Expand All @@ -47,6 +49,21 @@ export interface FileInfo {
isFavorite?: boolean
/** File type */
type: 'directory'|'file'
/** Attributes for file shares */
shareAttributes?: string

// custom attributes not fetch from API

/** Does the file has an existing preview */
hasPreview?: boolean
/** URL of the preview image */
previewUrl?: string
/** The id of the peer live photo */
metadataFilesLivePhoto?: number
/** The absolute dav path */
davPath?: string
/** filename without extension */
name?: string
}

/**
Expand Down
33 changes: 25 additions & 8 deletions src/views/Viewer.vue
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,6 @@
:spread-navigation="true"
:style="{ width: isSidebarShown ? `${sidebarPosition}px` : null }"
:name="currentFile.basename"
:view="currentFile.modal"
class="viewer"
size="full"
@close="close"
Expand Down Expand Up @@ -99,21 +98,24 @@
:close-after-click="true"
:href="downloadPath">
<template #icon>
<Download :size="24" />
<Download :size="20" />
</template>
{{ t('viewer', 'Download') }}
</NcActionLink>
<NcActionButton v-if="canDelete"
:close-after-click="true"
@click="onDelete">
<template #icon>
<Delete :size="22" />
<Delete :size="20" />
</template>
{{ t('viewer', 'Delete') }}
</NcActionButton>
</template>

<div class="viewer__content" :class="contentClass" @click.self.exact="close">
<div class="viewer__content"
:class="contentClass"
@click.self.exact="close"
@contextmenu="preventContextMenu">
<!-- COMPARE FILE -->
<div v-if="comparisonFile && !comparisonFile.failed && showComparison" class="viewer__file-wrapper">
<component :is="comparisonFile.modal"
Expand Down Expand Up @@ -203,8 +205,8 @@ import isMobile from '@nextcloud/vue/dist/Mixins/isMobile.js'

import { extractFilePaths, sortCompare } from '../utils/fileUtils.ts'
import { registerViewerAction } from '../files_actions/viewerAction.ts'
import { canDownload } from '../utils/canDownload.ts'
import getSortingConfig from '../services/FileSortingConfig.ts'
import canDownload from '../utils/canDownload.js'
import cancelableRequest from '../utils/CancelableRequest.js'
import Error from '../components/Error.vue'
import File from '../models/file.js'
Expand Down Expand Up @@ -373,12 +375,16 @@ export default {
},

/**
* Is the current user allowed to download the file in public mode?
* Is the current user allowed to download the file
*
* @return {boolean}
*/
canDownload() {
return canDownload() && !this.comparisonFile
// download not possible for comparison
if (this.comparisonFile) {
return false
}
return this.currentFile && canDownload(this.currentFile)
},

/**
Expand All @@ -389,7 +395,7 @@ export default {
*/
canEdit() {
return !this.isMobile
&& canDownload()
&& this.canDownload
&& this.currentFile?.permissions?.includes('W')
&& this.isImage
&& !this.comparisonFile
Expand Down Expand Up @@ -578,6 +584,17 @@ export default {
},

methods: {
/**
* If there is no download permission also hide the context menu.
* @param {MouseEvent} event The mouse click event
*/
preventContextMenu(event) {
if (this.canDownload) {
return
}
event.preventDefault()
},

async beforeOpen() {
// initial loading start
this.initiated = true
Expand Down

0 comments on commit 2520adb

Please sign in to comment.