2022-01-12 23:58:14 +05:00
|
|
|
import { FC, ReactNode } from 'react'
|
|
|
|
import { Location } from 'history'
|
|
|
|
import { Redirect, Route, RouteProps } from 'react-router-dom'
|
|
|
|
|
2021-12-29 17:48:10 +05:00
|
|
|
import { Role, Permission, hasPermission, isInRole } from '../../utils/permissions'
|
|
|
|
import { getUserToken } from '../../utils/storage'
|
2021-12-02 15:10:55 +05:00
|
|
|
|
2022-01-12 23:58:14 +05:00
|
|
|
export type PrivateRouteProps = RouteProps & {
|
2021-12-15 11:01:18 +05:00
|
|
|
roles: Role[] | Role
|
|
|
|
permission?: Permission
|
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>) => (
|
|
|
|
<Redirect to={{ pathname: '/login', state: { from: location } }} />
|
|
|
|
)
|
|
|
|
|
|
|
|
export const PrivateRoute: FC<PrivateRouteProps> = ({ permission, roles, component, children, redirect = defaultRedirect, ...other }) => {
|
2021-12-29 17:48:10 +05:00
|
|
|
const available = getUserToken() && (hasPermission(permission) && isInRole(roles))
|
2021-12-07 19:45:13 +05:00
|
|
|
|
|
|
|
return (
|
|
|
|
<Route {...other}
|
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
|
|
|
/>
|
|
|
|
)
|
2021-12-02 15:10:55 +05:00
|
|
|
}
|
2022-01-12 23:58:14 +05:00
|
|
|
|
|
|
|
export default PrivateRoute
|