How to store private pictures and videos in Ruby on Rails

后端 未结 4 817
情歌与酒
情歌与酒 2020-12-03 06:05

Here\'s a story:

  • User A should be able to upload an image.
  • User A should be able to set a privacy. (\"Public\" or \"Private\").
  • User B should
4条回答
  •  北荒
    北荒 (楼主)
    2020-12-03 06:56

    Here's how I did this in a similar application.

    • Store your images on Amazon S3 instead of the local file system. Paperclip supports this.
    • Set your :s3_permissions to "private" in your Paperclip options
    • In your Image model, define a method that let's you output an authorized, time-limited url for the image.

    Mine looks like this:

    def s3_url(style = :original, time_limit = 30.minutes)
      self.attachment.s3.interface.get_link(attachment.s3_bucket.to_s, attachment.path(style), time_limit)
    end
    
    • You can then show images to people only if they're authorized to see them (implement that however you like)–and not have to worry about people guessing/viewing private images. It also keeps them from passing URLs around since they expire (the URL has a token in it).
    • Be warned that it takes time for your app to generate the authorized urls for each image. So, if you have several images on a page, it will affect load time.

提交回复
热议问题