Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: check authorities in app adapter [LIBS-370] #757

Open
wants to merge 15 commits into
base: master
Choose a base branch
from
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
10 changes: 8 additions & 2 deletions adapter/i18n/en.pot
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,14 @@ msgstr ""
"Content-Type: text/plain; charset=utf-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n != 1)\n"
"POT-Creation-Date: 2022-09-22T19:11:17.660Z\n"
"PO-Revision-Date: 2022-09-22T19:11:17.660Z\n"
"POT-Creation-Date: 2022-10-18T07:20:55.997Z\n"
"PO-Revision-Date: 2022-10-18T07:20:55.997Z\n"

msgid "You don't have access to the {{appName}} app"
msgstr "You don't have access to the {{appName}} app"

msgid "Contact your system administrator for assistance with app access."
msgstr "Contact your system administrator for assistance with app access."

msgid "Save your data"
msgstr "Save your data"
Expand Down
5 changes: 3 additions & 2 deletions adapter/src/components/AppWrapper.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,15 @@ import React from 'react'
import { useCurrentUserLocale } from '../utils/useLocale.js'
import { useVerifyLatestUser } from '../utils/useVerifyLatestUser.js'
import { Alerts } from './Alerts.js'
import { AuthBoundary } from './AuthBoundary.js'
import { ConnectedHeaderBar } from './ConnectedHeaderBar.js'
import { ErrorBoundary } from './ErrorBoundary.js'
import { LoadingMask } from './LoadingMask.js'
import { styles } from './styles/AppWrapper.style.js'

