lleonard188
lleonard188

Reputation: 87

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.

Upvotes: 8

Views: 7419

Answers (3)

David Weldon
David Weldon

Reputation: 64342

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.

Upvotes: 17

Mark Shust at M.academy
Mark Shust at M.academy

Reputation: 6429

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']});

Upvotes: 7

linxea
linxea

Reputation: 41

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();
  }
};

FYI, pause( ) is no supported now, just replace with this.next( )

Upvotes: 4

Related Questions