Created
June 21, 2020 16:25
-
-
Save thinkclay/d2dc6e8efe6c9fe3ec9828342ace526c to your computer and use it in GitHub Desktop.
Restriction HOC
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
/** @jsx createElement **/ | |
import { createElement, FC, Fragment } from 'react' | |
import { connect } from 'react-redux' | |
import { RootState } from '@/models/app' | |
import { Auth, Roles, roleOptions } from '@/models/auth' | |
interface Props { | |
children: React.ReactNode | |
role?: Roles | |
roles?: Roles[] | |
} | |
interface Connected { | |
auth: Auth | |
} | |
const Restricted: FC<Props & Connected> = ({ children, role, roles, auth }) => { | |
if (!auth.isLoggedIn) return null | |
if (role && (!roleOptions[auth.role] || auth.role !== role)) return null | |
if (roles && !roles.includes(auth.role)) return null | |
return <Fragment>{children}</Fragment> | |
} | |
const mapState = (state: RootState): Connected => ({ | |
auth: state.auth | |
}) | |
export default connect(mapState)(Restricted) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment