Search code examples
meteoriron-router

Meteor Redirect after login and logout


I have a Meteor app and I would like to have users to go to a dashboard (called documentsIndex) page after signin and after signout, redirect them to the frontpage of the webapplication. Right now I have the following:

Iron.Router.hooks.requireLogin = function () {
  if (! Meteor.user()) {
    if (Meteor.loggingIn()) {
      this.render('this.loadingTemplate');
    } else {
      this.render('accessDenied');
    }
  } else {
    this.next();
  }
};

Iron.Router.hooks.goToDashboard = function () {
  if (Meteor.user()) {
    Router.go('documentsIndex');
    this.next();
  } else {
    this.next();
  }
};

Iron.Router.hooks.goToFrontpage= function () {
  if (!Meteor.user()) {
    Router.go('frontpage');
    this.next();
  } else {
    this.next();
  }
};

Router.onBeforeAction('goToDashboard', {except: ['documentNew', 'documentIndex', 'documentShow', 'documentEdit']});
Router.onBeforeAction('goToFrontpage', {except: ['frontpage', 'about']});
Router.onBeforeAction('requireLogin', {except: ['frontpage', 'about']});
Router.onBeforeAction('dataNotFound', {only: ['documentIndex','documentNew', 'documentIndex', 'documentShow', 'documentEdit']});

This works, so when a user is signing in, he is always redirected to the DocumentsIndex route and he can navigate the backend. When a user is signed out, he is redirected to the frontpage and can browse the frontend.

  1. This gets difficult to manage when my webapp will grow in the future (especially with the only and except statements in the onBeforeAction is will become confusing and error prone). So ideally I would like to combine everything in the requireLogin hook.
  2. Later on I will work with roles (alanning:roles). I will have an 'admin' role, a registered 'customer' role and then just a normal visitor that can only access the frontpage. Any ideas of using this role in the Router hooks? An example would be more than appreciated.

Note: Im using accounts-password package


Solution

  • You could use the Accounts.onLogin(function () {}); hook from Meteor instead of iron:router (doc). In this hook you can access Meteor.user() to check their role and change the action as needed.

    Similarly, you can use the callback function in Meteor.logout() to handle any logic on logout as shown below:

    Meteor.logout(function(err) {
      // logout logic here
    });
    

    If you want this logout hook to fire when you logout with {{> loginButtons}} on a certain template ie: adminTemplate then use the code below. I have not tested this code snippet so minor adjustments may be needed.

    Template.adminTemplate.events({
        'click #login-buttons-logout': function (event) {
            //add your custom logic on top of this
           //the default behaviour should still happen from meteor
        }
    });