Created
November 16, 2018 08:55
-
-
Save srph/8ca67aa0c24487c1d8c8e2c40f4fc8f6 to your computer and use it in GitHub Desktop.
Reach Router: Advanced permissions proof of concept
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { TAuthContainerUserData } from '@app/containers/AuthContainer' | |
export default { | |
guard(user: TAuthContainerUserData) { | |
return user == null | |
}, | |
redirectTo: '/login' | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { TAuthContainerUserData } from '@app/containers/AuthContainer' | |
export default { | |
guard(user: TAuthContainerUserData): boolean { | |
return user != null | |
}, | |
redirectTo: '/' | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as React from 'react' | |
import { Subscribe as UnstatedSubscribe } from 'unstated' | |
import { AuthContainer } from '@app/containers' | |
import { TAuthContainerUserData } from '@app/containers/AuthContainer' | |
import { Redirect } from '@reach/router' | |
import authOnly from './permission-auth-only' | |
import guestOnly from './permission-auth-only' | |
interface IPermissionFunction { | |
guard: (user: TAuthContainerUserData) => boolean | |
redirectTo: string | |
} | |
interface IPermissionExternalProps { | |
permission: IPermissionFunction | |
children: any | |
} | |
interface IPermissionInternalProps extends IPermissionExternalProps { | |
user: TAuthContainerUserData | |
} | |
class Permission extends React.Component<IPermissionInternalProps> { | |
render() { | |
const {children, permission, user, ...props} = this.props | |
if (!permission.guard(user)) { | |
return <Redirect to={permission.redirectTo} /> | |
} | |
return React.cloneElement(children, props) | |
} | |
} | |
class WrappedPermission extends React.Component<IPermissionExternalProps> { | |
static authOnly = authOnly | |
static guestOnly = guestOnly | |
render() { | |
const props = this.props | |
return ( | |
<UnstatedSubscribe to={[AuthContainer]}> | |
{(auth: AuthContainer) => ( | |
<Permission {...props} user={auth.state.data} /> | |
)} | |
</UnstatedSubscribe> | |
) | |
} | |
} | |
export default WrappedPermission |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment