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 1 commit
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
Prev Previous commit
Next Next commit
feat(adapter): check user app authorities before rendering app
  • Loading branch information
KaiVandivier committed Oct 14, 2022
commit 858546cd3e8a9d421d9f388b214c1c3830e18ea9
17 changes: 10 additions & 7 deletions adapter/src/components/AppWrapper.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ 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'
Expand All @@ -19,13 +20,15 @@ export const AppWrapper = ({ children }) => {
return (
<div className="app-shell-adapter">
<style jsx>{styles}</style>
<ConnectedHeaderBar />
<div className="app-shell-app">
<ErrorBoundary onRetry={() => window.location.reload()}>
{children}
</ErrorBoundary>
</div>
<Alerts />
<AuthBoundary>
<ConnectedHeaderBar />
<div className="app-shell-app">
<ErrorBoundary onRetry={() => window.location.reload()}>
{children}
</ErrorBoundary>
</div>
<Alerts />
</AuthBoundary>
</div>
)
}
Expand Down
95 changes: 95 additions & 0 deletions adapter/src/components/AuthBoundary.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import {
useConfig,
useDataQuery,
clearSensitiveCaches,
} from '@dhis2/app-runtime'
import PropTypes from 'prop-types'
import React, { useState } from 'react'
import { LoadingMask } from './LoadingMask'

// TODO: Remove useVerifyLatestUser
// TODO: add actual appName to config; rename existing to appTitle (& refactor)
// - will also need to change app-runtime and headerbar-ui APIs

const USER_QUERY = {
user: {
resource: 'me',
params: { fields: ['id', 'authorities'] },
},
}

const LATEST_USER_KEY = 'dhis2.latestUser'

const getRequiredAppAuthority = (appName) => {
// TODO: this only works for installed, non-core apps. Need other logic for those (dhis-web-app-name)
// Maybe add this logic to CLI add this to config, instead of needing more env vars here
// Need 'coreApp', 'name', 'title' (rename current appName to appTitle)
return (
'M_' +
appName
.trim()
.replaceAll(/[^a-zA-Z0-9\s]/g, '')
.replaceAll(/\s/g, '_')
)
}

async function clearCachesIfUserChanged({ currentUserId, pwaEnabled }) {
const latestUserId = localStorage.getItem(LATEST_USER_KEY)
if (currentUserId !== latestUserId) {
const cachesCleared = await clearSensitiveCaches()
localStorage.setItem(LATEST_USER_KEY, currentUserId)
if (cachesCleared && pwaEnabled) {
// If this is a PWA app, the app-shell cache will need to
// be restored with a page reload
return window.location.reload()
}
}
}

/**
* This hook is used to clear sensitive caches if a user other than the one
* that cached that data logs in
* @returns {Object} - { loading: boolean }
*/
export function AuthBoundary({ children }) {
const { pwaEnabled, appName } = useConfig()
const [finished, setFinished] = useState(false)
const { loading, error, data } = useDataQuery(USER_QUERY, {
onComplete: async ({ user }) => {
console.log({ authorities: user.authorities })

await clearCachesIfUserChanged({
currentUserId: user.id,
pwaEnabled,
})
setFinished(true)
},
})

if (loading || !finished) {
return <LoadingMask />
}

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

if (data) {
const userHasAllAuthority = data.user.authorities.includes('ALL')

const requiredAppAuthority = getRequiredAppAuthority(appName)
console.log({ requiredAppAuthority })

const userHasRequiredAppAuthority =
data.user.authorities.includes(requiredAppAuthority)
if (!userHasAllAuthority && !userHasRequiredAppAuthority) {
// TODO: better UI element than error boundary?
throw new Error('Forbidden: not authorized to view this app')
}
}

return children
}
AuthBoundary.propTypes = {
children: PropTypes.node,
}