Skip to content
This repository was archived by the owner on Jan 5, 2019. It is now read-only.

Commit 1a4f6a8

Browse files
authored
override the Sufia::Analytics module to load config with ERB parsing (#1468)
1 parent bc06723 commit 1a4f6a8

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

app/services/sufia/analytics.rb

+50
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
require 'google/api_client'
2+
require 'oauth2'
3+
require 'legato'
4+
5+
module Sufia
6+
module Analytics
7+
# Loads configuration options from config/analytics.yml. Expected structure:
8+
# `analytics:`
9+
# ` app_name: GOOGLE_OAUTH_APP_NAME`
10+
# ` app_version: GOOGLE_OAUTH_APP_VERSION`
11+
# ` privkey_path: GOOGLE_OAUTH_PRIVATE_KEY_PATH`
12+
# ` privkey_secret: GOOGLE_OAUTH_PRIVATE_KEY_SECRET`
13+
# ` client_email: GOOGLE_OAUTH_CLIENT_EMAIL`
14+
# @return [Hash] A hash containing five keys: 'app_name', 'app_version', 'client_email', 'privkey_path', 'privkey_secret'
15+
def self.config
16+
@config ||= YAML.load(ERB.new(File.read(File.join(Rails.root, 'config', 'analytics.yml'))).result)['analytics']
17+
end
18+
19+
# Generate an OAuth2 token for Google Analytics
20+
# @return [OAuth2::AccessToken] An OAuth2 access token for GA
21+
def self.token
22+
scope = 'https://www.googleapis.com/auth/analytics.readonly'
23+
client = Google::APIClient.new(application_name: self.config['app_name'],
24+
application_version: self.config['app_version'])
25+
key = Google::APIClient::PKCS12.load_key(self.config['privkey_path'],
26+
self.config['privkey_secret'])
27+
service_account = Google::APIClient::JWTAsserter.new(self.config['client_email'], scope,
28+
key)
29+
client.authorization = service_account.authorize
30+
oauth_client = OAuth2::Client.new('', '', {
31+
authorize_url: 'https://accounts.google.com/o/oauth2/auth',
32+
token_url: 'https://accounts.google.com/o/oauth2/token'})
33+
OAuth2::AccessToken.new(oauth_client, client.authorization.access_token)
34+
end
35+
36+
# Return a user object linked to a Google Analytics account
37+
# @return [Legato::User] A user account wit GA access
38+
def self.user
39+
Legato::User.new(self.token)
40+
end
41+
42+
# Return a Google Analytics profile matching specified ID
43+
# @ return [Legato::Management::Profile] A user profile associated with GA
44+
def self.profile
45+
self.user.profiles.detect do |profile|
46+
profile.web_property_id == Sufia.config.google_analytics_id
47+
end
48+
end
49+
end
50+
end

0 commit comments

Comments
 (0)