0

The Application

I am writing an application that requires getting the pictures from users and saving them in AWS S3 bucket.

app/models/picture.rb

class Picture < ActiveRecord::Base

  include Paperclip::Glue

  belongs_to :user

  scope :active_objects, -> { where(is_deleted: false)}

  has_attached_file :image,

  :styles => {:medium => "800>", :small => "480>", :thumb => "100>"},
  :convert_options => {:medium =>'-quality 90', :small =>'-quality 80', :thumb => '-quality 50' },
  :storage => :s3,
  :url => ":s3_domain_url",
  :path => 'pictures/:id/image/:style/:basename.:extension',
  # :s3_permissions => :private,
  :s3_region => 's3-ap-southeast-1.amazonaws.com',
  :s3_endpoint => 's3-ap-southeast-1.amazonaws.com',
  :s3_credentials => Proc.new { |a| a.instance.s3_credentials }

  def s3_credentials
    {:bucket => App.secrets.bucket_name, :access_key_id => App.secrets.aws_access_key_id, 
      :secret_access_key => App.secrets.aws_secret_access_key}
  end

  def url(style_name = :original, time = 30.minutes.to_i)
    image.s3_permissions == :private ? (image.expiring_url(time, style_name)) : (image.url(style_name))
  end

end

Problem

As you can see, I had set s3_permissions to true and for accessing those pictures I used expiring_url method. Now, I want to make the pictures public so I commented s3_permissions.

After uploading a new picture, I could access the picture without using the expiring_url method

>> Picture.last.url

and the url in the response opens up an image in browser tab but still the images that had been uploaded earlier (Picture.first) are not accessible. When I try to open the url, it gives me this

<Error>
<Code>AccessDenied</Code>
<Message>Access Denied</Message>
<RequestId>6423906A78A3FDFF</RequestId>
<HostId>
fowfNEi6+mM265iGig+jhT1/ih2P7yhPzNegHiS9Q6NrP4mnGNKkXFDefLva85tjAQ0uNbenYew=
</HostId>
</Error>

Also, their s3_permissions are coming as public_read.

>> Picture.first.image.s3_permissions
A, [2018-05-01T01:18:05.171381 #94266]   ANY -- : 2018-05-01 01:18:05 +0530 severity=DEBUG, Picture Load (0.7ms)  SELECT  "pictures".* FROM "pictures" ORDER BY "pictures"."id" ASC LIMIT $1  [["LIMIT", 1]]
=> :public_read

1 Answers1

0

You have to configure this access on the S3 side.

Put this in your bucket policy:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "PublicReadGetObject",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::your_bucket_name/*"
        }
    ]
}
Bitwise
  • 8,021
  • 22
  • 70
  • 161
  • 1
    Hi, Thank you for your answer. Could you please also explain what this code would do? Also, after putting this in my bucket policy, would my private images show their s3_permissions as :private? – Ankit Sharma May 01 '18 at 18:39