Search code examples
meteoriron-router

Meteor.user() login issue


I am testing a restrict login function with router code below

var requireLogin = function() { 
  if (! Meteor.user()) {
   console.log("user not logged");
   this.next()
 } else {
   console.log("user logged");
   this.next()
 }
}

Router.onBeforeAction(requireLogin, {except: ['home','login','about']});

when I try to enter restricted area like userprofile it ask me to log in and print "user not logged" and after I successfully log in and try to access that area again. it printing both code starts with "user not logged" and then "user logged"

I want to know how to avoid this to happen? since some page become glitched when this happened.

I want it to only print "user logged" if I enter a restricted area page.

Any help would be appreciated.


Solution

  • You need to integrate Meteor.loggingIn() somewhere in your requireLogin function. Because, what's happening is that Meteor is still loading the user system and for every route change, it re-authenticates the user based on current session, if it exists.

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

    You will notice that it uses this.loadingTemplate. To keep this, you must also configure your routes to have a loading template. e.g.:

    Router.configure({
      loadingTemplate: 'loading'
    });
    

    or you could just simply swap that out with this.render('loading'); where 'loading' is the template name of your 'Now loading' yield/page.