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

ruby
class Order
  class InvalidTransition < StandardError; end
 
  TRANSITIONS = {

A state machine for order transitions in Ruby

state-machine data-driven error-handling
Intermediate 8 steps
typescript
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { ConfigService } from '@nestjs/config';

How a JWT strategy authenticates in NestJS

authentication jwt passport
Intermediate 7 steps
ruby
class CreateOrderItems < ActiveRecord::Migration[7.1]
  def change
    create_table :order_items do |t|
      t.references :order, null: false, foreign_key: { on_delete: :cascade }

Enforcing order-item integrity in Rails

migrations foreign-keys validations
Intermediate 7 steps
ruby
class Registration < ApplicationRecord
  belongs_to :event
 
  validates :email, presence: true, format: { with: URI::MailTo::EMAIL_REGEXP }

Validating registrations in Rails

validations i18n error-handling
Intermediate 8 steps
typescript
import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common';
import { GqlExecutionContext } from '@nestjs/graphql';
import { Reflector } from '@nestjs/core';
import { JwtService } from '@nestjs/jwt';

How a GraphQL auth guard works in NestJS

authentication authorization jwt
Intermediate 7 steps
ruby
class ApacheLogParser
  LINE_PATTERN = /\A(?<ip>\S+)\s\S+\s\S+\s\[(?<time>[^\]]+)\]\s"(?<method>[A-Z]+)\s(?<path>\S+)\s(?<protocol>[^"]+)"\s(?<status>\d{3})\s(?<bytes>\d+|-)/
 
  TIME_FORMAT = "%d/%b/%Y:%H:%M:%S %z"

Parsing Apache logs with named captures

regex named-captures parsing
Intermediate 6 steps

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