SHARE
TWEET

Untitled

a guest Jul 19th, 2019 72 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import React from 'react'
  2. import { withRouter } from 'react-router-dom'
  3. import { compose } from 'recompose'
  4.  
  5. import { withFirebase } from '../Firebase'
  6. import * as ROUTES from '../../constants/routes'
  7. import UserContext from './context'
  8.  
  9. // interface User {
  10. //   email?: string
  11. //   displayName?: string
  12. // }
  13. // type Condition = (user: User) => boolean
  14. // type Selector = (user: User) => object
  15.  
  16. interface Props {
  17.   firebase: firebase.app.App
  18.   history: any
  19. }
  20.  
  21. const withAuthorisation = (condition, selector) => (
  22.   Component: React.ComponentType<{}>,
  23. ) => {
  24.   const WithAuthorisation = ({ firebase, ...props }: Props) => {
  25.     React.useEffect(() => {
  26.       const unsub = firebase.auth().onAuthStateChanged(user => {
  27.         if (!condition(user)) {
  28.           props.history.push(ROUTES.SIGN_IN)
  29.         }
  30.       })
  31.       return unsub()
  32.     })
  33.  
  34.     return (
  35.       <UserContext.Consumer>
  36.         {user => {
  37.           // Guard condition technique
  38.           if (!condition(user)) {
  39.             return null
  40.           }
  41.  
  42.           let contextProps
  43.           if (selector) {
  44.             contextProps = selector(user) // function returns only the required props
  45.           }
  46.  
  47.           return <Component {...props} {...contextProps} />
  48.         }}
  49.       </UserContext.Consumer>
  50.     )
  51.   }
  52.  
  53.   return compose<Props, {}>(
  54.     withRouter,
  55.     withFirebase,
  56.   )(WithAuthorisation)
  57. }
  58.  
  59. export default withAuthorisation
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top