Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect after user has just logged in or just logged out

It seems Deps.autorun is the way to go but Router.go doesn't seem to work within Deps.autorun.

like image 357
lleonard188 Avatar asked Apr 06 '14 21:04

lleonard188


2 Answers

Here is an example with three routes: index, signin and dashboard:

Router.configure({layoutTemplate: 'layout'});

Router.map(function() {
  this.route('index', {path: '/'});
  this.route('signin');
  this.route('dashboard');
});

var mustBeSignedIn = function(pause) {
  if (!(Meteor.user() || Meteor.loggingIn())) {
    Router.go('signin');
  } else {
    this.next();
  }
};

var goToDashboard = function(pause) {
  if (Meteor.user()) {
    Router.go('dashboard');
  } else {
    this.next();
  }
};

Router.onBeforeAction(mustBeSignedIn, {except: ['signin']});
Router.onBeforeAction(goToDashboard, {only: ['index']});

If a user is on the index page and she is logged in, she will automatically be routed to the dashboard page. On any page except for signin, if the user is not logged in she will be routed to the signin page. onBeforeAction is reactive so these rules will be enforced immediately if the user logs in or out.

Of course your routes will be different, but hopefully this example illustrates one way to make this work with iron-router.

Also see the using hooks section of the iron-router guide.

like image 52
David Weldon Avatar answered Oct 14 '22 19:10

David Weldon


A few things above seem to be outdated. Here's how I got things working at the present time:

Router.configure({
    layoutTemplate: 'Layout'
});

Router.map(function() {
    this.route('index', {path: '/'});
    this.route('login');
    this.route('home');
});

var mustBeSignedIn = function() {
    if (!(Meteor.user() || Meteor.loggingIn())) {
        Router.go('login');
    } else {
        this.next();
    }
};
var goHome = function() {
    if (Meteor.user()) {
        Router.go('home');
    } else {
        this.next();
    }
};

Router.onBeforeAction(mustBeSignedIn, {except: ['login']});
Router.onBeforeAction(goHome, {only: ['index', 'login']});
like image 39
Mark Shust at M.academy Avatar answered Oct 14 '22 21:10

Mark Shust at M.academy