Created
August 17, 2020 15:10
-
-
Save ugurcemozturk/ef02f0b083ad6888c875812ff1dfe139 to your computer and use it in GitHub Desktop.
Create a signed Cloudfront URL for an object in S3 on AWS
This file contains 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
const AWS = require("aws-sdk"); | |
var fs = require('fs'); | |
exports.GetImage = async(event) => { | |
try { | |
let image = event['pathParameters']['img'] | |
let ImageKey = `${process.env.IMAGE_FOLDER}/${image}`; | |
const cloudfrontAccessKeyId = process.env.CLOUDFRONT_KEY_ID; | |
const cloudFrontPrivateKey = fs.readFileSync('cloudfront-pk.pem', 'utf8'); | |
const signer = new AWS.CloudFront.Signer( | |
cloudfrontAccessKeyId, | |
cloudFrontPrivateKey | |
); | |
const signedUrl = signer.getSignedUrl({ | |
url: `https://${process.env.CLOUDFRONT_DOMAIN_NAME}/${ImageKey}`, | |
expires: Math.floor((Date.now() + process.env.URL_EXPIRE) / 1000), | |
}); | |
let body = { | |
signed_image_url: decodeURI(signedUrl) | |
}; | |
return { | |
statusCode: 200, | |
body: JSON.stringify(body), | |
}; | |
} catch (err) { | |
console.log(err) | |
return { | |
statusCode: err.statusCode || 400, | |
body: err.message || JSON.stringify(err.message), | |
}; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment