-
Notifications
You must be signed in to change notification settings - Fork 5
/
signed-url.js
73 lines (63 loc) · 2.33 KB
/
signed-url.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
'use strict'
const AWS = require('aws-sdk')
const s3bucket = new AWS.S3({
apiVersion: '2006-03-01',
signatureVersion: 'v4',
Bucket: process.env.UploadPictureBucket,
region: process.env.UploadPictureBucketRegion
})
module.exports.handler = async (event) => {
try {
const body = JSON.parse(JSON.stringify(event.body))
let { fileName } = JSON.parse(body)
fileName = updateFileName(fileName)
let s3Params = {
Bucket: process.env.UploadPictureBucket,
Key: fileName,
Expires: 60,
ACL: 'public-read',
ContentType: '*/*',
}
try {
const data = await s3bucket.getSignedUrl('putObject', s3Params)
return {
statusCode: 200,
headers: { 'Access-Control-Allow-Origin': '*', 'Content-Type': 'application/json' },
body: JSON.stringify({ signedUrl: data, picture: fileName })
}
} catch (err) {
return {
statusCode: 200,
headers: { 'Access-Control-Allow-Origin': '*', 'Content-Type': 'application/json' },
body: JSON.stringify({ 'message': err.message })
}
}
} catch (err) {
return {
statusCode: 200,
headers: { 'Access-Control-Allow-Origin': '*', 'Content-Type': 'application/json' },
status: 'error',
message: err.message
}
}
}
function updateFileName(fileName) {
if (!fileName) return
fileName = fileName.toLowerCase()
// strip out non-alpha numeric, dots, hyphens, underscores
fileName = fileName.replace(/[^a-z-0-9.-_]+/gi, '')
if (fileName === '') return
if (fileName.indexOf('.') === -1) return
// assign a random five digit number
let min = Math.ceil(10000)
let max = Math.floor(99999)
const randomNumber = (Math.floor(Math.random() * (max - min + 1)) + min).toString()
const existingFileName = fileName.split('.')
let newFileName = ''
for (let i = 0; i < existingFileName.length-1; i++) {
newFileName = newFileName + existingFileName[i] + '.'
}
newFileName = newFileName.substr(0, newFileName.length - 1)
const fileExtension = fileName.split('.').pop()
return randomNumber + '-' + newFileName + '.' + fileExtension
}