export const AppWrapper = ({ children, plugin }) => {
const { loading: localeLoading } = useCurrentUserLocale()
const { loading: latestUserLoading } = useVerifyLatestUser()
KaiVandivier marked this conversation as resolved.
Show resolved Hide resolved
const { loading: latestUserLoading, user } = useVerifyLatestUser()

if (localeLoading || latestUserLoading) {
return <LoadingMask />
Expand All @@ -22,7 +23,7 @@ export const AppWrapper = ({ children, plugin }) => {
{!plugin && <ConnectedHeaderBar />}
<div className="app-shell-app">
<ErrorBoundary onRetry={() => window.location.reload()}>
{children}
<AuthBoundary user={user}>{children}</AuthBoundary>
</ErrorBoundary>
</div>
<Alerts />
Expand Down
57 changes: 57 additions & 0 deletions adapter/src/components/AuthBoundary.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { useConfig } from '@dhis2/app-runtime'
import { CenteredContent, NoticeBox } from '@dhis2/ui'
import PropTypes from 'prop-types'
import React from 'react'
import i18n from '../locales'

const IS_PRODUCTION_ENV = process.env.NODE_ENV === 'production'
const APP_MANAGER_AUTHORITY = 'M_dhis-web-maintenance-appmanager'
const APP_AUTH_NAME = process.env.REACT_APP_DHIS2_APP_AUTH_NAME
const LEGACY_APP_AUTH_NAME = process.env.REACT_APP_DHIS2_APP_LEGACY_AUTH_NAME

const isAppAvailable = ({ userAuthorities, apiVersion }) => {
// Skip check on dev
if (!IS_PRODUCTION_ENV) {
return true
}

// On server versions < 35, auth name uses config.title instead of .name
const requiredAppAuthority =
apiVersion >= 35 ? APP_AUTH_NAME : LEGACY_APP_AUTH_NAME

// Check for three possible authorities
return userAuthorities.some((authority) =>
['ALL', APP_MANAGER_AUTHORITY, requiredAppAuthority].includes(authority)
)
}

/**
* Block the app if the user doesn't have the correct permissions to view this
* app.
*/
export function AuthBoundary({ user, children }) {
const { appName, apiVersion } = useConfig()

return isAppAvailable({ userAuthorities: user.authorities, apiVersion }) ? (
children
) : (
<CenteredContent>
<NoticeBox
error
title={i18n.t("You don't have access to the {{appName}} app", {
appName,
})}
>
{i18n.t(
'Contact your system administrator for assistance with app access.'
)}
</NoticeBox>
</CenteredContent>
)
}
AuthBoundary.propTypes = {
children: PropTypes.node,
user: PropTypes.shape({
authorities: PropTypes.arrayOf(PropTypes.string),
}),
}
7 changes: 3 additions & 4 deletions adapter/src/utils/useVerifyLatestUser.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { useState } from 'react'
const USER_QUERY = {
user: {
resource: 'me',
params: { fields: ['id'] },
params: { fields: ['id', 'username', 'authorities'] },
},
}

Expand All @@ -22,7 +22,7 @@ const LATEST_USER_KEY = 'dhis2.latestUser'
export function useVerifyLatestUser() {
const { pwaEnabled } = useConfig()
const [finished, setFinished] = useState(false)
const { loading, error } = useDataQuery(USER_QUERY, {
const { loading, error, data } = useDataQuery(USER_QUERY, {
onComplete: async (data) => {
const latestUserId = localStorage.getItem(LATEST_USER_KEY)
const currentUserId = data.user.id
Expand All @@ -38,10 +38,9 @@ export function useVerifyLatestUser() {
setFinished(true)
},
})

if (error) {
throw new Error('Failed to fetch user ID: ' + error)
}

return { loading: loading || !finished }
return { loading: loading || !finished, user: data?.user }
}
17 changes: 13 additions & 4 deletions cli/src/lib/constructAppUrl.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
module.exports.constructAppUrl = (baseUrl, config, serverVersion) => {
const formatUrlSafeAppSlug = (appName) => {
return appName.replace(/[^A-Za-z0-9\s-]/g, '').replace(/\s+/g, '-')
}

const constructAppUrl = (baseUrl, config, serverVersion) => {
let appUrl = baseUrl

const isModernServer = serverVersion.major >= 2 && serverVersion.minor >= 35

// From core version 2.35, short_name is used instead of the human-readable title to generate the url slug
const urlSafeAppSlug = (isModernServer ? config.name : config.title)
.replace(/[^A-Za-z0-9\s-]/g, '')
.replace(/\s+/g, '-')
const urlSafeAppSlug = formatUrlSafeAppSlug(
isModernServer ? config.name : config.title
)

// From core version 2.35, core apps are hosted at the server root under the /dhis-web-* namespace
if (config.coreApp && isModernServer) {
Expand All @@ -25,3 +29,8 @@ module.exports.constructAppUrl = (baseUrl, config, serverVersion) => {
appUrl = scheme + appUrl.substr(scheme.length).replace(/\/+/g, '/')
return appUrl
}

module.exports = {
constructAppUrl,
formatUrlSafeAppSlug,
}
35 changes: 35 additions & 0 deletions cli/src/lib/formatAppAuthName.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
const { formatUrlSafeAppSlug } = require('./constructAppUrl')

const APP_AUTH_PREFIX = 'M_'
const DHIS_WEB = 'dhis-web-'

/**
* Returns the string that identifies the 'App view permission'
* required to view the app
*
* Ex: coreApp && name = 'data-visualizer': authName = 'M_dhis-web-data-visualizer'
* Ex: name = 'pwa-example': authName = 'M_pwaexample'
* Ex: name = 'BNA Action Tracker': authName = 'M_BNA_Action_Tracker'
*
* The 'legacy' parameter specifies server version < 2.35 which uses
* config.title instead of config.name
*/
const formatAppAuthName = ({ config, legacy }) => {
const appName = legacy ? config.title : config.name

if (config.coreApp) {
return APP_AUTH_PREFIX + DHIS_WEB + formatUrlSafeAppSlug(appName)
}

// This formatting is drawn from https://github.com/dhis2/dhis2-core/blob/master/dhis-2/dhis-api/src/main/java/org/hisp/dhis/appmanager/App.java#L494-L499
// (replaceAll is only introduced in Node 15)
return (
APP_AUTH_PREFIX +
appName
.trim()
.replace(/[^a-zA-Z0-9\s]/g, '')
.replace(/\s/g, '_')
)
}

module.exports = formatAppAuthName
39 changes: 39 additions & 0 deletions cli/src/lib/formatAppAuthName.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
const formatAppAuthName = require('./formatAppAuthName.js')

describe('core app handling', () => {
it('should handle core apps', () => {
const config = { coreApp: true, name: 'data-visualizer' }
const formattedAuthName = formatAppAuthName({ config })

expect(formattedAuthName).toBe('M_dhis-web-data-visualizer')
})
})

describe('non-core app handling', () => {
it('should handle app names with hyphens', () => {
const config = { name: 'hyphenated-string-example' }
const formattedAuthName = formatAppAuthName({ config })

expect(formattedAuthName).toBe('M_hyphenatedstringexample')
})

it('should handle app names with capitals and spaces', () => {
const config = { name: 'Multi Word App Name' }
const formattedAuthName = formatAppAuthName({ config })

expect(formattedAuthName).toBe('M_Multi_Word_App_Name')
})
})

describe('legacy app handling', () => {
it('should use title instead of name if the legacy flag is added', () => {
const config = {
name: 'Multi Word App Name',
title: 'Title of the App',
}
const formattedAuthName = formatAppAuthName({ config, legacy: true })

expect(formattedAuthName).not.toBe('M_Multi_Word_App_Name')
expect(formattedAuthName).toBe('M_Title_of_the_App')
})
})
3 changes: 3 additions & 0 deletions cli/src/lib/shell/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const { exec } = require('@dhis2/cli-helpers-engine')
const formatAppAuthName = require('../formatAppAuthName')
const { getPWAEnvVars } = require('../pwa')
const bootstrap = require('./bootstrap')
const getEnv = require('./env')
Expand All @@ -7,6 +8,8 @@ module.exports = ({ config, paths }) => {
const baseEnvVars = {
name: config.title,
version: config.version,
auth_name: formatAppAuthName({ config }),
legacy_auth_name: formatAppAuthName({ config, legacy: true }),
}

return {
Expand Down
2 changes: 2 additions & 0 deletions examples/pwa-app/d2.config.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
const config = {
type: 'app',
name: 'pwa-example',
title: 'PWA Example',

pwa: {
enabled: true,
Expand Down