diff --git a/lib/pair.js b/lib/pair.js index 027f80fe..148bef0a 100644 --- a/lib/pair.js +++ b/lib/pair.js @@ -1,12 +1,17 @@ const db = require('./db') -function pair (token, deviceId) { +function pullToken (token) { const sql = `delete from pairing_tokens where token=$1 returning created < now() - interval '1 hour' as expired` return db.one(sql, [token]) - .then(r => { - if (r.expired) return false + .then(r => r.expired) +} + +function pair (token, deviceId) { + pullToken(token) + .then(valid => { + if (!valid) return false const pairSql = 'insert into paired_devices (device_id) values ($1)' return db.none(pairSql, [deviceId]) @@ -14,6 +19,10 @@ function pair (token, deviceId) { }) } +function authorizeCaDownload (caToken) { + return pullToken(caToken) +} + function isPaired (deviceId) { const sql = 'select device_id from paired_devices where device_id=$1' @@ -21,4 +30,4 @@ function isPaired (deviceId) { .then(() => true) } -module.exports = {pair, isPaired} +module.exports = {pair, authorizeCaDownload, isPaired} diff --git a/lib/routes.js b/lib/routes.js index 68a63267..78b82548 100644 --- a/lib/routes.js +++ b/lib/routes.js @@ -222,6 +222,17 @@ function verifyTx (req, res) { }) } +function ca (req, res) { + const token = req.body.token + + return pair.authorizeCaDownload(token) + .then(valid => { + if (valid) return res.json({ca: pair.ca()}) + + return res.status(408).end() + }) +} + function pair (req, res) { const token = req.body.token const deviceId = getDeviceId(req) @@ -337,6 +348,9 @@ function init (opts) { const app = opts.app const localApp = opts.localApp + app.post('/pair', pair) + app.post('/ca', ca) + app.get('/poll', authMiddleware, poll) app.post('/trade', authMiddleware, trade) @@ -348,7 +362,6 @@ function init (opts) { app.post('/event', authMiddleware, deviceEvent) app.post('/verify_user', authMiddleware, verifyUser) app.post('/verify_transaction', authMiddleware, verifyTx) - app.post('/pair', pair) app.post('/phone_code', authMiddleware, phoneCode) app.post('/update_phone', authMiddleware, updatePhone) diff --git a/migrations/015-paired_devices.js b/migrations/015-paired_devices.js new file mode 100644 index 00000000..5c310b29 --- /dev/null +++ b/migrations/015-paired_devices.js @@ -0,0 +1,17 @@ +var db = require('./db') + +exports.up = function (next) { + var sql = [ + 'alter table devices drop authorized', + 'alter table devices drop unpair', + `create table paired_devices ( + device_id text PRIMARY KEY, + created timestamptz NOT NULL default now() + )` + ] + db.multi(sql, next) +} + +exports.down = function (next) { + next() +}