Last active
October 21, 2015 13:03
-
-
Save slaskis/d8a40b6ddea225267470 to your computer and use it in GitHub Desktop.
Basic Auth for S3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "bucket-password", | |
"version": "1.0.0", | |
"description": "", | |
"main": "server.js", | |
"dependencies": { | |
"aws-sdk": "^2.2.10", | |
"basic-auth": "^1.0.3" | |
}, | |
"devDependencies": {}, | |
"scripts": { | |
"start": "node server", | |
"test": "echo \"Error: no test specified\" && exit 1" | |
}, | |
"author": "", | |
"license": "ISC" | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var http = require('http'); | |
var path = require('path'); | |
var auth = require('basic-auth'); | |
var aws = require('aws-sdk'); | |
// Expects the AWS credentials according to the official docs: | |
// http://docs.aws.amazon.com/AWSJavaScriptSDK/guide/node-configuring.html | |
// (if using heroku the easiest is ENV-variables) | |
var s3 = new aws.S3({ | |
region: 'eu-west-1' | |
}); | |
var BUCKET = 'buckit'; | |
var USERNAME = 'secretagent'; | |
var PASSWORD = 'verysecret'; | |
var server = http.createServer(function (req, res) { | |
var credentials = auth(req) | |
if (!credentials || credentials.name !== USERNAME || credentials.pass !== PASSWORD) { | |
res.writeHead(401, 'Access denied', { | |
'WWW-Authenticate': 'Basic realm="'+ BUCKET + '"' | |
}); | |
res.end(); | |
} else { | |
var url = s3.getSignedUrl('getObject', { | |
Bucket: BUCKET, | |
Key: req.url.slice(1), // strip the starting / | |
Expires: 60, // 1 minute from now | |
ResponseContentDisposition: 'attachment; filename=' + path.basename(req.url) | |
}); | |
console.log('redirecting to %s', url); | |
res.writeHead(301, { | |
'Location': url, | |
'Cache-Control': 'no-cache, no-store, must-revalidate', | |
'Pragma': 'no-cache', | |
'Expires': '0' | |
}); | |
res.end(); | |
} | |
}) | |
server.listen(process.env.PORT, function() { | |
console.log('started server on', this.address()) | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment