Last active
October 6, 2017 22:59
-
-
Save DavidLazic/fc32e2ab288cad2e16dbc2df7bd9c9ca to your computer and use it in GitHub Desktop.
React + Firebase - Persistent auth
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 React, { Component } from 'react'; | |
import PropTypes from 'prop-types'; | |
import firebase from 'firebase'; | |
import { browserHistory } from 'react-router'; | |
import { routeCodes } from 'routes'; | |
export default class App extends Component { | |
static propTypes = { | |
children: PropTypes.object.isRequired | |
} | |
constructor (props) { | |
super(props); | |
this.state = { user: null }; | |
} | |
componentDidMount () { | |
this.setAuthObserver(); | |
} | |
/** | |
* @description | |
* When AuthObserver invokes user change check if | |
* current route can be rendered and invoke redirect if necessary. | |
* | |
* @param {Object} props | |
* @param {Object} state | |
* @return {Function} | |
* @private | |
*/ | |
componentWillUpdate (props, state) { | |
return !this.isAuthorized(props.children.props.route.protected, state.user) && | |
browserHistory.push(routeCodes.ROOT); | |
} | |
/** | |
* @description | |
* Set AuthObserver for firebase user change. | |
* | |
* @return {Function} | |
* @private | |
*/ | |
setAuthObserver () { | |
return firebase.auth().onAuthStateChanged(user => this.setState({ user })); | |
} | |
/** | |
* @description | |
* Check if user is logged in or route is public. | |
* | |
* @param {Bool} protectedRoute | |
* @param {Object} user | |
* @return {Bool} | |
* @private | |
*/ | |
isAuthorized (protectedRoute, user) { | |
return Boolean(user) || !protectedRoute; | |
} | |
render () { | |
return ( | |
<section> | |
{ | |
React.Children.map(this.props.children, (child) => | |
React.cloneElement(child, { key: child.id })) || null | |
} | |
</section> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment