diff --git a/lib/app.js b/lib/app.js index ede1210d..fb5f9fbf 100644 --- a/lib/app.js +++ b/lib/app.js @@ -9,7 +9,7 @@ var plugins = require('./plugins') var logger = require('./logger') var configManager = require('./config-manager') -const db = require('./db') +const pair = require('./pair') module.exports = function (options) { var app = express() @@ -64,11 +64,15 @@ module.exports = function (options) { authMiddleware = function (req, res, next) { const deviceId = req.connection.getPeerCertificate().fingerprint - const sql = 'select id from devices where device_id=$1 and authorized=$2' - db.one(sql, [deviceId, true]) - .then(() => { - req.deviceId = deviceId - next() + + return pair.isPaired(deviceId) + .then(r => { + if (r) { + req.deviceId = deviceId + return next() + } + + throw new Error('Unauthorized') }) .catch(e => res.status(403).end()) } diff --git a/lib/pair.js b/lib/pair.js index 51e808b0..4276fe8b 100644 --- a/lib/pair.js +++ b/lib/pair.js @@ -1,26 +1,6 @@ -const fs = require('fs') -const pify = require('pify') -const readFile = pify(fs.readFile) const path = require('path') -const crypto = require('crypto') const db = require('./db') -const CA_PATH = path.resolve(__dirname, '..', 'ca-cert.pem') - -function totem (ipAddress) { - return readFile(CA_PATH) - .then(data => { - const caHash = crypto.createHash('sha256').update(data).digest() - const token = crypto.randomBytes(32) - const ip = Buffer.from(ipAddress.split('.').map(s => parseInt(s, 10))) - const buf = Buffer.concat([ip, caHash, token]) - const sql = 'insert into pairing_tokens (token) values ($1)' - - return db.none(sql, [token.toString('hex')]) - .then(() => buf.toString('base64')) - }) -} - function pair (token, deviceId) { const sql = `delete from pairing_tokens where token=$1 @@ -42,4 +22,4 @@ function isPaired (deviceId) { .then(() => true) } -module.exports = {totem, pair, isPaired} +module.exports = {totem, pair, unpair, isPaired}