forked from ddrilling/asb_cloud_front
31 lines
1.0 KiB
TypeScript
31 lines
1.0 KiB
TypeScript
import { FC, ReactNode } from 'react'
|
|
import { Location } from 'history'
|
|
import { Redirect, Route, RouteProps } from 'react-router-dom'
|
|
|
|
import { Role, Permission, hasPermission, isInRole } from '../../utils/permissions'
|
|
import { getUserToken } from '../../utils/storage'
|
|
|
|
export type PrivateRouteProps = RouteProps & {
|
|
roles: Role[] | Role
|
|
permission?: Permission
|
|
children?: ReactNode
|
|
redirect?: (location?: Location<unknown>) => ReactNode
|
|
}
|
|
|
|
export const defaultRedirect = (location?: Location<unknown>) => (
|
|
<Redirect to={{ pathname: '/login', state: { from: location } }} />
|
|
)
|
|
|
|
export const PrivateRoute: FC<PrivateRouteProps> = ({ permission, roles, component, children, redirect = defaultRedirect, ...other }) => {
|
|
const available = getUserToken() && (hasPermission(permission) && isInRole(roles))
|
|
|
|
return (
|
|
<Route {...other}
|
|
component={available ? component : undefined}
|
|
render={({ location }) => available ? children : redirect(location)}
|
|
/>
|
|
)
|
|
}
|
|
|
|
export default PrivateRoute
|