Question

On my meteor app I have a login system that sends you to the /dashboard path if you log in or sign up successfully. However, right now it is possible to get to the /dashboard path just by typing in localhost:3000/dashboard. How can I prevent this?

Was it helpful?

Solution

In addition to filtering the route with router hooks or custom actions, you may ensure that the template itself is displayed only to privileged users:

<template name="secret">
  {{#if admin}}
    ...
  {{/if}}
</template>

Handlebars.registerHelper('admin', function(options) {
  if(Meteor.user() && Meteor.user().admin) return options.fn(this);
  return options.inverse(this);
});

If you want to show a template to all registered users, you may use {{#if currentUser}} instead, in which case you don't need to register an additional helper.

OTHER TIPS

You can accomplish this using before hooks. Here is a simple example with three routes: index, signin, and dashboard:

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

  this.route('signin');

  this.route('dashboard');
});

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

Router.before(mustBeSignedIn, {except: ['signin']});

Before all routes except signin, we redirect the user back to the signin page unless they are logged in or in the process of logging in. You can see more examples in the using hooks section of the IR docs.

You need to check the state of the user before each route is run. If the user is not logged in (Meteor.userId() returns null) then redirect the user to the login route.

Router.before(function() {
  if (!Meteor.userId()) {
    this.redirect('userLoginRoute');
    this.stop();
  }
}, {
  except: ['userLoginRoute', 'userSignupRoute', 'userNewPasswordRoute']
});

I believe you can use custom actions for iron-router. You can check Meteor.userId() if it's null (not logged in) in the custom action, and redirect accordingly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top