1
votes

I have a login form template

<template name="loginPage">...content</template>

and it is rendered when {{currentUser}} is not logged in. The problem is that currentUser is not available for about one second after the page refresh, even when the user is logged in. This causes login page appear for one second, even if the user has already logged in, this does not look good. Any idea how to delay rendering Login page, to make sure if {{currentUser}} is really logged in or not?

[solved]

html

{{#if loggingIn}}
  please wait, user is logging in
{{/if}}
{{#unless loggingIn}}
  {{#if currentUser}}
    user logged in
  {{/if}}
  {{#unless currentUser}}
    login form
  {{/unless}}
{{/unless}}

js

// create global {{#if loggingIn}}{{/if}} helper
Session.set("loggingIn", true);
var loginWait = 3; // seconds
var loginTimeout = setInterval(function(){
  loginWait = loginWait - 1;
  if(loginWait <= 0 || Meteor.user()){
    Session.set("loggingIn", false);
    clearInterval(loginTimeout);
  }
},1000);
Handlebars.registerHelper('loggingIn', function () {
  return Session.get("loggingIn");
});
2
Use routes to achieve this, and router hooks (onBeforeAction). So the router will check if the user is logged in, and if they're not, you do a this.redirect() to go to another route, or this.render() to render a template. See: iron-meteor.github.io/iron-router/#using-redirects - CaptSaltyJack

2 Answers

2
votes

Inside your template, you could do something like:

{{#if loggingIn}}
  HTML to be rendered before the user is determined
{{else}}
  {{#if currentUser}}  
    Html to be rendered if the user is logged in 
  {{else}}  
    Html to be rendered if the user is not logged in
  {{/if}}
{{/if}}

BTW, I do realize this doesn't provide the answer you requested, but I think it might be a better approach.

0
votes

The right place to do the user login check is in the onRendered method of the JS.

Template.loginPage.onRendered(function () {
  if(! Meteor.user()) {
    //route somewhere else
  }
});

You don't need to add in an indeterminate amount of time for loading, onRendered will be called before the template gets rendered, so you don't have to worry whether the time you allocate is enough.