Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if Logged in - React Router App ES6

I am writing a React.js application (v15.3) using react-router (v2.8.1) and ES6 syntax. I cannot get the router code to intercept all transitions between pages to check if the user needs to login first.

My top level render method is very simple (the app is trivial as well):

 render()
   {
      return (
         <Router history={hashHistory}>
            <Route path="/" component={AppMain}>
               <Route path="login" component={Login}/>
               <Route path="logout" component={Logout}/>
               <Route path="subject" component={SubjectPanel}/>
               <Route path="all" component={NotesPanel}/>
            </Route>
         </Router>
      );
   }

All the samples on the web use ES5 code or older versions of react-router (older than version 2), and my various attempts with mixins (deprecated) and willTransitionTo (never gets called) have failed.

How can I set up a global 'interceptor function' to force users to authenticate before landing on the page they request?

like image 519
NullPumpkinException Avatar asked Oct 15 '16 05:10

NullPumpkinException


People also ask

How do I know if I am using ES6?

import is one of the major features of ES6, so if you have import statements and classes in your code, you are using ES6. if not, an older version.

How do you know if a user is logged in react?

Now whenever we want to know if the user is authed , login , or logout , we can use the useAuth Hook. There are lots of different ways the useAuth Hook could work. Perhaps it makes an HTTP Fetch request to an API endpoint to validate a cookie. Or maybe it decodes a JWT token stored in the browser's localstorage.

How check current router react?

Use the useLocation() hook to get the current route with React Router, e.g. const location = useLocation() . The hook returns the current location object. For example, you can access the pathname as location. pathname .

Does react support ES6?

React uses ES6, and you should be familiar with some of the new features like: Classes. Arrow Functions. Variables (let, const, var)


2 Answers

Every route has an onEnter hook which is called before the route transition happens. Handle the onEnter hook with a custom requireAuth function.

<Route path="/search" component={Search} onEnter={requireAuth} /> 

A sample requireAuth is shown below. If the user is authenticated, transition via next(). Else replace the pathname with /login and transition via next(). The login is also passed the current pathname so that after login completes, the user is redirected to the path originally requested for.

function requireAuth(nextState, replace, next) {   if (!authenticated) {     replace({       pathname: "/login",       state: {nextPathname: nextState.location.pathname}     });   }   next(); } 
like image 57
vijayst Avatar answered Sep 23 '22 07:09

vijayst


In v4 you just create a route component that checks if uses is authenticated and return the next components and of course next component can be other routes.

import React, { Component } from 'react';
import PropTypes from 'prop-types';

import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { Route, Redirect } from 'react-router-dom';

import AuthMiddleware from 'modules/middlewares/AuthMiddleware';

class PrivateRoute extends Component {
  static propTypes = {
    component: PropTypes.func.isRequired,
    isAuthenticated: PropTypes.bool,
    isLoggedIn: PropTypes.func.isRequired,
    isError: PropTypes.bool.isRequired
  };

  static defaultProps = {
    isAuthenticated: false
  };

  constructor(props) {
    super(props);
    if (!props.isAuthenticated) {
      setTimeout(() => {
        props.isLoggedIn();
      }, 5);
    }
  }

  componentWillMount() {
    if (this.props.isAuthenticated) {
      console.log('authenticated');
    } else {
      console.log('not authenticated');
    }
  }
  componentWillUnmount() {}

  render() {
    const { isAuthenticated, component, isError, ...rest } = this.props;
    if (isAuthenticated !== null) {
      return (
        <Route
          {...rest}
          render={props => (
            isAuthenticated ? (
              React.createElement(component, props)
            ) : (
              <Redirect
                to={{
                  pathname: isError ? '/login' : '/welcome',
                  state: { from: props.location }
                }}
              />
            )
          )}
        />
      );
    } return null;
  }

}

const mapStateToProps = (state) => {
  return {
    isAuthenticated: state.auth.isAuthenticated,
    isError: state.auth.isError
  };
};

const mapDispatchToProps = (dispatch) => {
  return bindActionCreators({
    isLoggedIn: () => AuthMiddleware.isLoggedIn()
  }, dispatch);
};

export default connect(mapStateToProps, mapDispatchToProps)(PrivateRoute);
like image 29
xtabbas Avatar answered Sep 20 '22 07:09

xtabbas