Ad

How To Implement Login-dependent Paths With React-router, When The Login-status Is In The Component-state?

I'm trying to implement the auth-flow example from the react-router-repo, but I'm running into issues for my usecase, which I don't grok as a ReactJS beginner.

My login-status is based on the existence of a CSRF-cookie, so I have a method in my App which retrieves the CSRF-cookie and saves its value in state:

@autobind
class App extends React.Component {
  constructor() {
    super();

    this.state = {
      csrfToken : '',
      log : {}
    }
  }

setCSRFToken() {
  this.state = { csrfToken : cookie.load('csrf') };
  this.setState({ csrfToken : this.state.csrfToken });
}

loggedIn() {
  return !!this.state.csrfToken
}

Since I only want to view my components when I'm logged in, I try to change the path in my routes according to loggedIn() with onEnter={requireAuth}:

function requireAuth(nextState, replace) {
  if (!App.loggedIn()) {
    console.log('No csrfToken found, asking for login')
    replace({
      pathname: '/login',
      state: {nextPathname: nextState.location.pathname }
    })
  }
}

render((
  <Router history={hashHistory}>
    <Route path="/" component={App} onEnter={requireAuth}>
      <IndexRoute component={Home}/>
      <Route path="/hello" component={Hello}/>
    </Route>
  </Router>

), document.querySelector('#main'))

App.loggedIn() is not working though, as it's not a public function. According to this answer, a public function in ReactJS has no access to the internal state, as intended by React's architecture, so it would not help to implement it with static.

I could probably go ahead and save the login-status in local storage, but I wonder if there's a different approach to solve this in ReactJS.

Ad

Answer

I'm setting login state in Store (like Flux suggests) and in routes:

const UserStore = require("./stores/UserStore.js");

let is_user_logged_in = !!UserStore.getToken();

UserStore.addChangeListener(() => {
    is_user_logged_in = !!UserStore.getToken();
});

function requireAuth(nextState, replaceState) {
    if (!is_user_logged_in) {
        replaceState({nextPathname: 'login'}, '');
    }
}

const routes = (
    <Route path="/" component={Layout}>
        <IndexRoute component={Home}/>
        <Route path="login" component={Login}/>
        <Route path="secret" component={Secret} onEnter={requireAuth}/>
        <Route path="*" component={NotFound}/>
    </Route>
);

module.exports = routes;

works great, built several apps with this :)

UserStore.js:

"use strict";
const AppDispatcher = require('./../dispatchers/AppDispatcher.js');
const EventEmitter = require('eventemitter3');
const assign = require('object-assign');
const store = require('store');
const Api = require('./../helpers/Api.js');
const UserActions = require('./../actions/UserActions.js');
import { browserHistory } from 'react-router';

const UserStore = assign({}, EventEmitter.prototype, {

    token: null,
    error: null,

    setError: function ({error}) {
        this.error = error;
    },

    getError: function () {
        return this.error;
    },

    setToken: function ({token}) {
        this.token = token;

        if (token !== null) {
            store.set('token', token);
        } else {
            store.remove('token');
        }
    },

    getToken: function () {
        return this.token;
    },

    emitChange: function () {
        this.emit('USER_CHANGE');
    },

    addChangeListener: function (cb) {
        this.on('USER_CHANGE', cb);
    },

    removeChangeListener: function (cb) {
        this.removeListener('USER_CHANGE', cb);
    },

});

AppDispatcher.register(function (action) {

    switch (action.actionType) {
        case 'user_login':
            Api.login({
                username: action.data.username,
                password: action.data.password,
                cb: function ({error, response}) {
                    if (error !== null) {
                        console.log('#dfd4sf424');
                        console.log(error);
                        UserActions.logout();
                    } else {
                        if (response['success'] === false) {
                            UserStore.setError({error: response['error']});
                            UserStore.emitChange();
                        } else {
                            UserStore.setError({error: null});
                            UserStore.setToken({token: response['auth-token']});
                            UserStore.emitChange();
                        }
                    }
                }
            });
            break;
        case 'user_logout':
            UserStore.setToken({token: null});
            UserStore.setError({error: null});
            UserStore.emitChange();
            break;
        case 'user_auto_login':
            UserStore.setToken({token: action.data.token});
            UserStore.setError({error: null});
            UserStore.emitChange();
            break;
    }
});

module.exports = UserStore;
Ad
source: stackoverflow.com
Ad