Skip to content

Instantly share code, notes, and snippets.

@jed
Created November 14, 2011 12:24
Show Gist options
  • Save jed/1363843 to your computer and use it in GitHub Desktop.
Save jed/1363843 to your computer and use it in GitHub Desktop.
github auth
var url = require("url")
, https = require("https")
exports.Application = function(options) {
if (!options.secret) throw "No application secret provided."
if (!options.clientId) throw "No application client ID provided."
return function(req, res) {
var protocol = res.socket.encrypted ? "https" : "http"
, uri = protocol + "://" + req.headers.host + req.url
, query = url.parse(uri, true).query
function error(message) {
message = "An error occurred: " + message
res.writeHead(500, {
"Content-Type": "text/plain",
"Content-Length": message.length
})
res.end(message)
}
if (query.code) {
https
.request({
method: "POST",
host: "github.com",
path:
"/login/oauth/access_token" +
url.format({query: {
client_id: options.clientId,
client_secret: options.secret,
code: query.code
}})
}, function(response) {
var data = ""
response
.on("data", function(chunk){ data += chunk })
.on("end", function() {
data = url.parse("?" + data, true).query
console.log(data)
res.end(data.access_token)
})
})
.on('error', function(err){ error(err.message) })
.end()
}
else if (query.error) error(query.error)
else {
res.writeHead(302, {
Location: url.format({
protocol: "https", host: "github.com",
pathname: "/login/oauth/authorize",
query: {
client_id: options.clientId,
scopes: options.scopes || [],
redirect_uri: uri
}
})
})
res.end()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment