Ruby on rails 理解用于Google API客户端身份验证的Ruby示例文件时遇到的问题
我正在尝试从我的Rails应用程序访问Google API。 我了解Web应用程序的OAuth2.0的基本流程。 我认为自己对Ruby和Rails有了基本的了解 然而,我无法理解谷歌在“”指南中展示的例子 当然,这看起来像Ruby,但我从未见过这里使用的一些构造,我也不确定在Rails应用程序中,这些代码会用到哪里Ruby on rails 理解用于Google API客户端身份验证的Ruby示例文件时遇到的问题,ruby-on-rails,ruby,google-api-ruby-client,Ruby On Rails,Ruby,Google Api Ruby Client,我正在尝试从我的Rails应用程序访问Google API。 我了解Web应用程序的OAuth2.0的基本流程。 我认为自己对Ruby和Rails有了基本的了解 然而,我无法理解谷歌在“”指南中展示的例子 当然,这看起来像Ruby,但我从未见过这里使用的一些构造,我也不确定在Rails应用程序中,这些代码会用到哪里 是红宝石吗?如果是,我该如何使用它?是的,这是ruby。您现在看到的是一个基于sinatra的示例实现,这是一个没有rails开销的普通功能。谢谢,很高兴知道。不明白为什么他们使用S
是红宝石吗?如果是,我该如何使用它?是的,这是ruby。您现在看到的是一个基于sinatra的示例实现,这是一个没有rails开销的普通功能。谢谢,很高兴知道。不明白为什么他们使用Sinatra作为Ruby示例的基础。这让我很难理解它。您没有解释是将OAuth2用于web应用程序还是服务器到服务器应用程序,但我建议您使用非Sinatra示例。
require 'google/apis/calendar_v3'
require 'google/api_client/client_secrets'
require 'sinatra'
require 'logger'
enable :sessions
def logger; settings.logger end
def calendar; settings.calendar; end
def user_credentials
# Build a per-request oauth credential based on token stored in session
# which allows us to use a shared API client.
@authorization ||= (
auth = settings.authorization.dup
auth.redirect_uri = to('/oauth2callback')
auth.update_token!(session)
auth
)
end
configure do
log_file = File.open('calendar.log', 'a+')
log_file.sync = true
logger = Logger.new(log_file)
logger.level = Logger::DEBUG
Google::Apis::ClientOptions.default.application_name = 'Ruby Calendar sample'
Google::Apis::ClientOptions.default.application_version = '1.0.0'
calendar_api = Google::Apis::CalendarV3::CalendarService.new
client_secrets = Google::APIClient::ClientSecrets.load
authorization = client_secrets.to_authorization
authorization.scope = 'https://www.googleapis.com/auth/calendar'
set :authorization, authorization
set :logger, logger
set :calendar, calendar_api
end
before do
# Ensure user has authorized the app
unless user_credentials.access_token || request.path_info =~ /^\/oauth2/
redirect to('/oauth2authorize')
end
end
after do
# Serialize the access/refresh token to the session and credential store.
session[:access_token] = user_credentials.access_token
session[:refresh_token] = user_credentials.refresh_token
session[:expires_in] = user_credentials.expires_in
session[:issued_at] = user_credentials.issued_at
end
get '/oauth2authorize' do
# Request authorization
redirect user_credentials.authorization_uri.to_s, 303
end
get '/oauth2callback' do
# Exchange token
user_credentials.code = params[:code] if params[:code]
user_credentials.fetch_access_token!
redirect to('/')
end
get '/' do
# Fetch list of events on the user's default calandar
events = calendar.list_events('primary', options: { authorization: user_credentials })
[200, {'Content-Type' => 'application/json'}, events.to_h.to_json]
end