ee836beed45059ce362f30e104db46bb13c054a3
[oweals/peertube.git] / server / middlewares / secure.js
1 'use strict'
2
3 const logger = require('../helpers/logger')
4 const mongoose = require('mongoose')
5 const peertubeCrypto = require('../helpers/peertube-crypto')
6
7 const Pod = mongoose.model('Pod')
8
9 const secureMiddleware = {
10   checkSignature
11 }
12
13 function checkSignature (req, res, next) {
14   const host = req.body.signature.host
15   Pod.loadByHost(host, function (err, pod) {
16     if (err) {
17       logger.error('Cannot get signed host in body.', { error: err })
18       return res.sendStatus(500)
19     }
20
21     if (pod === null) {
22       logger.error('Unknown pod %s.', host)
23       return res.sendStatus(403)
24     }
25
26     logger.debug('Checking signature from %s.', host)
27
28     const signatureOk = peertubeCrypto.checkSignature(pod.publicKey, host, req.body.signature.signature)
29
30     if (signatureOk === true) {
31       return next()
32     }
33
34     logger.error('Signature is not okay in body for %s.', req.body.signature.host)
35     return res.sendStatus(403)
36   })
37 }
38
39 // ---------------------------------------------------------------------------
40
41 module.exports = secureMiddleware