Skip to content

Instantly share code, notes, and snippets.

@samim23
Created December 4, 2013 10:19
Show Gist options
  • Save samim23/7785333 to your computer and use it in GitHub Desktop.
Save samim23/7785333 to your computer and use it in GitHub Desktop.
meteor-user-status / user_status.coffee converted to javascript
var removeSession;
this.UserSessions = new Meteor.Collection(null);
this.UserStatus = new (Npm.require('events').EventEmitter)();
removeSession = function(userId, sessionId) {
UserSessions.remove({
_id: sessionId
});
UserStatus.emit("sessionLogout", userId, sessionId);
if (UserSessions.find({
userId: userId
}).count() === 0) {
return Meteor.users.update(userId, {
$set: {
'profile.online': false
}
});
}
};
Meteor.startup(function() {
return Meteor.users.update({}, {
$unset: {
"profile.online": null
}
}, {
multi: true
});
});
Meteor.publish(null, function() {
var existing, ipAddr, sessionId, userId, _ref;
userId = this._session.userId;
if (this._session.socket == null) {
return;
}
sessionId = this._session.id;
if (userId == null) {
existing = UserSessions.findOne({
_id: sessionId
});
if (existing == null) {
return;
}
removeSession(existing.userId, sessionId);
return;
}
ipAddr = ((_ref = this._session.socket.headers) != null ? _ref['x-forwarded-for'] : void 0) || this._session.socket.remoteAddress;
/*
TODO serious bug here when sessionId already exists in local collection
Happens when userId exists but session has already been recorded with the same sessionId
*/
if (UserSessions.findOne(sessionId)) {
UserSessions.update(sessionId, {
userId: userId,
ipAddr: ipAddr
});
} else {
UserSessions.insert({
_id: sessionId,
userId: userId,
ipAddr: ipAddr
});
}
UserStatus.emit("sessionLogin", userId, sessionId, ipAddr);
Meteor.users.update(userId, {
$set: {
'profile.online': true
}
});
this._session.socket.on("close", Meteor.bindEnvironment(function() {
return removeSession(userId, sessionId);
}, function(e) {
return Meteor._debug("Exception from connection close callback:", e);
}));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment