Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React from 'react'
- import { withRouter } from 'react-router-dom'
- import { compose } from 'recompose'
- import { withFirebase } from '../Firebase'
- import * as ROUTES from '../../constants/routes'
- import UserContext from './context'
- // interface User {
- // email?: string
- // displayName?: string
- // }
- // type Condition = (user: User) => boolean
- // type Selector = (user: User) => object
- interface Props {
- firebase: firebase.app.App
- history: any
- }
- const withAuthorisation = (condition, selector) => (
- Component: React.ComponentType<{}>,
- ) => {
- const WithAuthorisation = ({ firebase, ...props }: Props) => {
- React.useEffect(() => {
- const unsub = firebase.auth().onAuthStateChanged(user => {
- if (!condition(user)) {
- props.history.push(ROUTES.SIGN_IN)
- }
- })
- return unsub()
- })
- return (
- <UserContext.Consumer>
- {user => {
- // Guard condition technique
- if (!condition(user)) {
- return null
- }
- let contextProps
- if (selector) {
- contextProps = selector(user) // function returns only the required props
- }
- return <Component {...props} {...contextProps} />
- }}
- </UserContext.Consumer>
- )
- }
- return compose<Props, {}>(
- withRouter,
- withFirebase,
- )(WithAuthorisation)
- }
- export default withAuthorisation
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement