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