To prevent anyone with a url accessing restricted files, I need to check user role permissions to view those ActiveStorage model attachments beforehand. I've created an ActiveStorage::BaseController
with a before action that does all the needed checks.
I currently find the original parent model that the attachment belongs to by using the signed_id
in the params:
signed_id = params[:signed_id].presence || params[:signed_blob_id].presence
blob_id = ActiveStorage::Blob.find_signed(signed_id)
attachment = ActiveStorage::Attachment.find_by(blob_id: blob_id)
record = attachment.record
# record.some_model method_or_check etc.
This works really well and I'm able to do all the stuff I want to do, however, sometimes the signed_id
is not in the params and instead I just get:
{"encoded_key"=>
"[LONG KEY HERE]",
"filename"=>"sample",
"format"=>"pdf"}
I have no idea why this happens unpredictably as I'm always using rails_blob_path(model.attachment, disposition: 'attachment')
or rails_blob_path(model.attachment, disposition: 'preview')
everywhere in the code and testing under the same conditions.
Is it possible to ensure the signed_id
is always present or alternatively, is there a way to get back to the parent model using the encoded_key
as rails obviously does this to display the attachment anyway?