Login and feed subscription example in Node.js

This example displays how to establish a session and login to the public feed.
It runs with http://nodejs.org and needs 2 modules which are easily acquired with npm:

npm install ursa restler
var util = require('util'),
  fs = require('fs'),
  rest = require('restler'),
  ursa = require('ursa'),
  tls = require('tls');

function login(user, pass, fn) {
  var auth = encryptLogin(user, pass, 'NEXTAPI_TEST_public.pem');
  var opts = {
    headers: {
      'Accept': 'application/json'
    }
  };

  // post JSON
  var jsonData = {
    service: 'NEXTAPI',
    auth: auth
  };
  rest.postJson('https://api.test.nordnet.se/next/2/login', jsonData, opts).on('success', function (data, response) {
    // handle response
    util.puts('response: ' + util.inspect(data));
    fn(data, null);

  }).on('fail', function (data, resp) {
    util.log('fail: ' + util.inspect(data));
    fn(null, data);
  });
}

function subscribePrice(market, ident, sessionData) {
  var client = tls.connect(sessionData.private_feed.port, sessionData.public_feed.hostname, function () {
    client.setNoDelay(true);
    client.setTimeout(10000);

    util.log('Connected to feed');

    client.write(
    formatFeedCmd('login', {
      session_key: sessionData.session_key,
      service: 'NEXTAPI'
    }),

    function () {
      client.write(formatFeedCmd('subscribe', {
        t: 'price',
        i: ident,
        m: market
      }));
    });

  }).on('data', function (d) {
    util.log(d);
  });
}

function formatFeedCmd(cmd, args) {
  return JSON.stringify({
    cmd: cmd,
    args: args
  }) + '\n';
}

function encryptLogin(user, pass, keyfile) {
  var rsaPublic = fs.readFileSync(keyfile, 'ascii');
  var key = ursa.createPublicKey(rsaPublic, 'utf8');

  if (!key) {
    console.log('KEY error');
  }

  var auth = new Buffer(user).toString('base64');
  auth += ':';
  auth += new Buffer(pass).toString('base64');
  auth += ':';
  auth += new Buffer('' + new Date().getTime()).toString('base64');
  return key.encrypt(auth, 'utf8', 'base64', ursa.RSA_PKCS1_PADDING);
}

login('USER', 'PASS', function (sessionData, error) {
  if (!error) {
    subscribePrice(30, '1869', sessionData);
  }
});