Skip to content

Commit

Permalink
reInitialization for remoteClient
Browse files Browse the repository at this point in the history
  • Loading branch information
PatrikMatiasko committed Aug 31, 2023
1 parent 4cfac78 commit 801bfdd
Show file tree
Hide file tree
Showing 8 changed files with 81 additions and 54 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import Tabs from '@shared-ui/components/Atomic/Tabs'
import Breadcrumbs from '@shared-ui/components/Layout/Header/Breadcrumbs'
import StatusTag from '@shared-ui/components/Atomic/StatusTag'
import { getApiErrorMessage } from '@shared-ui/common/utils'
import { security } from '@shared-ui/common/services'
import { clientAppSettings, security } from '@shared-ui/common/services'
import Footer from '@shared-ui/components/Layout/Footer'
import EditDeviceNameModal from '@shared-ui/components/Organisms/EditDeviceNameModal'
import Notification from '@shared-ui/components/Atomic/Notification/Toast'
Expand Down Expand Up @@ -60,6 +60,8 @@ const DevicesDetailsPage: FC<Props> = (props) => {

const { footerExpanded, setFooterExpanded } = useContext(AppContext)

clientAppSettings.reset()

useEffect(() => {
setDomReady(true)
}, [])
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import TableActionButton from '@shared-ui/components/Organisms/TableActionButton
import Notification from '@shared-ui/components/Atomic/Notification/Toast'
import { IconShowPassword, IconTrash, StatusTag } from '@shared-ui/components/Atomic'
import Breadcrumbs from '@shared-ui/components/Layout/Header/Breadcrumbs'
import { clientAppSettings } from '@shared-ui/common/services'

import { PendingCommandsExpandableList } from '@/containers/PendingCommands'
import { DEVICES_REGISTERED_UNREGISTERED_COUNT_EVENT_KEY, devicesStatuses, NO_DEVICE_NAME, RESET_COUNTER } from '../../constants'
Expand Down Expand Up @@ -59,6 +60,8 @@ const DevicesListPage: FC<any> = () => {
const combinedSelectedDevices = singleDevice ? [singleDevice] : selectedDevices
const { footerExpanded, setFooterExpanded, collapsed } = useContext(AppContext)

clientAppSettings.reset()

useEffect(() => {
deviceError &&
Notification.error(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,14 @@ const RemoteClientDetailPage: FC<any> = () => {
return (
<RemoteClientsPage>
{(clientData, wellKnownConfig) => {
if (!wellKnownConfig || !wellKnownConfig?.isInitialized) {
// console.group('render Props')
// console.log(wellKnownConfig)
// console.log(clientData)
// console.log({ isInitialized: wellKnownConfig?.isInitialized })
// console.log({ reInitialization: clientData.reInitialization })
// console.groupEnd()

if (!wellKnownConfig || !wellKnownConfig.isInitialized) {
return <FullPageLoader i18n={{ loading: _(g.loading) }} />
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { forwardRef, useEffect, useImperativeHandle, useState } from 'react'
import { useIntl } from 'react-intl'
import { useDispatch } from 'react-redux'

import { clientAppSettings } from '@shared-ui/common/services'
import {
Expand All @@ -19,15 +18,15 @@ import Notification from '@shared-ui/components/Atomic/Notification/Toast'
import { messages as t } from '../RemoteClients.i18n'
import { AppAuthProviderRefType, Props } from './RemoteClientsAuthProvider.types'
import notificationId from '@/notificationId'
import { unInitializeRemoteClient } from '@/containers/RemoteClients/slice'

const RemoteClientsAuthProvider = forwardRef<AppAuthProviderRefType, Props>((props, ref) => {
const { wellKnownConfig, clientData, children, setAuthError, setInitialize, unauthorizedCallback } = props
const { id, clientUrl, authenticationMode, preSharedSubjectId, preSharedKey, reInitialization } = clientData
const { wellKnownConfig, reInitialization, clientData, children, setAuthError, setInitialize, unauthorizedCallback } = props
const { id, clientUrl, authenticationMode, preSharedSubjectId, preSharedKey } = clientData
const { formatMessage: _ } = useIntl()
const [userData] = useState(clientAppSettings.getUserData())
const [signOutRedirect] = useState(clientAppSettings.getSignOutRedirect())
const dispatch = useDispatch()
const [reInitializationLoading, setReInitializationLoading] = useState(false)
const [initializationLoading, setInitializationLoading] = useState(false)

useImperativeHandle(ref, () => ({
getSignOutMethod: () =>
Expand All @@ -38,22 +37,25 @@ const RemoteClientsAuthProvider = forwardRef<AppAuthProviderRefType, Props>((pro
}))

useEffect(() => {
if (reInitialization) {
if (reInitialization && !reInitializationLoading) {
setReInitializationLoading(true)
console.log('%c reInitializationProp start! ', 'background: #f0000; color: #bada55')
reset(clientUrl, unauthorizedCallback)
.then(() => {
console.log('reset done')
dispatch(unInitializeRemoteClient(id))
console.log('%c reset done! ', 'background: #222; color: #bada55')
setInitialize(false)
setReInitializationLoading(false)
})
.catch(() => {})
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [reInitialization, clientUrl, id, setInitialize])
}, [reInitialization, clientUrl, id, setInitialize, wellKnownConfig?.isInitialized, reInitializationLoading, unauthorizedCallback])

useEffect(() => {
if (wellKnownConfig && !wellKnownConfig.isInitialized) {
if (wellKnownConfig && !wellKnownConfig.isInitialized && !initializationLoading) {
if (authenticationMode === DEVICE_AUTH_MODE.X509) {
try {
setInitializationLoading(true)
getOpenIdConfiguration(wellKnownConfig.remoteProvisioning?.authority!).then((result) => {
getJwksData(result.data.jwks_uri).then((result) => {
initializeJwksData(result.data).then((result) => {
Expand All @@ -64,15 +66,17 @@ const RemoteClientsAuthProvider = forwardRef<AppAuthProviderRefType, Props>((pro
identityCertificateChallenge.certificateSigningRequest
).then((result) => {
initializeFinal(identityCertificateChallenge.state, result.data.certificate).then(() => {
console.log('init done x509')
console.log('%c init done x509! ', 'background: #bada55; color: #1a1a1a')
setInitialize(true)
setInitializationLoading(false)
})
})
})
})
})
} catch (e) {
console.error(e)
setInitializationLoading(false)
setAuthError(e as string)
}
} else if (authenticationMode === DEVICE_AUTH_MODE.PRE_SHARED_KEY) {
Expand All @@ -81,8 +85,9 @@ const RemoteClientsAuthProvider = forwardRef<AppAuthProviderRefType, Props>((pro
initializedByPreShared(preSharedSubjectId, preSharedKey)
.then((r) => {
if (r.status === 200) {
console.log('init done PSK')
console.log('%c init done PSK! ', 'background: #bada55; color: #1a1a1a')
setInitialize(true)
setInitializationLoading(false)
}
})
.catch((e) => {
Expand All @@ -97,16 +102,17 @@ const RemoteClientsAuthProvider = forwardRef<AppAuthProviderRefType, Props>((pro
} catch (e) {
console.error(e)
setAuthError(e as string)
setInitializationLoading(false)
}
} else {
setAuthError('Bad parameters for PRE_SHARED_KEY mode')
setAuthError('Wrong parameters for PRE_SHARED_KEY mode')
}
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [wellKnownConfig, setAuthError, setInitialize])

if (!wellKnownConfig || !wellKnownConfig?.isInitialized) {
if (!wellKnownConfig || !wellKnownConfig?.isInitialized || initializationLoading) {
return (
<AppLoader
i18n={{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ export type Props = {
children: ReactElement
clientData: RemoteClientType
setAuthError: (error: string) => void
setInitialize: (isInitialize?: boolean) => void
setInitialize: (isInitialize: boolean) => void
unauthorizedCallback: () => void
wellKnownConfig?: WellKnownConfigType
reInitialization?: boolean
}
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,12 @@ const RemoteClientsPage: FC<Props> = (props) => {
},
})
const [httpGatewayAddress] = useState(getClientUrl(clientData?.clientUrl))
const [wellKnownConfig, setWellKnownConfig, reFetchConfig, wellKnownConfigError] = useWellKnownConfiguration(httpGatewayAddress, hubWellKnownConfig)
const [loading, setLoading] = useState(false)
const [wellKnownConfig, setWellKnownConfig, reFetchConfig, wellKnownConfigError] = useWellKnownConfiguration(
httpGatewayAddress,
hubWellKnownConfig,
() => loading && setLoading(false)
)

const [authError, setAuthError] = useState<string | undefined>(undefined)
const [initializedByAnother, setInitializedByAnother] = useState(false)
Expand All @@ -42,23 +47,38 @@ const RemoteClientsPage: FC<Props> = (props) => {

const setInitialize = useCallback(
(value = true) => {
setLoading(true)
setWellKnownConfig(
{
isInitialized: value,
} as WellKnownConfigType,
'update'
)

reFetchConfig().then(() => setLoading(false))
},
[setWellKnownConfig]
[reFetchConfig, setWellKnownConfig]
)

clientAppSettings.setGeneralConfig({
httpGatewayAddress,
})

const reInitialization = useMemo(
() =>
wellKnownConfig &&
wellKnownConfig.deviceAuthenticationMode !== DEVICE_AUTH_MODE.UNINITIALIZED &&
wellKnownConfig.deviceAuthenticationMode !== clientData.authenticationMode,
[wellKnownConfig, clientData]
)

const compareOwners = useCallback((wellKnownConfig?: WellKnownConfigType) => {
const userData = clientAppSettings.getUserData()
if (userData && wellKnownConfig) {
if (!wellKnownConfig.isInitialized) {
return true
}

const parsedData = jwtDecode(userData.access_token)
const ownerId = get(parsedData, wellKnownConfig?.remoteProvisioning?.jwtOwnerClaim as string, '')

Expand All @@ -67,29 +87,28 @@ const RemoteClientsPage: FC<Props> = (props) => {
}
}

// TODO!
// setInitializedByAnother(true)
return false
}, [])

const unauthorizedCallback = useCallback(() => {
if (clientData.authenticationMode === DEVICE_AUTH_MODE.PRE_SHARED_KEY) {
setSuspectedUnauthorized(true)

reFetchConfig().then((newWellKnownConfig: WellKnownConfigType) => {
if (compareOwners(newWellKnownConfig)) {
setSuspectedUnauthorized(false)
} else {
setInitializedByAnother(true)
}
})
}
}, [clientData.authenticationMode, compareOwners, reFetchConfig])
setSuspectedUnauthorized(true)

reFetchConfig().then((newWellKnownConfig: WellKnownConfigType) => {
if (compareOwners(newWellKnownConfig)) {
setSuspectedUnauthorized(false)
} else {
setInitializedByAnother(true)
}
})
}, [compareOwners, reFetchConfig])

const contextValue = useMemo(
() => ({
unauthorizedCallback,
useToken: compareOwners(wellKnownConfig) && clientData.authenticationMode === DEVICE_AUTH_MODE.X509,
}),
[clientData.authenticationMode, compareOwners, unauthorizedCallback, wellKnownConfig]
[unauthorizedCallback]
)

if (error) {
Expand All @@ -100,10 +119,13 @@ const RemoteClientsPage: FC<Props> = (props) => {
return <div className='client-error-message'>{wellKnownConfigError?.message}</div>
}

if (!wellKnownConfig) {
if (!wellKnownConfig || !clientData || loading) {
return <FullPageLoader i18n={{ loading: _(g.loading) }} />
} else {
clientAppSettings.setWellKnowConfig(wellKnownConfig)
clientAppSettings.setUseToken(compareOwners(wellKnownConfig) && clientData.authenticationMode === DEVICE_AUTH_MODE.X509)

console.log({ setUseToken: compareOwners(wellKnownConfig) && clientData.authenticationMode === DEVICE_AUTH_MODE.X509 })

if (wellKnownConfig.remoteProvisioning) {
clientAppSettings.setWebOAuthConfig({
Expand All @@ -128,13 +150,14 @@ const RemoteClientsPage: FC<Props> = (props) => {
{!initializedByAnother && !suspectedUnauthorized && (
<RemoteClientsAuthProvider
clientData={clientData}
reInitialization={reInitialization}
ref={authProviderRef}
setAuthError={setAuthError}
setInitialize={setInitialize}
unauthorizedCallback={unauthorizedCallback}
wellKnownConfig={wellKnownConfig}
>
{clientData.reInitialization ? <FullPageLoader i18n={{ loading: _(g.loading) }} /> : children(clientData, wellKnownConfig)}
{reInitialization ? <FullPageLoader i18n={{ loading: _(g.loading) }} /> : children(clientData, wellKnownConfig)}
</RemoteClientsAuthProvider>
)}
</div>
Expand Down
21 changes: 3 additions & 18 deletions http-gateway/web/src/containers/RemoteClients/slice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,13 +39,12 @@ const initialState: StoreType = {
id: '789',
created: '2023-07-22T17:58:11.427Z',
version: '0.6.0',
clientName: 'Test X509 RE',
clientName: 'Test X509 ffff',
clientUrl: 'https://212.89.237.161:50080',
status: remoteClientStatuses.REACHABLE,
authenticationMode: 'X509',
preSharedSubjectId: '',
preSharedKey: '',
reInitialization: true,
},
]
: [],
Expand Down Expand Up @@ -73,24 +72,10 @@ const { reducer, actions } = createSlice({
const index = state.remoteClients.findIndex((originRemoteClient) => originRemoteClient.id === payload.id)

if (index >= 0) {
const remoteClient = state.remoteClients[index]
// const remoteClient = state.remoteClients[index]
state.remoteClients[index] = {
...state.remoteClients[index],
...payload,
reInitialization:
remoteClient.authenticationMode !== payload.authenticationMode ||
remoteClient.preSharedSubjectId !== payload.preSharedSubjectId ||
remoteClient.preSharedKey !== payload.preSharedKey,
}
}
},
unInitializeRemoteClient(state, { payload }) {
const index = state.remoteClients.findIndex((originRemoteClient) => originRemoteClient.id === payload)

if (index >= 0) {
state.remoteClients[index] = {
...state.remoteClients[index],
reInitialization: false,
}
}
},
Expand All @@ -107,7 +92,7 @@ const { reducer, actions } = createSlice({
})

// Actions
export const { addRemoteClient, deleteRemoteClients, deleteAllRemoteClients, updateRemoteClients, updateRemoteClient, unInitializeRemoteClient } = actions
export const { addRemoteClient, deleteRemoteClients, deleteAllRemoteClients, updateRemoteClients, updateRemoteClient } = actions

// Reducer
export default reducer

0 comments on commit 801bfdd

Please sign in to comment.