Skip to content

Instantly share code, notes, and snippets.

@netroy
Last active August 15, 2017 08:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save netroy/59aa0f29032f2aee0a402e5c6666e476 to your computer and use it in GitHub Desktop.
Save netroy/59aa0f29032f2aee0a402e5c6666e476 to your computer and use it in GitHub Desktop.
fitbit oauth

setup

  • get node 6.x
  • run npm install or yarn
  • run node index.js
  • open http://localhost:3000/auth/fitbit/connect
const OAuth2 = require('oauth').OAuth2
const Koa = require('koa')
const router = require('koa-router')()
const querystring = require('querystring')
const FITBIT_KEY = '---'
const FITBIT_SECRET = '---'
const baseUrl = 'https://www.fitbit.com'
const authUrl = '/oauth2/authorize'
const tokenUrl = 'https://api.fitbit.com/oauth2/token'
const scopes = ['profile', 'heartrate']
const callbackUrl = 'http://localhost:3000/auth/fitbit/callback'
const authParams = {
response_type: 'code',
redirect_uri: callbackUrl,
scope: scopes.join(' ')
}
const fitbitAuth = new OAuth2(FITBIT_KEY, FITBIT_SECRET, baseUrl, authUrl, tokenUrl)
router.get('/auth/fitbit/connect', context => {
context.redirect(fitbitAuth.getAuthorizeUrl(authParams))
})
router.get('/auth/fitbit/callback', (context, next) => {
const body = querystring.stringify({
code: context.query.code,
grant_type: 'authorization_code',
client_id: FITBIT_KEY,
redirect_uri: callbackUrl
})
const headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + new Buffer(FITBIT_KEY + ':' + FITBIT_SECRET).toString('base64')
}
return new Promise((resolve, reject) => {
fitbitAuth._request('POST', tokenUrl, headers, body, null, (err, data) => {
if (err) {
console.log('error', err)
resolve('failed')
} else {
console.log('got an access-token', data.access_token)
resolve('connected')
}
})
}).then(status => {
context.body = `<!doctype html> <meta http-equiv="refresh" content="0; url=clue://auth/fitbit/${status}">`
return next()
})
})
const app = new Koa()
app.use(router.routes())
app.listen(3000, () => {
console.log('open http://localhost:3000/auth/fitbit/connect in a browser to start')
})
{
"name": "fitbit",
"version": "1.0.0",
"main": "index.js",
"dependencies": {
"koa": "2.0.0",
"koa-router": "7.0.1",
"oauth": "0.9.14"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment