2022-01-12 23:58:14 +05:00
|
|
|
import { Location } from 'history'
|
2022-02-07 14:58:38 +05:00
|
|
|
import { memo, ReactNode } from 'react'
|
2022-01-12 23:58:14 +05:00
|
|
|
import { Redirect, Route, RouteProps } from 'react-router-dom'
|
2022-02-07 14:58:38 +05:00
|
|
|
import { join } from 'path'
|
2022-01-12 23:58:14 +05:00
|
|
|
|
2022-02-07 17:36:19 +05:00
|
|
|
import { getUserId } from '@utils/storage'
|
2022-02-07 14:58:38 +05:00
|
|
|
import { isURLAvailable } from '@utils/permissions'
|
2021-12-02 15:10:55 +05:00
|
|
|
|
2022-01-12 23:58:14 +05:00
|
|
|
export type PrivateRouteProps = RouteProps & {
|
2022-04-29 18:38:49 +05:00
|
|
|
root?: string
|
2022-02-07 14:58:38 +05:00
|
|
|
path: string
|
2022-01-12 23:58:14 +05:00
|
|
|
children?: ReactNode
|
|
|
|
redirect?: (location?: Location<unknown>) => ReactNode
|
2021-12-02 15:10:55 +05:00
|
|
|
}
|
|
|
|
|
2022-01-12 23:58:14 +05:00
|
|
|
export const defaultRedirect = (location?: Location<unknown>) => (
|
2022-02-25 16:57:08 +05:00
|
|
|
<Redirect to={{ pathname: getUserId() ? '/access_denied' : '/login', state: { from: location?.pathname } }} />
|
2022-01-12 23:58:14 +05:00
|
|
|
)
|
|
|
|
|
2022-02-07 14:58:38 +05:00
|
|
|
export const PrivateRoute = memo<PrivateRouteProps>(({ root = '', path, component, children, redirect = defaultRedirect, ...other }) => {
|
|
|
|
const available = isURLAvailable(join(root, path))
|
2021-12-07 19:45:13 +05:00
|
|
|
|
|
|
|
return (
|
2022-02-07 14:58:38 +05:00
|
|
|
<Route
|
|
|
|
{...other}
|
|
|
|
path={path}
|
2021-12-15 11:01:18 +05:00
|
|
|
component={available ? component : undefined}
|
2022-01-12 23:58:14 +05:00
|
|
|
render={({ location }) => available ? children : redirect(location)}
|
2021-12-07 19:45:13 +05:00
|
|
|
/>
|
|
|
|
)
|
2022-02-07 14:58:38 +05:00
|
|
|
})
|
2022-01-12 23:58:14 +05:00
|
|
|
|
|
|
|
export default PrivateRoute
|