Search code examples
rubygoogle-apigoogle-api-ruby-client

Update user photo in G Suite


I am trying to update the user photo for a G Suite user using the following code:

require 'google/apis/admin_directory_v1'
require 'googleauth'
require 'googleauth/stores/file_token_store'

require 'fileutils'

OOB_URI = 'urn:ietf:wg:oauth:2.0:oob'
CLIENT_SECRETS_PATH = 'client_secrets.json'
CREDENTIALS_PATH = File.join(Dir.home, '.credentials',
                             "admin-directory_v1-ruby-quickstart.yaml")
SCOPE = "https://www.googleapis.com/auth/admin.directory.user"    

def authorize
  FileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH))

  client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)
  token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)
  authorizer = Google::Auth::UserAuthorizer.new(
    client_id, SCOPE, token_store)
  user_id = 'default'
  credentials = authorizer.get_credentials(user_id)
  if credentials.nil?
    url = authorizer.get_authorization_url(
      base_url: OOB_URI)
    puts "Open the following URL in the browser and enter the " +
         "resulting code after authorization"
    puts url
    code = gets
    credentials = authorizer.get_and_store_credentials_from_code(
      user_id: user_id, code: code, base_url: OOB_URI)
  end
  credentials
end

# Initialize the API
service = Google::Apis::AdminDirectoryV1::DirectoryService.new
service.authorization = authorize

require "base64"    
pic = Base64.encode64(File.read('profilepic.png')).tr("+/", "-_")

photo = Google::Apis::AdminDirectoryV1::UserPhoto.new
photo.photo_data = pic

service.update_user_photo("user@domain.com", photo)

But then I'm getting the error "invalid: Invalid Input: photoData (Google::Apis::ClientError)". I am starting to suspect that this might be a bug on the Client Library but I want to check first if someone else performed this successfully.

I have been able to update the photo in the "Try it!" section here using the base64 encoded string returned by pic = Base64.encode64(File.read('profilepic.png')).tr("+/", "-_") and I have been able to do it using the PHP Client Library. Am I correct in thinking this is a bug?


Solution

  • I know this is a very old question, but I was having the same problem and it turns out the google-api-client library automatically base64 encodes/decodes your photo_data, so you just need to pass it the file data instead of encoding it, otherwise it gets encoded twice and you'll experience a 400 error.

    # Read file
    photo_data = File.read(image_path)
    
    # Create a UserPhoto object
    user_photo_object = Google::Apis::AdminDirectoryV1::UserPhoto.new(photo_data: photo_data)
    
    # Update Photo
    directory.update_user(user_key, user_photo_object)