1

I am trying to set up an Admin page that is only accessible to people with a user "level" greater than 2. I am using MobX and React-Router. The problem is likely based on the fact that I don't know how to connect to the MobX store properly. I am importing a function, isAdmin, that is located in a seperate file from routes.js. The function looks like:

export const isAdmin = (nextState, replace) => {
    const user = this.context.store.auth.user;
    if (user.level < 2 || !user) {
        replace({
            pathname: '/',
        });
    }
};

This is loosely based on the final example from the gitHub page for react-router located here.

Thanks for any help!

dkimot
  • 1,648
  • 1
  • 12
  • 24

1 Answers1

5

This link explains what Context object is and where to use it. `isAdmin' function will need access to your Store class to get the user level.

Create an AuthStore (/stores/auth.js) -

import { observable, computed } from 'mobx';
import singleton from 'singleton';

export default class Auth extends singleton {
  @observable user = null;

  @computed get isLoggedIn() {
    return !!this.user;
  }

  login(username, password) {
    return post('/api/auth/login', {
      username, password
    })
    .then((res) => {
      this.user = res.data.user;
      return res;
    });
  }

  logout() {
    Storage.remove('token');
    return get('/api/auth/logout');
  }
}

In your routes file, you can import the AuthStore and use it like this

import React from 'react';
import { Route, IndexRoute } from 'react-router';
import Auth from './stores/Auth'; // note: we can use the same store here..

function authRequired(nextState, replace) {
  if (!Auth.isLoggedIn) {
    replace('/login');
  }
}

export default (
  <Route name="root" path="/" component={App}>
    <Route name="login" path="login" component={Login} />
    <Route name="admin" path="admin" onEnter={authRequired} component={Admin}>
      <IndexRoute name="dashboard" component={Dashboard} />
    </Route>
  </Route>
);

This stackoverflow question should give you more info

Community
  • 1
  • 1
Arjun Hariharan
  • 300
  • 2
  • 9