diegohaz / arc

React starter kit based on Atomic Design
https://arc.js.org
2.92k stars 292 forks source link

Protected routes? #223

Closed Geczy closed 7 years ago

Geczy commented 7 years ago

Can you please post an example of a protected route using redux social login in arc.js?

Geczy commented 7 years ago

rr4 https://github.com/ReactTraining/react-router/issues/4962

Geczy commented 7 years ago

Solved myself using

<Route path="/" component={RequireAuthentication(HomePage)} exact />

import React from 'react'
import { connect } from 'react-redux'
import { fromAuth } from 'store/selectors'

export default function RequireAuthentication(Component) {
  class AuthenticatedComponent extends React.Component {

    componentWillMount() {
      this.checkAuth()
    }

    componentWillReceiveProps(nextProps) {
      this.checkAuth()
    }

    checkAuth() {
      if (!this.props.isAuthenticated) {
        this.props.history.push('/login')
      }
    }

    render() {
      return (
        <div>
          {this.props.isAuthenticated === true
            ? <Component {...this.props} />
            : null
          }
        </div>
      )
    }
  }

  const mapStateToProps = (state) => ({
    isAuthenticated: fromAuth.getIdToken(state) !== null,
  })

  return connect(mapStateToProps)(AuthenticatedComponent)
}