node.jsapioauth-2.0access-tokenjawbone

Oauth access_token with node.js and jawbone-up NPM


UPDATED: following feedback from Remus below.

I can successfully authorize my web application and get back an access_token and refresh_token. I'm using the nice Grant NPM (or is that really grant-express?) to get authenticated (thanks to author Simeon Valichkov).

How do I pass in the access_token to my Jawbone API calls as a bearer token using NPMs like jawbone-up or Purest?

Question#1 - What's the simplest way to create this API call with a express-bearer-token and actually get back my Jawbone json data?

What I'm seeing on the page is the token (a looong string) rather than the Jawbone json results data.

var express =   require('express')
  , session =   require('express-session')
  , ejs     =   require('ejs')
  , app     =   express()
  , fs      =   require('fs')
  , https   =   require('https')
  , Grant   =   require('grant-express')
  , grant   =   new Grant(require('./config'))
  , bodyParser = require('body-parser')
  , Purest  =   require('purest')
  , jawbone =   new Purest({provider: 'jawbone'})
  , morgan  =   require('morgan')
  , bearerToken = require('express-bearer-token');

    app.set('view engine', 'ejs');
    app.use(bodyParser.urlencoded({extended:true}))
    app.use(session({secret:'grant'}))
    app.use(grant)
    app.use(morgan('combined'))
    app.use(bearerToken());
    app.use(function (req, res) {
        res.send('Token '+req.token);
    });

var $today      = new Date()
var $start      = new Date($today); $start.setDate($today.getDate() -7)
var $end        = new Date($today)
var $startDate  = Math.floor(($start).getTime()/1000)
var $endDate    = Math.floor(($end).getTime()/1000)


    app.get('/sleeps', function (req, res) {

        //res.send(JSON.stringify(req.query.raw, null, 2))

        jawbone.query()
            .select('sleeps')
            .where ({start_date:$startDate, end_date:$endDate})
            .auth(req.token)
            .request(function(err, res, body) {
              // expecting (hoping) to get sleep json here ...??
                var result = JSON.parse(body);
                res.json(result.data.items)
            })
    }); 

// HTTPS
var sslOptions = {
        key     : fs.readFileSync('./.server.key'),
        cert    : fs.readFileSync('./.server.crt')
    };
var secureServer = https.createServer(sslOptions, app).listen(5000, function(){
    console.log('Listening on 5000');
});

My Grant config file looks like this and would seem to be the obvious place to store my tokens.

module.exports = {

"server": {
    "protocol"      : "https",
    "host"          : "localhost:5000"
    },

'jawbone' : {
    'key'           : '6f**********', 
    'secret'        : '9b918*********************',
    'callback'      : '/sleeps',
    'scope'         : ['basic_read','extended_read','move_read','sleep_read']
    }

};

Solution

  • Just to clarify - you're asking how to grab the token a user used when making a request to your server?

    Personally I've done it several ways, notably using a regular expression to grab Authorization: Bearer <token> out of the headers. But in the end, I've found my go-to solution when using Express is to use the express-bearer-token middleware:

    express = require('express');
    bearerToken = require('express-bearer-token');
    app = express();
    
    app.use(bearerToken());
    app.use(function (req, res) {
        res.send('Token '+req.token);
    });
    

    So in your case, it would be as simple as:

    app.get('/sleeps', function(req, res) {
        jawbone.query()
            .select('sleeps')
            .where ({start_date:'', end_date:''})
            .auth(req.token)
            .request(function(err, res, body) {
                res.json(req.query.raw);
            })
    });