verificarNonce.js
1.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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) => 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, error, { expose: true }))
}