]>
Commit | Line | Data |
---|---|---|
9f10b292 C |
1 | 'use strict' |
2 | ||
f0f5567b | 3 | const logger = require('../helpers/logger') |
a3ee6fa2 | 4 | const mongoose = require('mongoose') |
5f698b82 | 5 | const peertubeCrypto = require('../helpers/peertube-crypto') |
a3ee6fa2 C |
6 | |
7 | const Pod = mongoose.model('Pod') | |
9f10b292 | 8 | |
f0f5567b | 9 | const secureMiddleware = { |
c4403b29 C |
10 | checkSignature, |
11 | decryptBody | |
9f10b292 C |
12 | } |
13 | ||
0eb78d53 | 14 | function checkSignature (req, res, next) { |
49abbbbe C |
15 | const host = req.body.signature.host |
16 | Pod.loadByHost(host, function (err, pod) { | |
9f10b292 | 17 | if (err) { |
49abbbbe | 18 | logger.error('Cannot get signed host in decryptBody.', { error: err }) |
9f10b292 C |
19 | return res.sendStatus(500) |
20 | } | |
21 | ||
22 | if (pod === null) { | |
49abbbbe | 23 | logger.error('Unknown pod %s.', host) |
9f10b292 C |
24 | return res.sendStatus(403) |
25 | } | |
26 | ||
49abbbbe | 27 | logger.debug('Decrypting body from %s.', host) |
9f10b292 | 28 | |
49abbbbe | 29 | const signatureOk = peertubeCrypto.checkSignature(pod.publicKey, host, req.body.signature.signature) |
9f10b292 | 30 | |
bc503c2a | 31 | if (signatureOk === true) { |
0eb78d53 C |
32 | return next() |
33 | } | |
34 | ||
49abbbbe | 35 | logger.error('Signature is not okay in decryptBody for %s.', req.body.signature.host) |
0eb78d53 C |
36 | return res.sendStatus(403) |
37 | }) | |
38 | } | |
39 | ||
40 | function decryptBody (req, res, next) { | |
41 | peertubeCrypto.decrypt(req.body.key, req.body.data, function (err, decrypted) { | |
42 | if (err) { | |
43 | logger.error('Cannot decrypt data.', { error: err }) | |
44 | return res.sendStatus(500) | |
9f10b292 | 45 | } |
0eb78d53 C |
46 | |
47 | try { | |
48 | req.body.data = JSON.parse(decrypted) | |
49 | delete req.body.key | |
50 | } catch (err) { | |
51 | logger.error('Error in JSON.parse', { error: err }) | |
52 | return res.sendStatus(500) | |
53 | } | |
54 | ||
55 | next() | |
9f10b292 C |
56 | }) |
57 | } | |
58 | ||
59 | // --------------------------------------------------------------------------- | |
60 | ||
61 | module.exports = secureMiddleware |