Search code examples
javascriptmeteoriron-router

Iron-Router Login and Register best practice


I would be grateful for some feedback on my Iron-Router logged out redirection code.

I intend to only allow logged in users to access routes other than login or register and to redirect others to login with error code.

// routes.js with Router.beforeAction
if (!Meteor.userId()) {
  // Get current route
  var currentRoute = Router.current().route.getName();
    // if the current user is not trying to login or register send to login with error
  if (currentRoute = 'register'){
      this.layout('login');
      this.render('registerview');
    } else if (currentRoute = 'login') {
      this.layout('login');
      this.render('loginview');
    } else {
      Session.set("errorMessage", "You need to log in to access this page.");
      this.redirect('/login');
    }
} else {
    // otherwise don't hold up the rest of hooks or our route/action function
    // from running
    this.next();
}

This works but i would appreciate some feedback on efficiency and good code.

Also my routes.js file is in /client , I know that the login logic should be sent to server methods but is there any security concern for the route file?


Solution

  • In terms of logic, I could say that it is ok. But I would do it in another way: I usually do all the tests in the onBeforeAction() hook. I do the validations using functions and if all validations pass, I call this.next(). If there is an error the router redirects (using Router.go()) to a route which an unregistered user could see. Concerning the folder, I place the router. js in the root/lib folder. Example :

    Router.onBeforeAction(mustBeSignedIn, {only:  [the templates you want to check]});