Skip to content

Instantly share code, notes, and snippets.

@tcr
Created October 23, 2011 07:30
Show Gist options
  • Save tcr/1306996 to your computer and use it in GitHub Desktop.
Save tcr/1306996 to your computer and use it in GitHub Desktop.
How to get started with OAuth and Github's API on node.js?
config =
key: "github_key"
secret: "github_secret"
clientID: "github_client_id"
# Network shim.
net =
post: (host, path, query, headers, data, fn) ->
headers ?= {}
if not headers['Content-Length']? then headers['Content-Length'] = data.length
options =
method: 'POST'
host: host
headers: headers
path: path + '?' + querystring.stringify(query)
req = https.request options, (res) ->
statusCode = Number(res.statusCode)
data = ''
res.on 'data', (d) -> data += d
res.on 'end', ->
if statusCode >= 400 then fn(statusCode, data)
else fn(0, data)
req.write data
req.end()
# Now your express login route...
app.get '/login', (req, res) ->
unless req.query.code
res.redirect "https://github.com/login/oauth/authorize?client_id=#{config.clientID}&scope=gist"
return
else
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
body = querystring.stringify({client_id: config.clientID, client_secret: config.secret, code: req.query.code})
net.post 'github.com', '/login/oauth/access_token', {}, headers, body, (err, data) ->
{access_token} = querystring.parse(data)
req.session.access_token = access_token
res.redirect '/'

Github uses a somewhat nonconventional OAuth flow, in that it is easy enough to implement without the Node OAuth library. Here is a possible implementation for Express.

["node","node.js","oauth","github","api","coffeescript"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment