Skip to content

Commit

Permalink
feat(adapter): clear sensitive caches on user-change
Browse files Browse the repository at this point in the history
  • Loading branch information
KaiVandivier committed Sep 22, 2021
1 parent ceba7d7 commit 398cde2
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 2 deletions.
6 changes: 4 additions & 2 deletions adapter/src/components/AppWrapper.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,17 @@ import { HeaderBar } from '@dhis2/ui'
import PropTypes from 'prop-types'
import React from 'react'
import { useCurrentUserLocale } from '../utils/useLocale.js'
import { useVerifyLatestUser } from '../utils/useVerifyLatestUser.js'
import { Alerts } from './Alerts.js'
import { ErrorBoundary } from './ErrorBoundary.js'
import { LoadingMask } from './LoadingMask.js'
import { styles } from './styles/AppWrapper.style.js'

export const AppWrapper = ({ appName, children }) => {
const { loading } = useCurrentUserLocale()
const { loading: localeLoading } = useCurrentUserLocale()
const { loading: latestUserLoading } = useVerifyLatestUser()

if (loading) {
if (localeLoading || latestUserLoading) {
return <LoadingMask />
}

Expand Down
47 changes: 47 additions & 0 deletions adapter/src/utils/useVerifyLatestUser.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import {
useConfig,
useDataQuery,
clearSensitiveCaches,
} from '@dhis2/app-runtime'
import { useState } from 'react'

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

const LATEST_USER_KEY = 'dhis2.latestUser'

/**
* 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 useVerifyLatestUser() {
const { pwaEnabled } = useConfig()
const [finished, setFinished] = useState(false)
const { loading, error } = useDataQuery(USER_QUERY, {
onComplete: async data => {
const latestUserId = localStorage.getItem(LATEST_USER_KEY)
const currentUserId = data.user.id
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()
}
}
setFinished(true)
},
})

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

return { loading: loading || !finished }
}

0 comments on commit 398cde2

Please sign in to comment.