Logo
ManuelSchoebel

Login required for an url done right

Often times you have a route that should only be available for logged in users and the question is what is the ideal workflow to handle this in general and in more detail with meteor.

##The ideal workflow for restricted routes A guest (not logged in user) visits your website under this url:

http://www.your-domain.com/settings

Of course as a guest user he or she cannot access the settings page and one way to handle it would be to redirect him or her to the login page. This is the easy way but I swear the most best way to handle this is so easy in meteor, that you should not do it this way.

The best way to handle this situation would be:

1. User opens http://www.your-domain.com/settings
2. The login template is rendered
3. User types in login credentials and submits
4. The settings template is rendered

This way the user does not have to navigate to the estimated location after he logged in.

##The implementation of the ideal workflow for restricted routes At first we do have the Iron Router added to our project, of course (Iron Router Tutorial here).

Next we create a global onBeforeAction for our Iron Router to check if the user is logged in or not.

    var OnBeforeActions;
 
    OnBeforeActions = {
        loginRequired: function(pause) {
          if (!Meteor.userId()) {
            this.render('login');
            return pause();
          }
        }
    };
 
    Router.onBeforeAction(OnBeforeActions.loginRequired, {
        only: ['settings', 'anotherPriveRoute']
    });

In the 'loginRequired' before hook we check if the user is logged in and if not we render the login template and also do not forget to call 'pause'.

We also specify an 'only' option for the global before hook so we do not check if the user is logged in for any route but only for those we specify.

No we already render the login template if a user opens the '/settings' route but is not logged in. Now we have one last thing to do, call the login function and also check if the user comes from the login route itself or from another route.

    Template.login.events({
      'submit form': function(evt, tpl) {
 
        ... // get the form fields etc.
 
        Meteor.loginWithPassword(data.email.toLowerCase(), data.password, function(err) {
          if (err) {
            ... // handle err
            return;
          }
          if (Router.current().route.name === 'login') {
            // if we are on the login route, we want to redirect the user
            return Router.go('home');
          }
        });
      }
    });

If the second 'if' returns false, we are not on the login route and there for we finally want to render the settings template and gues what: This will happen due to the reactivity automatically.

##Conclusion You need one global before hook and one additional if clause and you get really nice usability for restricted routes.

©️ 2024 Digitale Kumpel GmbH. All rights reserved.