verificarNonce.js 1.36 KB
const createError = require('http-errors')
const su = require('superagent')
const EC = require('elliptic').ec
const ec = new EC('secp256k1')
const { clientPoint } = require('../keys')
const clientPub = ec.keyFromPublic(clientPoint)

const headers = {
  'Accept': 'application/json',
  'Content-Type': 'application/json',
}

const dbhost = process.env.COUCHDB_URL
const dbnonces = process.env.DB_NONCES

// GET -> Request Token
// El nonce es un uuid, y solo se puede utilizar una sola vez
// La firma es solamente la firma del nonce
// GET /token/:nonce/:firma

const existe = (nonce) =>
  su.head(`${dbhost}/${dbnonces}/${nonce}`)
  .then(
    (response) => response.status === 200,
    (error) => {
      if (error.status === 404) return false
      throw error
    }
  )

const crear = (nonce, firma) =>
  su.put(`${dbhost}/${dbnonces}/${nonce}`)
  .set(headers)
  .send( JSON.stringify({ _id: nonce, firma }))
  .then(res => res.body)

const verificar = (nonce, firma) => {
  return clientPub.verify(nonce, new Buffer(firma, 'hex'))
}

module.exports = (req, res, next) => {
  const { nonce, firma } = req.params
  const valido = verificar(nonce, firma)
  if (!valido ) return next(createError(403))

  existe(nonce)
  .then((utilizado) => {
    if(utilizado) return next(createError(403))
    return crear(nonce, firma).then(() => next())
  })
  .catch((error) => createError(500))
}