ruby-on-rails - 如何随机生成文件链接?

标签 ruby-on-rails ruby amazon-web-services

我有一个 PDF 文件,我不想通过我网站上的 URL 公开访问它。作为(轻微的)安全层,我想通过电子邮件向用户发送一个随机生成的唯一 URL,他们可以从中下载 PDF,我会将其存储在 AWS 或类似的东西上。

我觉得我被困在 routes.rb jail 里了,我不知道如何动态生成 URL,也不知道如何正确地创建随机 URL、跟踪它们或将它们链接到存储在本地或上的文件AWS。

有人对解决这个问题有什么建议吗?

最佳答案

您如何存储 PDF?如果你使用类似 Paperclip 的东西,您可以很容易地生成私有(private)文件的临时公共(public) URL:

class Attachment < ActiveRecord::Base

  has_attached_file :file

  # ...

  def file_url
    file.expiring_url(10)
  end

end

file_url 将为该文件生成一个 10 秒有效的 URL。然后,在任何相关的 Controller 中,您都可以为文件本身提供一个“显示”方法,该方法在访问时快速重定向到私有(private) url:

class AttachmentsController < ApplicationController

  # GET /whatever/attachments/:id
  def show
    redirect_to Attachment.find(params[:id]).file_url
  end

end

要像您要发送的那样获得“随机”URL,您需要一个额外的步骤。您可以使用 SecureRandom.uuid 之类的东西生成一个长散列,并将其作为参数传递,并使用 AttachmentProxy 之类的简单模型。

类似于:

class AttachmentProxy < ActiveRecord::Base

  has_one :attachment

  # has an attribute called 'key', indexed...

end

在你的 Controller 中:

class AttachmentProxyController < ApplicationController

  def show
    proxy = AttachmentProxy.find_by_key(params[:key])
    redirect_to proxy.attachment.file_url
  end

end

关于ruby-on-rails - 如何随机生成文件链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19847292/

相关文章:

android - 仅允许 Android 应用程序访问 Rails API 的最佳实践

ruby-on-rails - Rails Guides 离线文档

ruby-on-rails - 以 DRY 方式覆盖 ActiveRecord 中的 "find"

ruby-on-rails - Rails fields_for 里面的 fields_for

amazon-web-services - AWS Glue Sagemaker 笔记本 "No module named awsglue.transforms"

ruby-on-rails - 在没有 method_missing 的情况下使用 Rails 获取 SEO 友好的 URLS?

ruby - 如何关闭 rvm 的全局 gem?

Ruby,向模块、类或对象添加方法

postgresql - 尝试使用 Postgresql 连接到 Amazon RDS 时出错

amazon-web-services - 将亚马逊产品类别映射到正确的类别 XSD