Search code examples
javascriptreactjsoauth-2.0github-api

How to maintain isAuth and protect private routes?


I'm trying to implement authentication using Github oAuth API in React, I'm using React.CreateContext() to manage my AuthContext.

AuthContext.js

class AuthProvider extends React.Component {
  constructor(props) {
      super(props);
      if(typeof(sessionStorage.getItem('isAuth')) === 'undefined') {
        sessionStorage.setItem('isAuth',false);
      } 
      this.state = { isAuth: sessionStorage.getItem('isAuth') };
      this.login = this.login.bind(this)
      this.logout = this.logout.bind(this)
  }  

  login() {
   this.setState({isAuth: true});
  }

  logout() {
    this.setState({isAuth: false});
  }

When the user clicks on login button login method is fired, isAuth is set to true, and the user is redirected to github login page, but once the user returns to my app, the component is reinitialized and isAuth is set to false.

How can I handle this?


Solution

  • Reflect the state to sessionStorage:

    // AuthProvider
    componentDidUpdate(prevProps, prevState, snapshot) {
      if(prevState.isAuth !== this.state.isAuth)
        sessionStorage.setItem('isAuth', this.state.isAuth);
    }
    

    Note that data in sessionStorage is always a string, and anything that is not a string (e.g. booleans) will be converted to a string so you should:

    this.state = { isAuth: sessionStorage.getItem('isAuth') === "true" };