2021-12-02 15:10:55 +05:00
|
|
|
import React from 'react'
|
2021-12-15 11:01:18 +05:00
|
|
|
import { StaticContext } from 'react-router'
|
|
|
|
import { Route, Redirect, RouteComponentProps } 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
|
|
|
|
|
|
|
type PrivateRouteProps = {
|
2021-12-15 11:01:18 +05:00
|
|
|
roles: Role[] | Role
|
|
|
|
permission?: Permission
|
|
|
|
component?: React.ComponentType<any> | React.ComponentType<RouteComponentProps<any, StaticContext, unknown>>
|
|
|
|
children?: React.ReactNode
|
2021-12-07 19:45:13 +05:00
|
|
|
[other: string]: any
|
2021-12-02 15:10:55 +05:00
|
|
|
}
|
|
|
|
|
2021-12-15 11:01:18 +05:00
|
|
|
export const PrivateRoute: React.FC<PrivateRouteProps> = ({ permission, roles, component, children, ...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}
|
2021-12-07 19:45:13 +05:00
|
|
|
render={({ location }) => available ? children : (
|
|
|
|
<Redirect to={{ pathname: '/login', state: { from: location } }} />
|
|
|
|
)}
|
|
|
|
/>
|
|
|
|
)
|
2021-12-02 15:10:55 +05:00
|
|
|
}
|