-
Notifications
You must be signed in to change notification settings - Fork 21
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
* First working iteration * Replace connected private route with own privateRoute component * Replace PrivateRoute component in fhir-app
- Loading branch information
1 parent
e9b2c46
commit 2cc7d53
Showing
8 changed files
with
325 additions
and
315 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
77 changes: 77 additions & 0 deletions
77
packages/react-utils/src/components/PrivateRoute/index.tsx
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,77 @@ | ||
import { isAuthenticated } from '@onaio/session-reducer'; | ||
import React from 'react'; | ||
import { useSelector } from 'react-redux'; | ||
import { RouteProps, Route, Redirect, useRouteMatch, useLocation } from 'react-router'; | ||
import { getAllConfigs } from '@opensrp/pkg-config'; | ||
import { RbacCheck } from '@opensrp/rbac'; | ||
import { UnauthorizedPage } from '../UnauthorizedPage'; | ||
|
||
const configs = getAllConfigs(); | ||
|
||
export const LOGIN_REDIRECT_URL_PARAM = 'next'; | ||
|
||
/** interface for PrivateRoute props */ | ||
interface PrivateRouteProps extends RouteProps { | ||
disableLoginProtection: boolean /** should we disable login protection */; | ||
redirectPath: string /** redirect to this path is use if not authenticated */; | ||
permissions: string[] /** string representing permissions required to view nested view */; | ||
} | ||
|
||
/** declare default props for PrivateRoute */ | ||
const defaultPrivateRouteProps: Partial<PrivateRouteProps> = { | ||
disableLoginProtection: false, | ||
redirectPath: '/login', | ||
permissions: [], | ||
}; | ||
|
||
/** | ||
* Wrapper around route that makes sure user is authenticated and has the correct permission | ||
* | ||
* @param props - component props | ||
*/ | ||
const PrivateRoute = (props: PrivateRouteProps) => { | ||
const allProps = { | ||
...props, | ||
keycloakBaseURL: configs.keycloakBaseURL, | ||
opensrpBaseURL: configs.opensrpBaseURL, | ||
fhirBaseURL: configs.fhirBaseURL, | ||
}; | ||
const { component, disableLoginProtection, redirectPath, permissions, ...routeProps } = allProps; | ||
const Component = component as unknown as typeof React.Component; | ||
|
||
const match = useRouteMatch(); | ||
const location = useLocation(); | ||
const authenticated = useSelector((state) => isAuthenticated(state)); | ||
|
||
const nextUrl = match.path; | ||
const currentSParams = new URLSearchParams(location.search); | ||
currentSParams.set(LOGIN_REDIRECT_URL_PARAM, nextUrl); | ||
|
||
const fullRedirectPath = `${redirectPath}?${currentSParams.toString()}`; | ||
const okToRender = authenticated === true || disableLoginProtection === true; | ||
if (!okToRender) { | ||
return <Redirect to={fullRedirectPath} />; | ||
} | ||
|
||
return ( | ||
<Route {...routeProps}> | ||
{(routeProps) => ( | ||
<RbacCheck | ||
permissions={permissions} | ||
fallback={ | ||
<UnauthorizedPage | ||
title={'403'} | ||
errorMessage={'Sorry, you are not authorized to access this page'} | ||
/> | ||
} | ||
> | ||
<Component {...routeProps} {...allProps} /> | ||
</RbacCheck> | ||
)} | ||
</Route> | ||
); | ||
}; | ||
|
||
PrivateRoute.defaultProps = defaultPrivateRouteProps; | ||
|
||
export { PrivateRoute }; |
239 changes: 239 additions & 0 deletions
239
packages/react-utils/src/components/PrivateRoute/tests/index.test.tsx
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,239 @@ | ||
/* eslint-disable @typescript-eslint/no-explicit-any */ | ||
/* eslint-disable @typescript-eslint/naming-convention */ | ||
import React, { useEffect, useState } from 'react'; | ||
import { act } from 'react-dom/test-utils'; | ||
import { history } from '@onaio/connected-reducer-registry'; | ||
import { Provider } from 'react-redux'; | ||
import { MemoryRouter, Router } from 'react-router'; | ||
import { store } from '@opensrp/store'; | ||
import { mount } from 'enzyme'; | ||
import toJson from 'enzyme-to-json'; | ||
import { authenticateUser } from '@onaio/session-reducer'; | ||
import flushPromises from 'flush-promises'; | ||
import fetch from 'jest-fetch-mock'; | ||
import { RoleContext, UserRole } from '@opensrp/rbac'; | ||
import { render } from '@testing-library/react'; | ||
import { createMemoryHistory } from 'history'; | ||
import { superUserRole } from '../../../helpers/test-utils'; | ||
import { PrivateRoute as PrivateComponent } from '../'; | ||
|
||
it('First check that user is logged in before Rbac', async () => { | ||
const MockComponent = () => { | ||
return <p>I love oof!</p>; | ||
}; | ||
const history = createMemoryHistory(); | ||
const props = { | ||
component: MockComponent, | ||
redirectPath: '/login', | ||
disableLoginProtection: false, | ||
}; | ||
|
||
render( | ||
<Provider store={store}> | ||
<Router history={history}> | ||
<RoleContext.Provider value={superUserRole}> | ||
<PrivateComponent {...props} component={MockComponent} permissions={[]} /> | ||
</RoleContext.Provider> | ||
</Router> | ||
</Provider> | ||
); | ||
await act(async () => { | ||
await flushPromises(); | ||
}); | ||
|
||
// should redirect non-AuthN'd users to login | ||
expect(history.location.pathname).toEqual('/login'); | ||
expect(history.location.search).toEqual('?next=%2F'); | ||
}); | ||
|
||
it('PrivateComponent Renders correctly', async () => { | ||
store.dispatch( | ||
authenticateUser( | ||
true, | ||
{ | ||
email: '[email protected]', | ||
name: 'This Name', | ||
username: 'tHat Part', | ||
}, | ||
{ | ||
roles: ['ROLE_VIEW_KEYCLOAK_USERS'], | ||
username: 'superset-user', | ||
user_id: 'cab07278-c77b-4bc7-b154-bcbf01b7d35b', | ||
} | ||
) | ||
); | ||
const MockComponent = () => { | ||
return <p>I love oof!</p>; | ||
}; | ||
const props = { | ||
exact: true, | ||
redirectPath: '/login', | ||
disableLoginProtection: false, | ||
path: '/admin', | ||
authenticated: true, | ||
}; | ||
|
||
const wrapper = mount( | ||
<Provider store={store}> | ||
<MemoryRouter initialEntries={[{ pathname: `/admin`, hash: '', search: '', state: {} }]}> | ||
<RoleContext.Provider value={superUserRole}> | ||
<PrivateComponent {...props} component={MockComponent} permissions={[]} /> | ||
</RoleContext.Provider> | ||
</MemoryRouter> | ||
</Provider> | ||
); | ||
await act(async () => { | ||
await flushPromises(); | ||
await flushPromises(); | ||
}); | ||
wrapper.update(); | ||
// test if isAuthorized is called | ||
expect(wrapper.exists(MockComponent)).toBeTruthy(); | ||
wrapper.unmount(); | ||
}); | ||
|
||
it('Show Unauthorized Page if role does not have sufficient permissions', async () => { | ||
const MockComponent = () => { | ||
return <p>I love oof!</p>; | ||
}; | ||
const props = { | ||
exact: true, | ||
redirectPath: '/login', | ||
disableLoginProtection: false, | ||
path: '/admin', | ||
authenticated: true, | ||
}; | ||
const wrapper = mount( | ||
<Provider store={store}> | ||
<MemoryRouter initialEntries={[{ pathname: `/admin`, hash: '', search: '', state: {} }]}> | ||
<RoleContext.Provider value={new UserRole()}> | ||
<PrivateComponent | ||
{...props} | ||
component={MockComponent} | ||
permissions={['iam_user.create']} | ||
/> | ||
</RoleContext.Provider> | ||
</MemoryRouter> | ||
</Provider> | ||
); | ||
await act(async () => { | ||
await flushPromises(); | ||
wrapper.update(); | ||
}); | ||
expect(wrapper.exists(MockComponent)).toBeFalsy(); | ||
// test if UnauthorizedPage is rendered | ||
expect(wrapper.find('UnauthorizedPage').text()).toMatchInlineSnapshot( | ||
`"403Sorry, you are not authorized to access this pageGo backGo home"` | ||
); | ||
expect(toJson(wrapper.find('UnauthorizedPage'))).toBeTruthy(); | ||
wrapper.unmount(); | ||
}); | ||
|
||
it('Updates state on route/pathname changes for same component', async () => { | ||
store.dispatch( | ||
authenticateUser( | ||
true, | ||
{ | ||
email: '[email protected]', | ||
name: 'This Name', | ||
username: 'tHat Part', | ||
}, | ||
{ | ||
roles: ['ROLE_VIEW_KEYCLOAK_USERS'], | ||
username: 'superset-user', | ||
user_id: 'cab07278-c77b-4bc7-b154-bcbf01b7d35b', | ||
} | ||
) | ||
); | ||
|
||
// mock component with internal state change | ||
const MockComponent = (props: { | ||
match: { | ||
params: { | ||
id: string; | ||
}; | ||
}; | ||
}) => { | ||
// get user id from url | ||
const { | ||
match: { | ||
params: { id }, | ||
}, | ||
} = props; | ||
const [someState, setSomeState] = useState<{ | ||
firstName: string; | ||
lastName: string; | ||
}>({ | ||
firstName: '', | ||
lastName: '', | ||
}); | ||
|
||
// update state on fetch - internal data change on mount | ||
useEffect(() => { | ||
fetch(`http://example.com/users/${id}`) | ||
.then((response) => response.json()) | ||
.then((data) => setSomeState(data)) | ||
.catch((err) => { | ||
throw err; | ||
}); | ||
}, [id]); | ||
|
||
return <p className="mockClassName">{`${someState.firstName} ${someState.lastName}`}</p>; | ||
}; | ||
|
||
// mock re-fetch on re-mount | ||
fetch | ||
.mockOnce( | ||
JSON.stringify({ | ||
firstName: 'Anon', | ||
lastName: 'Ops', | ||
}) | ||
) | ||
.mockOnce( | ||
JSON.stringify({ | ||
firstName: 'Anon', | ||
lastName: 'Central', | ||
}) | ||
); | ||
|
||
const props = { | ||
exact: true, | ||
redirectPath: '/login', | ||
disableLoginProtection: false, | ||
path: '/admin/users/:id', | ||
authenticated: true, | ||
}; | ||
|
||
// start with user with id 1 | ||
history.push('/admin/users/1'); | ||
|
||
const wrapper = mount( | ||
<Provider store={store}> | ||
<Router history={history}> | ||
<RoleContext.Provider value={superUserRole}> | ||
<PrivateComponent {...props} component={MockComponent} permissions={[]} /> | ||
</RoleContext.Provider> | ||
</Router> | ||
</Provider> | ||
); | ||
|
||
await act(async () => { | ||
await flushPromises(); | ||
wrapper.update(); | ||
}); | ||
|
||
expect(wrapper.find('.mockClassName').text()).toMatchInlineSnapshot(`"Anon Ops"`); | ||
|
||
// simulate navigation - similar url but different pathname (id) | ||
history.push('/admin/users/2'); | ||
|
||
await act(async () => { | ||
await flushPromises(); | ||
wrapper.update(); | ||
}); | ||
|
||
// expect change to result of second fetch | ||
expect(wrapper.find('.mockClassName').text()).toMatchInlineSnapshot(`"Anon Central"`); | ||
|
||
wrapper.unmount(); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.