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