我在将 OAuth 集成逻辑构建到我的 Web 应用程序中时遇到问题。在应用程序中,用户创建一个报告,其中包含来自其谷歌分析帐户的数据。
用户步骤:
- 用户点击“新报告”
- Google 为 OAuth 访问提供“允许访问”页面
- 用户会看到他们的 GA 网络资产列表并选择一个
- 使用来自所选网络媒体资源的数据创建报告
我的问题在于构建下面的代码。
当用户点击“New Report”时,他们实际上被重定向google_analytics#ga_session
到开始授权过程。检索用户网络属性的代码成功,但底部的代码需要重构,以便在检索网络属性数据时可重用。我无法弄清楚的两个主要问题是如何使 GoogleAnalytics 实例可重用以及如何构建 oauth 重定向。
检索网络属性:
谷歌分析控制器
def ga_session
client = OAuth2::Client.new(ENV['GA_CLIENT_ID'], ENV['GA_SECRET_KEY'], {
:authorize_url => 'https://accounts.google.com/o/oauth2/auth',
:token_url => 'https://accounts.google.com/o/oauth2/token'
})
redirect_to client.auth_code.authorize_url({
:scope => 'https://www.googleapis.com/auth/analytics.readonly',
:redirect_uri => ENV['GA_OAUTH_REDIRECT_URL'],
:access_type => 'offline'
})
end
def oauth_callback
session[:oauth_code] = params[:code]
redirect_to new_report_path
end
报告控制器
def new
@report = Report.new
ga_obj = GoogleAnalytics.new
ga_obj.initialize_ga_session(session[:oauth_code])
@ga_web_properties = ga_obj.fetch_web_properties
end
谷歌分析模型
def initialize_ga_session(oauth_code)
client = OAuth2::Client.new(ENV['GA_CLIENT_ID'], ENV['GA_SECRET_KEY'], {
:authorize_url => 'https://accounts.google.com/o/oauth2/auth',
:token_url => 'https://accounts.google.com/o/oauth2/token'
})
access_token_obj = client.auth_code.get_token(oauth_code, :redirect_uri => ENV['GA_OAUTH_REDIRECT_URL'])
self.user = Legato::User.new(access_token_obj)
end
def fetch_web_properties
self.user.web_properties
end
检索网络媒体资源数据:创建报告时
报告控制器
def create
@report = Report.new(params[:report])
@report.get_top_traffic_keywords(session[:oauth_code])
create!
end
报告模型
def get_keywords(oauth_code)
ga = GoogleAnalytics.new
ga.initialize_ga_session(oauth_code) # this is a problem b/c the user will be redirected the new_report_path after the callack
self.url = ga.fetch_url(self.web_property_id)
self.keywords = # Get keywords for self.url from another service
keyword_revenue_data(oauth_code)
end
def keyword_revenue_data(oauth_code)
ga = GoogleAnalytics.new
ga.initialize_ga_session(oauth_code)
revenue_data = # Get revenue data
end