-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
76 lines (58 loc) · 1.57 KB
/
index.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
68
69
70
71
72
73
74
75
76
// Basic node server for signing S3 requests
const PORT = process.env.PORT || 4005;
require('dotenv').config();
const aws = require('aws-sdk');
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
//
// S3 LOGIC
//
const s3Options = {
accessKeyId: process.env.S3_KEY,
secretAccessKey: process.env.S3_SECRET,
region: process.env.S3_REGION || 'us-west-1',
bucket: process.env.S3_BUCKET
};
aws.config.update(s3Options);
const client = new aws.S3();
function getSignedS3Url(fileName, fileType, cb) {
const bucket = s3Options.bucket
const params = {
Bucket: bucket,
Key: fileName,
Expires: 60 * 15, // 15 minutes
ContentType: fileType,
ACL: 'public-read'
}
client.getSignedUrl('putObject', params, function(err, data) {
const url = 'https://' + bucket + '.s3.amazonaws.com/' + fileName;
cb(err, {
signedRequest: data,
url: url
});
});
}
//
// SERVER LOGIC
//
const app = express();
// allow cors on all routes
app.use(cors());
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
// parse application/json
app.use(bodyParser.json());
app.post('/signed-request', function(req, res) {
console.log('POST /signed-request: ', req.body.file);
const body = req.body;
const file = body.file;
const type = body.type;
getSignedS3Url(file, type, function(err, signedData) {
if (err) { console.log('ERROR', err); }
res.send(signedData);
});
});
app.listen(PORT, function() {
console.log('Server listening on port: ', PORT);
});