Handle express-validator error on the client side and fix #96 (#98)
[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 import { PodSignature } from '../../shared'
10
11 function checkSignature (req: express.Request, res: express.Response, next: express.NextFunction) {
12   const signatureObject: PodSignature = req.body.signature
13   const host = signatureObject.host
14
15   db.Pod.loadByHost(host)
16     .then(pod => {
17       if (pod === null) {
18         logger.error('Unknown pod %s.', host)
19         return res.sendStatus(403)
20       }
21
22       logger.debug('Checking signature from %s.', host)
23
24       let signatureShouldBe
25       // If there is data in the body the sender used it for its signature
26       // If there is no data we just use its host as signature
27       if (req.body.data) {
28         signatureShouldBe = req.body.data
29       } else {
30         signatureShouldBe = host
31       }
32
33       const signatureOk = peertubeCryptoCheckSignature(pod.publicKey, signatureShouldBe, signatureObject.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.', signatureObject.host)
44       return res.sendStatus(403)
45     })
46     .catch(err => {
47       logger.error('Cannot get signed host in body.', { error: err.stack, signature: signatureObject.signature })
48       return res.sendStatus(500)
49     })
50 }
51
52 // ---------------------------------------------------------------------------
53
54 export {
55   checkSignature
56 }