Week 11: Atlas multipass library

So this week I have written a library which encodes and decodes a multipass token and it is specific to the atlas and can be hacked to our requirements.

encode() method, encode the user details and generate a token using the keys and decode() method, decode the token to a JSON object which can be used to log the user.

var crypto = require('crypto');

// Block size
var BLOCK_SIZE = 16;

// Create an return a Multipass API
var api = module.exports = function(apiKey, siteKey) {
if (!(this instanceof api)) return new api(apiKey, siteKey);
if (!(typeof apiKey == 'string' && apiKey.length > 0)) throw new Error('Invalid API key');
if (!(typeof siteKey == 'string' && siteKey.length > 0)) throw new Error('Invalid site key');
this._key = crypto.createHash('sha1').update(apiKey + siteKey).digest('binary').substring(0, BLOCK_SIZE);
this._iv = new Buffer('OpenSSL for Node', 'binary');
return this;
};

// Encode a Multipass token
api.prototype.encode = function(obj) {
if (!obj) return;
// Create a buffer
var data = new Buffer(typeof obj == 'string' ? obj : JSON.stringify(obj), 'utf8');
  
// Encrypt with AES
var cipher = crypto.createCipheriv('aes-128-cbc', this._key, this._iv),
token = cipher.update(data, 'binary', 'binary') + cipher.final('binary');

//prepend the iv
token = new Buffer(token, 'binary');
token = token.toString('base64');

token = token.replace(/\n/g, '') // Remove newlines
.replace(/\=+$/, '') // Remove trailing =
.replace(/\+/g, '-') // Replace + with -
.replace(/\//g, '_'); // Replace / with _
return token;
};

// Decode a Multipass token
api.prototype.decode = function(token) {
if (typeof token != 'string') return;
token = token.replace(/_/g, '/') // Replace _ with /
.replace(/\-/g, '+'); // Replace - with +
// Decrypt with AES
var cipher = crypto.createDecipheriv('aes-128-cbc', this._key, this._iv.toString('binary')),
data = cipher.update(token, 'base64', 'binary') + cipher.final('binary');
// Create a buffer
data = new Buffer(data);
try {
return JSON.parse(data.toString('utf8'));
} catch (e) {};
};

Time is flying and I have to gear up to meet the expectations:)

NPM Package: https://github.com/ShekharReddy4/atlas-node-multipass

To install the package

npm i atlas-node-multipass

Regards

Shekhar 🙂

Advertisements

One thought on “Week 11: Atlas multipass library

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s