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

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

我想为我们的 Google Apps 服务的用户自动创建文档。
注意事项:

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

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

最佳答案

我能够使用“服务帐户”和 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似乎最有用。

关于ruby - 作为 Google Apps 管理员,如何使用 Ruby 为用户创建 Google 电子表格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13352317/

相关文章:

android - 如何判断 Play Integrity 判决中的证书 SHA-256 摘要是否有效?

google-apps-script - 可以使用 Google 脚本集成到 Google Drive UI

android - Google Drive Android API 和跨客户端授权

ruby - gem_original_require' : no such file to load -- sinatra (LoadError)

ruby-on-rails - 您如何跟踪 View 的页面浏览量

带字符串的 Ruby switch 语句

ruby - 这是正常的吗? ruby 的 CPU 使用率 50%?

php - 将事件页面与谷歌日历同步

android - 使用 Amazon Web Services (AWS) 简单通知服务 (SNS) 设置 Google Cloud Messenging (GCM)

python - 使用 Drive API 编辑 Google 文档