如何为使用Ruby的用户创建Google电子表格,作为Google Apps管理员?

时间:2012-11-12 22:01:54

标签: ruby google-api google-drive-api google-sheets google-apps

我想为Google Apps服务的用户自动创建文档 考虑:

  • 无法为用户启用OAuth
  • 我有超级管理员API访问权限
  • 我只知道用户的电子邮件地址

这可以通过现有的Ruby库实现吗? (大多数人使用2-legged auth来完成此操作,而不是管理员。)

1 个答案:

答案 0 :(得分:1)

我能够通过“服务帐户”和Google的(alpha)gem google-api-client完成此操作。这是一个Ruby类,从不同的Google文档中采样,在实例化时收集用户的电子邮件(来自您管理的Google Apps域)。

require 'google/api_client'

class GoogleDriveConnection
  def initialize(user_email=nil)
    @client = Google::APIClient.new
    @drive = @client.discovered_api('drive', 'v2')

    key_file_name = '<DOWNLOADED WHEN CREATING A SERVICE ACCOUNT>.p12'
    key = Google::APIClient::PKCS12.load_key("#{Rails.root.to_s}/config/#{key_file_name}", 'notasecret')

    asserter = Google::APIClient::JWTAsserter.new(
      '<THE EMAIL ADDRESS OF YOUR SERVICE ACCOUNT>',
      'https://www.googleapis.com/auth/drive',
    key)

    @client.authorization = asserter.authorize(user_email)
  end

  def insert_file(title, description, parent_id, mime_type, file_name)
    file = @drive.files.insert.request_schema.new({
      'title' => title,
      'description' => description,
      'mimeType' => mime_type
    })
    # Set the parent folder.
    if parent_id
      file.parents = [{'id' => parent_id}]
    end
    media = Google::APIClient::UploadIO.new(file_name, mime_type)
    result = @client.execute(
      :api_method => @drive.files.insert,
      :body_object => file,
      :media => media,
      :parameters => {
        'uploadType' => 'multipart',
        'convert' => true,
        'alt' => 'json'})
    if result.status == 200
      return result.data
    else
      puts "An error occurred: #{result.data['error']['message']}"
      return nil
    end
  end

  def list_files
    result = @client.execute!(:api_method => @drive.files.list)
    result.data.to_hash
  end

  def get_file(file_id)
    result = @client.execute!(
      :api_method => @drive.files.get,
      :parameters => { 'fileId' => file_id })
    result.data.to_hash
  end

  private

    def token
      @client.authorization.access_token
    end
end

用法很简单:

g = GoogleDriveConnection.new('me@mycompany.com')
g.insert_file('My file', 'File stuff', nil, 'text/csv', "#{Rails.root}/tmp/test.csv")

*创建服务帐户并管理“API项目”非常棘手。 This guide似乎最有用。