How to redirect after user has just logged in or just logged out
Asked Answered
C

3

8

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

Claycomb answered 6/4, 2014 at 21:44 Comment(0)
E
17

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.

Excessive answered 6/4, 2014 at 21:57 Comment(2)
Using this approach, you need to create a empty template index. Right? Otherwise, Meteor throws an exception.Philibeg
@GiuseppePes I have not found that to be the case. However, in this example the index route isn't meaningful because you always get routed somewhere else, so using a blank or "loading" index template certainly wouldn't hurt.Excessive
M
7

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']});
Magisterial answered 8/4, 2015 at 20:8 Comment(0)
R
4
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( )

Retharethink answered 23/2, 2015 at 9:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.