Skip to content

Instantly share code, notes, and snippets.

@samim23
Created December 4, 2013 10:19

Revisions

  1. samim23 created this gist Dec 4, 2013.
    79 changes: 79 additions & 0 deletions gistfile1.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,79 @@
    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);
    }));
    });