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