Skip to content

Instantly share code, notes, and snippets.

@btd
Created August 15, 2016 11:03
Show Gist options
  • Save btd/64d39357e8a74a6b6a1479f4d94c2d34 to your computer and use it in GitHub Desktop.
Save btd/64d39357e8a74a6b6a1479f4d94c2d34 to your computer and use it in GitHub Desktop.
Very basic image proxy
'use strict';
const express = require('express');
const crypto = require('crypto');
const got = require('got');
const signingKey = 'some sort of key here';
const proxyHeaders = [
'content-length',
'content-type',
'etag',
'expires',
'last-modified',
'vary'
];
var app = express()
app.disable('x-powered-by');
app.get('/:imageSignature/:imageUrl', function (req, res, next) {
const imageSignature = req.params.imageSignature;
const imageUrl = req.params.imageUrl;
// compare signature
const hmac = crypto.createHmac('sha256', signingKey);
hmac.update(imageUrl, 'utf8');
var expectedSignature = hmac.digest('hex');
console.log(req.params)
console.log('expectedSignature', expectedSignature);
if(expectedSignature !== imageSignature) {
var err = new Error('Requested signature does not match');
err.status = 400;
return next(err);
}
console.log('Request headers', req.headers);
var headers = {
'Accept': req.headers.accept || 'image/*',
'User-Agent': req.headers['user-agent'],
};
return got.get(imageUrl, { headers: headers })
.then(function(imageResponse) {
console.log('response headers', imageResponse.headers)
proxyHeaders.forEach(function(header) {
var headerValue = imageResponse.headers[header];
if(headerValue) {
res.setHeader(header, headerValue);
console.log('set header', header, headerValue)
}
})
res.status(imageResponse.statusCode)
.send(imageResponse.body)
})
.catch(function(err) {
err.status = 400;
return next(err);
})
})
app.listen(3000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment