Rails service + oauth code structure

I am having a problem structuring the OAuth integration logic in my web application. In the application, the user creates a report that consists of data from his Google Analytics account.

User Response:

  • User clicks "New Report"
  • Google introduces the Allow Access page to access OAuth.
  • The user gets a list of their GA network properties and selects
  • The report is created using data from the selected web resource

My problem is structuring the code below.

When a user clicks New Report, they are actually redirected to google_analytics#ga_session to begin the authorization process. The code to restore the properties of the website completed successfully, but the code below must be reorganized so that it can be reused when retrieving the web properties. The main two questions that I cannot understand are how to make the GoogleAnalytics instance reusable and how to structure oauth redirects.

Get web properties:

GoogleAnalyticsController

 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 

ReportsController

 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 

GoogleAnalytics Model

 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 

Get web property data when creating a report

ReportsController

 def create @report = Report.new(params[:report]) @report.get_top_traffic_keywords(session[:oauth_code]) create! end 

Report Model

 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 
+1
source share

Source: https://habr.com/ru/post/1483659/


All Articles