GitHub provider for township.
// index.js, your server file
var Github = require('township-github')
var explain = require('explain-error')
var Auth = require('township-auth')
var merry = require('merry')
var level = require('level')
var db = level('users')
var app = merry()
var github = Github({
returnUrl: '<some-browser-url-we-control>',
secret: '<our-secret>',
name: 'our-app',
id: '<our-id>'
})
var auth = Auth(db, {
providers: { github: github.provider() }
})
app.router([
[ '/redirect', redirect ],
[ '/register', {
// your client.js file will be posting to this route
'post': register
} ],
[ '/login', {
'post': login
} ]
])
function redirect (req, res, ctx, next) {
var html = github.redirect(req, res)
next(null, html)
}
function register (req, res, ctx, done) {
_parseJson(req, function (err, json) {
if (err) return done(err)
var opts = {
github: { code: json.code }
}
auth.create(opts, done)
})
}
function login (req, res, ctx, done) {
_parseJson(req, function (err, json) {
if (err) return done(err)
var opts = {
github: { code: json.code }
}
auth.verify('github', opts, done)
})
}
function _parseJson (req, cb) {
req.pipe(concat(function (buf) {
try {
var json = JSON.parse(buf)
} catch (err) {
return cb(explain(err, 'error parsing JSON'))
}
cb(null, json)
}))
}
You will need a client to handle requests to the server's redirect and register/login routes. The following functions should get you started:
var xhr = require('xhr')
function redirect () {
var url = '/redirect'
xhr(url, function (err, res, body) {
if (err) return console.log(err)
var location = res.headers['x-github-oauth-redirect']
window.location = location
})
}
function register() {
// need to grab the code provided by GitHub
var code = window.location.href.match(/\?code=(.*)/)[1]
var json = {
code: code
}
var opts = {
// or /login to verify user info
uri: '/register',
json: json,
method: 'POST'
}
xhr(opts, function (err, res, body) {
if (err) return console.log(err)
})
}
Create a new instance of township-github
. Takes the following arguments:
- opts.id: (required) the GitHub client ID
- opts.secret: (required) the GitHub client secret
- opts.name: (required) the GitHub application name for which id and secret were issued
- opts.returnUrl: (required)
Alternatively GITHUB_ID
, GITHUB_SECRET
, GITHUB_NAME
and
GITHUB_RETURN_URL
can be used too, which is useful when passing variables
directly from process.env
.
Set 302
redirect headers to the GitHub oauth page and return a snippet of
HTML.
Create a new provider for township-auth.