asb_cloud_front/src/components/Private/PrivateRoute.tsx

34 lines
1.0 KiB
TypeScript
Raw Normal View History

import { Location } from 'history'
import { memo, ReactNode } from 'react'
import { Redirect, Route, RouteProps } from 'react-router-dom'
import { join } from 'path'
import { getUserId } from '@utils/storage'
import { isURLAvailable } from '@utils/permissions'
export type PrivateRouteProps = RouteProps & {
root?: string
path: string
children?: ReactNode
redirect?: (location?: Location<unknown>) => ReactNode
}
export const defaultRedirect = (location?: Location<unknown>) => (
<Redirect to={{ pathname: getUserId() ? '/access_denied' : '/login', state: { from: location?.pathname } }} />
)
export const PrivateRoute = memo<PrivateRouteProps>(({ root = '', path, component, children, redirect = defaultRedirect, ...other }) => {
const available = isURLAvailable(join(root, path))
return (
<Route
{...other}
path={path}
component={available ? component : undefined}
render={({ location }) => available ? children : redirect(location)}
/>
)
})
export default PrivateRoute