简体   繁体   中英

Meteor: How to detect if users authenticated

In my app I use accounts-github . Works perfect, but I have one problem.

In one of my templates I do

Template.bar.rendered = function () {
    if (Meteor.user()) {
        // setup stuff
    }
}

The problem is that if the user initially is not logged in this code is not executed (thats ok). But when the user authenticates this code is not executed again. So the question is how can I listen for this change inside a template (doesn't have to be in inside the rendered function!)?

You could use Deps.autorun . ( http://docs.meteor.com/#deps_autorun )

Usually Deps.autorun would run for your whole Meteor app. If you want to make it so that it only runs per template you would need to create and stop it in the rendered and destroyed template callbacks

eg

var loginRun;

Template.bar.rendered = function() {
    loginRun = Deps.autorun(function() {
        if(Meteor.user()) {
            //Stuff to run when logged in
        }
    });
}

Template.bar.destroyed = function() {
    loginRun.stop();
}

If you don't need it to run per template (need it to run just once for you app on any template, then you can use the Deps.autorun on its own, anywhere in your client side code.

Meteor.user() is reactive, it would ensure that the Deps.autorun callback runs again when it changes, so you could theoretically use it to do things when the user logs in or out.

Other alternatives is there is a package on atmosphere that provides login and logout hooks, though they basically would use the Deps.autorun like above to work anyway. See https://github.com/BenjaminRH/meteor-event-hooks

My solution for similar problem was to

  1. Attach an event to template where the login happens
  2. Re-render template if login is succesful so the Template.bar.rendered is called

Eg

Template.bar.events({ 
   'click .loginButton' : function() {
    if( Meteor.call.Login( username, pw ) )
    {
        $('#bar').html( Meteor.render( Template.bar ));
        //jQuery is optional
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM