0

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']
    }

};
Colin
  • 930
  • 3
  • 19
  • 42
  • Have you gotten this working? Struggling myself with Grant and Purest hit an API endpoint provided by Cubesensors (OAuth1). Endpoint is not accepting the access_token I am sending. – Alan J. Aug 30 '15 at 15:10

1 Answers1

2

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);
        })
});
brandonscript
  • 68,675
  • 32
  • 163
  • 220
  • Thanks Remus, I'll give this a try tomorrow but it looks like it may be what I'm looking for. It looks suspiciously simple(!) :-) Half the problem for node-noobs seems to be discovering the right NPM. – Colin Jul 22 '15 at 21:13
  • ALL of the problems for node *developers* seems to be discovering the right NPM LOL! – brandonscript Jul 22 '15 at 21:17
  • The second part of the question is how do you save the token for use another day? I don't have user profiles to justify Mongo, just a website rendering my own data. – Colin Jul 22 '15 at 21:24
  • Honestly that would be bad practice - caching OAuth tokens on a server is a huge security risk. Instead, store the token on the client (in a cookie or localstorage) and set the expiry to match the token expiry. Then the client will always be passing it in and you'll never have to worry about storing a database of live tokens on your server. – brandonscript Jul 22 '15 at 21:27