Class: Analytic

Inherits:
Object
  • Object
show all
Includes:
ActionView::Helpers::TextHelper, ActionView::Helpers::UrlHelper, ApplicationHelper
Defined in:
app/models/analytic.rb

Instance Method Summary collapse

Methods included from PostsHelper

#breadcrumb, #index_of_posts, #navigation_menu, #read_on, #render_post_content_parts, #render_post_type_content

Methods included from RdcmsHelper

#basic_headers, #bugtracker, #edit_post_link, #errors_for, #flash_message, #language_links, #render_address, #render_footer, #render_header, #s, #social_buttons_json, #social_pages_buttons

Constructor Details

#initialize(settings = {}) ⇒ Analytic

Returns a new instance of Analytic.



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'app/models/analytic.rb', line 6

def initialize(settings={})
  # Merge Configurações padrões com as definidas pelo usuário
  @settings = {
    client_id:        Setting.for_key("rdcms.omniauth.google.key", false),
    client_secret:    Setting.for_key("rdcms.omniauth.google.secret", false),
    scope:            "https://www.googleapis.com/auth/analytics.readonly",
    redirect_uri:     "",
    approval_prompt:  "force",
    response_type:    "code",
    access_type:      "offline",
    token_method:     "post"
  }.merge settings

  @client = nil
  @oauth2 = nil
  @error = nil
  @token = nil
end

Instance Method Details

#authorize_buttonObject

Cria botão para autorização



61
62
63
# File 'app/models/analytic.rb', line 61

def authorize_button
  link_to(I18n.t("admin.analytics.authorize_access"), url_for(get_authorize_url), class: "btn btn-primary")
end

#clientObject



25
26
27
# File 'app/models/analytic.rb', line 25

def client
  return @client
end

#connect(code = nil) ⇒ Object

Salva a token e retorna conexão autenticada code = Código de Autorização fornecido pelo google, necessário para requisição da token



67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'app/models/analytic.rb', line 67

def connect(code=nil)
  # caso o client ainda não ter sido criado, cria-o
  self.create if @client.nil?
  return false if code.nil?

  # Token para permissão de acesso nas requisições
  begin
    @oauth2 = @client.auth_code.get_token(code, redirect_uri: @settings[:redirect_uri])

    Setting.set_value_for_key(@oauth2.token, "rdcms.omniauth.google.token")
    Setting.set_value_for_key(@oauth2.refresh_token, "rdcms.omniauth.google.refresh_token")
    Setting.set_value_for_key(@oauth2.expires_at, "rdcms.omniauth.google.expires_at")
    return @oauth2
  rescue => exception
    @error = I18n.t("error.messages.rest.#{exception.code}") if defined?(exception.code)
    exception
  end
end

#createObject

OAuth2 com os dados da API do google



39
40
41
42
43
44
# File 'app/models/analytic.rb', line 39

def create
  @client = OAuth2::Client.new(
    @settings[:client_id],
    @settings[:client_secret],
    { :site => 'https://accounts.google.com', :authorize_url => "/o/oauth2/auth", :token_url => "/o/oauth2/token" })
end

#destroy!Object

efetua o logout



127
128
129
130
131
132
# File 'app/models/analytic.rb', line 127

def destroy!
  Setting.set_value_for_key("", "rdcms.omniauth.google.token")
  Setting.set_value_for_key("", "rdcms.omniauth.google.refresh_token")
  Setting.set_value_for_key("", "rdcms.omniauth.google.expires_at")
  nil
end

#error?Boolean

Returns:

  • (Boolean)


31
32
33
# File 'app/models/analytic.rb', line 31

def error?
  !@error.nil?
end

#error_messageObject



34
35
36
# File 'app/models/analytic.rb', line 34

def error_message
  @error
end

#get_authorize_urlObject

Gera url para authorização da api



47
48
49
50
51
52
53
54
55
56
57
58
# File 'app/models/analytic.rb', line 47

def get_authorize_url
  # caso o client ainda não ter sido criado, cria-o
  self.create if @client.nil?

  @client.auth_code.authorize_url(
    redirect_uri:     @settings[:redirect_uri],
    response_type:    @settings[:response_type],
    scope:            @settings[:scope],
    approval_prompt:  @settings[:approval_prompt],
    access_type:      @settings[:access_type]
    )
end

#get_json(url, data = {}) ⇒ Object

Faz a requisição



115
116
117
118
119
120
121
122
123
124
# File 'app/models/analytic.rb', line 115

def get_json(url, data={})
  return false if !defined?(url) or url.blank?

  begin
    @oauth2.get url, params: data
  rescue OAuth2::Error => exception
    @error = I18n.t("error.messages.rest.#{exception.code["code"]}")
    exception
  end
end

#get_settingsObject



133
134
135
# File 'app/models/analytic.rb', line 133

def get_settings
  @settings
end

#new_oauth(token = nil, opts = {}) ⇒ Object

Atualiza a token



95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
# File 'app/models/analytic.rb', line 95

def new_oauth(token=nil, opts={})
  # caso o client ainda não ter sido criado, cria-o
  self.create if @client.nil?


  Setting.set_value_for_key(token, "rdcms.omniauth.google.token") unless token.blank?

  if defined? opts
    Setting.set_value_for_key(opts[:expires_at], "rdcms.omniauth.google.expires_at") unless opts[:expires_at].blank?
    Setting.set_value_for_key(opts[:refresh_token], "rdcms.omniauth.google.refresh_token") unless opts[:refresh_token].blank?
  end

  token ||= Setting.for_key("rdcms.omniauth.google.token", false)
  opts = {:refresh_token  => Setting.for_key("rdcms.omniauth.google.refresh_token", false),
          :expires_at     => Setting.for_key("rdcms.omniauth.google.expires_at", false).to_i}.merge opts

  @oauth2 = OAuth2::AccessToken.new @client, token, opts
end

#oauth2Object



28
29
30
# File 'app/models/analytic.rb', line 28

def oauth2
  return @oauth2
end

#refreshToken!Object

Atualiza a token



87
88
89
90
91
92
# File 'app/models/analytic.rb', line 87

def refreshToken!
  oauth = @oauth2.refresh!

  # Atualizando AccessToken existente
  new_oauth oauth.token, { :expires_at => oauth.expires_at }
end