forked from odysseyscience/react-s3-uploader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paths3router.js
67 lines (56 loc) · 1.79 KB
/
s3router.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
var mime = require('mime'),
uuid = require('node-uuid'),
aws = require('aws-sdk'),
express = require('express');
function S3Router(options) {
var S3_BUCKET = options.bucket,
getFileKeyDir = options.getFileKeyDir || function() { return "."; };
if (!S3_BUCKET) {
throw new Error("S3_BUCKET is required.");
}
var router = express.Router();
/**
* Redirects image requests with a temporary signed URL, giving access
* to GET an image.
*/
router.get(/\/img\/(.*)/, function(req, res) {
var params = {
Bucket: S3_BUCKET,
Key: getFileKeyDir(req) + '/' + req.params[0]
};
var s3 = new aws.S3();
s3.getSignedUrl('getObject', params, function(err, url) {
res.redirect(url);
});
});
/**
* Returns an object with `signedUrl` and `publicUrl` properties that
* give temporary access to PUT an object in an S3 bucket.
*/
router.get('/sign', function(req, res) {
var filename = uuid.v4() + "_" + req.query.objectName;
var mimeType = mime.lookup(filename);
var fileKey = getFileKeyDir(req) + '/' + filename;
var s3 = new aws.S3();
var params = {
Bucket: S3_BUCKET,
Key: fileKey,
Expires: 60,
ContentType: mimeType,
ACL: 'private'
};
s3.getSignedUrl('putObject', params, function(err, data) {
if (err) {
console.log(err);
return res.send(500, "Cannot create S3 signed URL");
}
res.json({
signedUrl: data,
publicUrl: '/s3/img/' + filename,
filename: filename
});
});
});
return router;
}
module.exports = S3Router;