]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - middlewares/misc.js
Infile code reorganization
[github/Chocobozzz/PeerTube.git] / middlewares / misc.js
1 ;(function () {
2 'use strict'
3
4 var fs = require('fs')
5 var ursa = require('ursa')
6
7 var logger = require('../helpers/logger')
8 var PodsDB = require('../initializers/database').PodsDB
9 var utils = require('../helpers/utils')
10
11 var miscMiddleware = {
12 cache: cache,
13 decryptBody: decryptBody
14 }
15
16 function cache (cache) {
17 return function (req, res, next) {
18 // If we want explicitly a cache
19 // Or if we don't specify if we want a cache or no and we are in production
20 if (cache === true || (cache !== false && process.env.NODE_ENV === 'production')) {
21 res.setHeader('Cache-Control', 'public')
22 } else {
23 res.setHeader('Cache-Control', 'no-cache, no-store, max-age=0, must-revalidate')
24 }
25
26 next()
27 }
28 }
29
30 function decryptBody (req, res, next) {
31 PodsDB.findOne({ url: req.body.signature.url }, function (err, pod) {
32 if (err) {
33 logger.error('Cannot get signed url in decryptBody.', { error: err })
34 return res.sendStatus(500)
35 }
36
37 if (pod === null) {
38 logger.error('Unknown pod %s.', req.body.signature.url)
39 return res.sendStatus(403)
40 }
41
42 logger.debug('Decrypting body from %s.', req.body.signature.url)
43
44 var crt = ursa.createPublicKey(pod.publicKey)
45 var signature_ok = crt.hashAndVerify('sha256', new Buffer(req.body.signature.url).toString('hex'), req.body.signature.signature, 'hex')
46
47 if (signature_ok === true) {
48 var myKey = ursa.createPrivateKey(fs.readFileSync(utils.getCertDir() + 'peertube.key.pem'))
49 var decryptedKey = myKey.decrypt(req.body.key, 'hex', 'utf8')
50 req.body.data = JSON.parse(utils.symetricDecrypt(req.body.data, decryptedKey))
51 delete req.body.key
52 } else {
53 logger.error('Signature is not okay in decryptBody for %s.', req.body.signature.url)
54 return res.sendStatus(403)
55 }
56
57 next()
58 })
59 }
60
61 // ---------------------------------------------------------------------------
62
63 module.exports = miscMiddleware
64 })()