Skip to content

Instantly share code, notes, and snippets.

@maxguzenski
Last active August 29, 2015 14:07
Show Gist options
  • Save maxguzenski/69cff1e36f6dfb8318a1 to your computer and use it in GitHub Desktop.
Save maxguzenski/69cff1e36f6dfb8318a1 to your computer and use it in GitHub Desktop.
A alternative to build in primus authentification
var helper = require('../helper')
, crypto = require('crypto')
, logger = helper.logger;
/*
* I know that primus has a authotization feature, but it not works
* with some transformers (like sockjs, that not support querystring)
*
* This auth will send userid/username and a uniq token
* on all packages untill user be authentificated
*
* Another alternative is user cookies, but it only works
* if your main server (that authentificate user) and awesome-im are into same domain
*/
var generateAuthToken = function(userid) {
return crypto.createHash('sha256').update(helper.token+'&'+userid).digest('hex');
}
var validateAuthToken = function(userid, token) {
if (!userid || generateToken(userid) !== token) {
logger.error('invalid token "%s" for user "%s", should be "%s"', token, userid);
return false;
}
return true;
}
var PrimusAuth = {};
PrimusAuth.server = function(primus, options) {
primus.Spark.writable('auth', null);
//
// aiauth: {userid: <id>, username: <username>, token: <uniq token>}
//
primus.transform('incoming', function (p) {
if (!this.auth && p.data.aiauth) {
var aiauth = p.data.aiauth;
this.auth = (validateAuthToken(aiauth.userid, aiauth.token)) ?
p.data.aiauth : null;
}
if (!this.auth) {
logger.error('invalid user token', p.data, this.address.ip);
this.end(undefined, { reconnect: false });
return false;
}
delete p.data.aiauth;
if (p.data.aiinit) {
primus.emit('authorized', this, this.auth, p.data);
return false;
}
});
primus.reserved.events['authorized'] = 1;
}
PrimusAuth.client = function(primus, options) {
primus.authSent = false;
primus.transform('outgoing', function (p) {
if (!primus.authSent || p.data.aiinit) {
p.data.aiauth = options.aiauth;
}
if (p.data.aiinit) {
this.authSent = true;
}
});
primus.on('open', function() {
this.authSent = false;
this.write({aiinit: 1});
});
primus.on('reconnecting', function (opts) {
this.authSent = false;
});
primus.on('end', function () {
this.authSent = false;
});
}
module.exports = PrimusAuth;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment