Search code examples
ruby-on-railsamazon-web-servicesamazon-s3coffeescriptcarrierwave

How to test an S3 Presigned GET url to see if it has expired, and regenerate it if it has, using Ruby on Rails/Coffeescript


I am building a document management system in Ruby on Rails that uses Amazon S3 for storage. I am using the carrierwave and carrierwave-aws gems for uploading/downloading the files.

I have it working to where I can generate a presigned url that expires after a certain amount of time (the sooner the better...maybe 10 seconds-1 minute), but the problem I'm having is if someone loads the page and doesn't click the "Download" button right away, then the link expires and they get directed to an ugly XML error.

What I'm trying to figure out is either:

  1. How can I generate the presigned url on the fly when the download button is clicked (I'm thinking with Coffeescript) OR

  2. Go ahead and generate the presigned url on page load, but when download is clicked, somehow check to see if it returns an error and if so, get a new presigned url and redirect to it at that time. (Again, thinking Coffeescript, if possible)


Solution

  • In the past I have taken the following entirely serverside approach to a similar problem (not using carrier wave, but shouldn't be relevant).

    Have the download button link to a controller/action in your app, passing the id of the document. Your controller action then generates a presigned URL and then redirects the user to that URL.

    In theory you would only need a very short lifetime on such a presigned urls, although if the files are large enough that a user might want to pause and resume transfers then a longer lifetime might be advisable.