Skip to content

Instantly share code, notes, and snippets.

@kapkaev
Forked from matiaskorhonen/downloads_controller.rb
Created January 11, 2012 09:41
Show Gist options
  • Save kapkaev/1593940 to your computer and use it in GitHub Desktop.
Save kapkaev/1593940 to your computer and use it in GitHub Desktop.
unicorn secure download rails
class DownloadsController < ApplicationController
DOWNLOAD_EXPIRY = 30.minutes
DOWNLOAD_SECRET = "MYSECRET"
def show
download = Download.find(params[:id])
# download.file_path - get the path to the file, relative to the downloads directory
serve_file(download.file_path)
render :nothing => true
end
private
def serve_file(path, mime_type = "application/octet-stream")
if Rails.env == "development" || Rails.env == "test"
send_file "#{Rails.root}/downloads/#{path}", :type => mime_type
else
time = (Time.now + DOWNLOAD_EXPIRY).to_i.to_s(16).upcase
hmac = Digest::MD5.hexdigest("/downloads/#{path}/#{DOWNLOAD_SECRET}/#{time}")
redirect_to "/downloads/#{path}/#{hmac}/#{time}"
end
end
end
sudo apt-get install libpcre3 libpcre3-dev libmhash-dev build-essential zlibc zlib1g zlib1g-dev
# http://wiki.nginx.org/Modules
./configure --with-http_mp4_module --with-http_flv_module --with-http_ssl_module --with-http_secure_link_module --with-http_stub_status_module --with-http_gzip_static_module --with-google_perftools_module
# Upstream Unicorn app server
upstream unicorns {
server unix:/srv/APPLICATION/tmp/unicorn.sock;
}
# Front facing nginx
server {
listen 80;
server_name example.com;
root /srv/APPLICATION/public;
location ~ /downloads/(.*) {
rewrite ^/(.+)$ http://files.example.com/$1 last;
}
location / {
proxy_redirect off;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://unicorns;
}
}
# Downloads server
server {
listen 80;
server_name files.example.com;
root /srv/APPLICATION;
location /downloads {
secure_download on;
secure_download_secret MYSECRET; # Change MYSECRET to something random
secure_download_path_mode file;
secure_download_fail_location /fail;
}
location /fail {
# Do whatever...
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment