UNPKG

github-oauth2

Version:

A utility to get Oauth2 tokens from github for use in api calls.

72 lines (62 loc) 1.65 kB
var request = require("request") , credential = require("git-credential") , USER_AGENT = require("./user-agent") , ap = require("ap") var host = "https://api.github.com/authorizations" module.exports = get_token // TODO make this a writable stream, (as well?) so you just emit note, note_url // and scopes with the data event.) function prep(note, note_url, scopes){ return get_token function get_token(ready){ var f = ap([ready], check_for) credential(f) } function check_for(ready, error, credentials){ if (error){ console.log("request failed") console.log(""+error) } var r = { url: host , headers: {"User-Agent": USER_AGENT} , auth: credentials } request.get(r, function(error, response){ if (error) { return ready(error) } if (response.statusCode != 200) { return ready(response.body, response.statusCode) } //otherwise search for a token var token var token_found = JSON.parse(response.body).some(function(d){ token = d.token return d.note == note }) if (token_found) { ready(error, token) } else { get_new_token(ready, credentials) } }) } function get_new_token(ready, credentials){ var r = { url: host , headers: { "User-Agent": USER_AGENT } , body: JSON.stringify({ scopes: scopes , note: note , note_url: note_url }) , 'auth': credentials } request.post(r, function(err, response, body){ ready(err, JSON.parse(body).token) }) } }