Files
fizzy/lib/rails_ext/active_storage_authorization.rb
T
Rosa Gutierrez 196d685f8d Implement authorization for Active Storage endpoints
Consider blobs attached to any public records accessible to anyone with
the URL.
2025-12-25 21:22:36 +01:00

50 lines
1.4 KiB
Ruby

ActiveSupport.on_load :active_storage_blob do
def accessible_to?(user)
attachments.includes(:record).any? { |attachment| attachment.accessible_to?(user) } || attachments.none?
end
def publicly_accessible?
attachments.includes(:record).any? { |attachment| attachment.publicly_accessible? }
end
end
ActiveSupport.on_load :active_storage_attachment do
def accessible_to?(user)
record.try(:accessible_to?, user)
end
def publicly_accessible?
record.try(:publicly_accessible?)
end
end
Rails.application.config.to_prepare do
module ActiveStorage::Authorize
extend ActiveSupport::Concern
include Authentication
included do
# Ensure require_authentication runs after set_blob.
skip_before_action :require_authentication
before_action :require_authentication, :ensure_accessible, unless: :publicly_accessible_blob?
end
private
def publicly_accessible_blob?
@blob.publicly_accessible?
end
def ensure_accessible
unless @blob.accessible_to?(Current.user)
head :forbidden
end
end
end
ActiveStorage::Blobs::RedirectController.include ActiveStorage::Authorize
ActiveStorage::Blobs::ProxyController.include ActiveStorage::Authorize
ActiveStorage::Representations::RedirectController.include ActiveStorage::Authorize
ActiveStorage::Representations::ProxyController.include ActiveStorage::Authorize
end