Storing Tokens in JSON file

To start with I had the Trademe tokens and secrets in the code to get up and going.

var oauth = new OAuth.OAuth(
    'some token',
    ....
);

A better way is to store them in a file and then read them on startup of script. In this instance they are stores in JSON format.

vim trademe/secrets/secrets.json
{
   "request_token": "foo",
   "access_token": "bar",
   "consumer_key": "foo",
   "consumer_secret": "bar"
}

I have gone to the length of creating a login module now, which will just contain the code to read in the secrets file and expose it’s contents. Later we can look to extend the module with other login tasks like requesting a token and having users login.

vim trademe/login.js
var fs = require('fs');
module.exports = function(file, callback) {
   var secrets = fs.readFileSync(file, 'utf8');
   secrets = JSON.parse(secrets);
   return callback(null, secrets);
};

In the main file we are using to work with trademe API’s we can get and use those details.

 

vim trademe/insert_data.js
var login = require('./login.js');

login('./secrets/secrets.json', function(error, data) {
   if (error) { console.error(error); }
   secrets = data;
});

var oauth = new OAuth.OAuth(
 secrets.request_token,
 ...
);

At present the secrets file is checked with the actual tokens in as we are just developing at the moment. In prod we would remove from source and encrypt and store locally.

 

Advertisements

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