Search code examples
rubygoogle-cloud-storagegoogle-api-ruby-client

Ruby google storage API change SHARED PUBLICLY


I have a question regarding ruby google API.

I was trying to use Google storage to host images. I want to make every user to be able to read the images. So far I can connect to google cloud storage and upload an image to Storage. However, I cannot change the permission through API, the codes I used as following:

 def build_client
  client = Google::APIClient.new()

  key = Google::APIClient::PKCS12.load_key('client.p12', 'notasecret')

  service_account = Google::APIClient::JWTAsserter.new(
      '553281084416-og1purkefp0md0g9n5kvlko8e74qm42v@developer.gserviceaccount.com',
      'https://www.googleapis.com/auth/devstorage.full_control',
  key)

  client.authorization = service_account.authorize
  client
end

def send_image_file(file_path, upload_file_name, client)
    storage = client.discovered_api('storage', 'v1beta2')
    media = Google::APIClient::UploadIO.new(file_path, 'image/*')
    result = client.execute(
      api_method: storage.objects.insert,
      media: media,
      parameters: {
        uploadType: 'media',
        predefinedAcl: 'publicRead',
        bucket: 'portlight_images',
        name: upload_file_name,
        projection: 'full'
      }
    )
    result
end

I use the (predefinedAcl: 'publicRead') to change the ACL, but it won't do anything. When I want to use the url like : "https://console.developers.google.com/m/cloudstorage/b/#{bucket}/o/#{object}" to access the image, I'll have to manually click the button on the storage console to make it "SHARED PUBLICLY".

I would like to know is there any way I can get the link public to everyone through API. Thanks.


Solution

  • you probably have solved this already, but just for anyone else who faces the same issue: you must set the acl key and value within the body object at client.execute.

    result = client.execute(
      api_method: storage.objects.insert,
      media: media,
      parameters: {
        uploadType: 'multipart',
        bucket: 'portlight_images',
        name: upload_file_name,
        projection: 'full',
        acl: 'public-read'
      },
     :body_object => {
        'acl' => [{
            'entity' => 'allUsers',
            'role' => 'READER'  
        }],
        'bucket' => portlight_images,
        'object' => upload_file_name
      }
    )