简体   繁体   中英

Picking up meteor.js user logout

Is there any way to pick up when a user logs out of the website? I need to do some clean up when they do so. Using the built-in meteor.js user accounts.

I'll be doing some validation using it, so I need a solution that cannot be trigger on behalf of other users on the client side - preferably something completely server side.

You may use Deps.autorun to setup a custom handler observing Meteor.userId() reactive variable changes.

Meteor.userId() (and Meteor.user()) are reactive variables returning respectively the currently logged in userId (null if none) and the corresponding user document (record) in the Meteor.users collection.

As a consequence one can track signing in/out of a Meteor application by reacting to the modification of those reactive data sources.

client/main.js :

var lastUser=null;

Meteor.startup(function(){
    Deps.autorun(function(){
        var userId=Meteor.userId();
        if(userId){
            console.log(userId+" connected");
            // do something with Meteor.user()
        }
        else if(lastUser){
            console.log(lastUser._id+" disconnected");
            // can't use Meteor.user() anymore
            // do something with lastUser (read-only !)
            Meteor.call("userDisconnected",lastUser._id);
        }
        lastUser=Meteor.user();
    });
});

In this code sample, I'm setting up a source file local variable (lastUser) to keep track of the last user that was logged in the application. Then in Meteor.startup, I use Deps.autorun to setup a reactive context (code that will get re-executed whenever one of the reactive data sources accessed is modified). This reactive context tracks Meteor.userId() variation and reacts accordingly.

In the deconnection code, you can't use Meteor.user() but if you want to access the last user document you can use the lastUser variable. You can call a server method with the lastUser._id as argument if you want to modify the document after logging out.

server/server.js

Meteor.methods({
    userDisconnected:function(userId){
        check(userId,String);
        var user=Meteor.users.findOne(userId);
        // do something with user (read-write)
    }
});

Be aware though that malicious clients can call this server method with anyone userId, so you shouldn't do anything critical unless you setup some verification code.

Use the user-status package that I've created: https://github.com/mizzao/meteor-user-status . This is completely server-side.

See the docs for usage, but you can attach an event handler to a session logout:

UserStatus.events.on "connectionLogout", (fields) ->
  console.log(fields.userId + " with connection " + fields.connectionId + " logged out")

Note that a user can be logged in from different places at once with multiple sessions. This smart package detects all of them as well as whether the user is online at all. For more information or to implement your own method, check out the code.

Currently the package doesn't distinguish between browser window closes and logouts, and treats them as the same.

We had a similar, though not exact requirement. We wanted to do a bit of clean up on the client when they signed out. We did it by hijacking Meteor.logout :

if (Meteor.isClient) {
  var _logout = Meteor.logout;
  Meteor.logout = function customLogout() {
    // Do your thing here
    _logout.apply(Meteor, arguments);
  }
}

The answer provided by @saimeunt looks about right, but it is a bit fluffy for what I needed. Instead I went with a very simple approach like this:

if (Meteor.isClient) {
    Deps.autorun(function () {
        if(!Meteor.userId())
        {
            Session.set('store', null);
        }
    });
}

This is however triggered during a page load if the user has not yet logged in, which might be undesirable. So you could go with something like this instead:

if (Meteor.isClient) {
    var userWasLoggedIn = false;
    Deps.autorun(function (c) {
        if(!Meteor.userId())
        {
            if(userWasLoggedIn)
            {
                console.log('Clean up');
                Session.set('store', null);
            }
        }
        else
        {
            userWasLoggedIn = true;
        }
    });
}

None of the solutions worked for me, since they all suffered from the problem of not being able to distinguish between manual logout by the user vs. browser page reload/close.

I'm now going with a hack, but at least it works (as long as you don't provide any other means of logging out than the default accounts-ui buttons):

Template._loginButtons.events({
    'click #login-buttons-logout': function(ev) {
        console.log("manual log out");
        // do stuff
    }
});

您可以使用以下Meteor.logout - http://docs.meteor.com/#meteor_logout

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