ruby 34 lines · 8 steps

Serving secure file downloads in Rails

A controller gates document access, then hands out short-lived signed URLs for downloads and previews.

Explained by highlit
1class DocumentsController < ApplicationController
2 before_action :authenticate_user!
3 before_action :set_document
4 
5 def download
6 unless @document.readable_by?(current_user)
7 return head :forbidden
8 end
9 
10 url = @document.file.url(
11 expires_in: 5.minutes,
12 disposition: "attachment",
13 filename: @document.original_filename
14 )
15 
16 redirect_to url, allow_other_host: true
17 end
18 
19 def preview
20 return head :not_found unless @document.file.attached?
21 
22 url = @document.file.representation(resize_to_limit: [1200, 1200]).url(
23 expires_in: 15.minutes
24 )
25 
26 render json: { url: url, expires_at: 15.minutes.from_now }
27 end
28 
29 private
30 
31 def set_document
32 @document = current_user.account.documents.find(params[:id])
33 end
34end
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Redirecting to short-lived signed URLs offloads file serving from your app while keeping access controlled.
  2. 2Scoping lookups through the current user's account turns authorization into a query so records simply can't be found across tenants.
  3. 3Active Storage's representation lets you serve on-the-fly resized variants without storing them separately.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Serving secure file downloads in Rails — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code