Skip to content

Instantly share code, notes, and snippets.

@JayBizzle
Forked from solidgoldpig/monzo-auth.js
Last active April 5, 2016 21:57
Show Gist options
  • Save JayBizzle/9d6119fc3f0d7ddaf0294cedf0990a3b to your computer and use it in GitHub Desktop.
Save JayBizzle/9d6119fc3f0d7ddaf0294cedf0990a3b to your computer and use it in GitHub Desktop.
'use strict'
const yargs = require('yargs')
const express = require('express')
const request = require('request')
const uuid = require('node-uuid')
const querystring = require('querystring')
const opener = require('opener')
let argv = require('yargs')
.option('client_id', {
alias: 'id',
type: 'string',
required: true
})
.option('client_secret', {
alias: 'secret',
type: 'string',
required: true
})
.option('auth_url', {
alias: 'auth',
type: 'string',
default: 'auth.getmondo.co.uk'
})
.option('api_domain', {
alias: 'api',
type: 'string',
default: 'api.getmondo.co.uk'
})
.option('state', {
type: 'string'
})
.option('port', {
alias: 'p',
type: 'number',
default: 0
})
.option('exit', {
alias: 'x',
type: 'boolean',
default: true
})
.argv
const client_id = argv.client_id
const client_secret = argv.client_secret
const auth_url = `https://${argv.auth_url}`
const api_domain = `https://${argv.api_domain}`
const api_token_url = '/oauth2/token'
const app = express()
const server = require('http').createServer(app)
const exit_immediately = argv.exit
let port = argv.port
let state = argv.state
function getRootAddress(url) {
url = url || ''
return `http://localhost:${port}${url}`
}
function getAuthAddress() {
return getRootAddress('/mondo')
}
app.use('/mondo', (req, res) => {
if (req.query.state !== state) {
res.json({
error: 'State does not match',
state: state,
query: req.query
})
}
request({
uri: `${api_domain}${api_token_url}`,
method: 'POST',
json: true,
form: {
grant_type: 'authorization_code',
client_id: client_id,
client_secret: client_secret,
redirect_uri: getAuthAddress(),
code: req.query.code
}
}, (err, data) => {
if (err) {
res.status(500)
res.json(err)
}
if (data) {
res.json(data.body)
}
if (exit_immediately) {
process.exit()
}
})
})
app.use('/', (req, res) => {
state = req.query.state || uuid.v4()
let params = {
client_id: client_id,
redirect_uri: getAuthAddress(),
response_type: 'code',
state: state
}
let qs = querystring.stringify(params)
res.redirect(`${auth_url}?${qs}`)
})
server.listen(port, function() {
console.log('Mondo auth process started')
port = server.address().port
opener(getRootAddress())
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment