This repository has been archived by the owner on Jan 15, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathoauth.js
61 lines (51 loc) · 1.67 KB
/
oauth.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
'use strict'
const logger = require('winston')
const jsonwebtoken = require('jsonwebtoken')
const request = require('request')
// Obtain an OAuth token for the app, repeat at regular intervals before the
// token expires. Returns a function that will always return a current
// valid token.
exports.run = (appId, secret, cb) => {
let tok
// Return the current token
const current = () => tok
// Return the time to live of a token
const ttl = (tok) =>
Math.max(0, jsonwebtoken.decode(tok).exp * 1000 - Date.now())
// Refresh the token
const refresh = (cb) => {
logger.verbose(`Requesting token for appId '${appId}' and secret`)
request.post('https://api.watsonwork.ibm.com/oauth/token', {
auth: {
user: appId,
pass: secret
},
json: true,
form: {
grant_type: 'client_credentials'
}
}, (err, res) => {
if (err) {
logger.error(`Error requesting token error '${err}'`)
cb(err, current)
return
} else if (res.statusCode !== 200) {
logger.error(`Bad status code requesting token: ${res.statusCode}`)
cb(new Error(res.statusCode), current)
return
} else {
// Save the fresh token
logger.verbose(`Successfully requested token`)
tok = res.body.access_token
// Schedule next refresh a bit before the token expires
const t = ttl(tok)
logger.verbose('Token time-to-live', t)
setTimeout(() => { refresh(cb) }, Math.max(0, t - 60000)).unref()
// Return a function that'll return the current token
cb(null, current)
}
})
}
// Obtain initial token
setImmediate(() => refresh(cb))
}