iron-meteor / iron-router

A client and server side router designed specifically for Meteor.
MIT License
1.98k stars 412 forks source link

Router.go works with {{pathFor}} but not for direct url #1286

Open huntonas opened 9 years ago

huntonas commented 9 years ago

So I have an admin route that checks the user's roles and renders the template if they are an admin or I send them to the homepage using Router.go. If I am logged in as the admin and click on the link to the admin page, it works fine, but if I go to localhost:3000/admin, it redirects to the home page. Any ideas?

Router.route('/admin', {
name: 'admin',
controller: 'AdminController'
});

//Controllers
 AdminController = RouteController.extend({
onBeforeAction: function() {
    if(Roles.userIsInRole(Meteor.userId(), ['admin'])) {
        this.next();
    } else {
        Router.go('home');
    }
},
layoutTemplate: 'layout'
});
dcyou commented 9 years ago

maybe my code can help you:

/**
   * ensure user is logged in 
   * 
   */
  var OnBeforeActions  = {
    loginRequired: function (self, role) {
      var user;
      user = Meteor.user();
      if (!user) {
        self.render('signin');
        self.stop();
        return;
      }
      if(role !== undefined){
        if(!Roles.userIsInRole(user, [role])) {
          self.render('home');
          self.stop();
          return;
        }
      }
      self.next();
    } // end filters
  };

Router.map(function () {
        this.route('/', function () {
          this.render('home');
        });
        this.route('/home', function () {
          this.render('home');
        });
        this.route('/signin', function () {
          this.render('signin');
        });
        this.route('/admin', {
            onBeforeAction: function(pause) { OnBeforeActions.loginRequired(this, "myrolename"); },
...