Class: RHACK::OAuthClient

Inherits:
Client show all
Defined in:
lib/rhack/clients/oauth.rb

Instance Attribute Summary collapse

Attributes inherited from Client

#f, #service, #storage

Instance Method Summary collapse

Methods inherited from Client

#account, #go, inherited, #inspect, #login, method_missing, #route, #scrape!, store

Constructor Details

#initialize(*args) ⇒ OAuthClient

Returns a new instance of OAuthClient.



22
23
24
25
26
27
28
29
# File 'lib/rhack/clients/oauth.rb', line 22

def initialize *args
  @users_data = {}
  @oauth_tokens = {}
  @oauth_states_users = {}
  @storage = self.class.storage
  service, frame, opts = args.get_opts [:api, nil], {}
  super service, frame, {cp: false, wait: true, json: true, scouts: 1}.merge(opts)
end

Instance Attribute Details

#oauth_tokensObject (readonly)

Returns the value of attribute oauth_tokens.



16
17
18
# File 'lib/rhack/clients/oauth.rb', line 16

def oauth_tokens
  @oauth_tokens
end

#users_dataObject

just a buffer for one action @ => hash<last used user data>



20
21
22
# File 'lib/rhack/clients/oauth.rb', line 20

def users_data
  @users_data
end

Instance Method Details

#api(action, *args, &block) ⇒ Object

Если придёт мысль делать враппер клиента по запросу

@ action : url or reference to ::API @ args :

token : token or state_params
action_params : smth to append to url


165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
# File 'lib/rhack/clients/oauth.rb', line 165

def api(action, *args, &block)
  if action_data = API(action)
    action, scope = action_data.values_at :path, :scope
    app_token = action_data[:token] == :application
  end
  token, opts = args.get_opts [app_token ? ['__app__'] : ['__default__']]
  opts = opts.symbolize_keys
  action_params = opts.delete(:params) || {}
  redirect_params = opts.extract!(:redirect_protocol)
  
  if token.is Array 
    token[1] ||= scope
    state_params = token
    L.debug state_params
    request_params = [token[0], (token[1] ? {scope: token[1]} : {}).merge(redirect_params)]
    L.debug request_params
    token = validate(*request_params)
    if token.is Hash
      L.debug token
      if block
        return {res: block.(token)}
      else
        return token
      end
    end
  end
  unless token
    raise NoTokenError
  end
  
  L.debug state_params
  action += '?' if !action['?']
  action += action_params.urlencode
  L.debug [action_data, action, token]
  opts = {proc_result: block, headers: {'Referer' => nil}, result: CodeIndiffirentPage}.merge(opts)
  # TODO: option to 
  @f.run(route(:api) % {action: action} + token, opts) {|page|
    if page.hash and page.hash != true and error = page.hash.error
      L.debug state_params
      if error.code.in([190, 100]) and state_params
        user_data state_params, :clear
        L.warn error.message
        if request_params
          {oauth_url: get_oauth_url(*request_params)}
        end
      else
        raise OAuthError, error.message
      end
    else
      page
    end
  }
end

#get_application_oauth_token(&block) ⇒ Object



143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
# File 'lib/rhack/clients/oauth.rb', line 143

def get_application_oauth_token(&block)
  @f.run(route(:oauth)[:token] + {
    grant_type: 'client_credentials',
    client_id: OAUTH(:id), 
    client_secret: OAUTH(:secret)
  }.urlencode, raw: true, proc_result: block) {|curl|
    if curl.res.code == 200
      body = curl.res.body
      hash = '{['[body[0]] ? body.from_json(symbolize_keys: true) : body.to_params
      user_data(['__app__', nil], [hash.access_token])[0]
    else
      raise OAuthError, curl.res.body
    end
  }
end

#get_oauth_token(url_params = {}, &block) ⇒ Object

@ url_params : :state, …



102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
# File 'lib/rhack/clients/oauth.rb', line 102

def get_oauth_token(url_params={}, &block)
  state = url_params.delete :state
  L.debug state
  if state_params = @oauth_states_users[state]
    if data = user_data(state_params)
      # code is allready used, return token
      return data[0]
    end
  else
    raise StateError, "Couldn't find user authentication state. Please, retry authorization from start"
  end
  
  url_params[:redirect_uri] = OAUTH(:landing).dup
  L.debug url_params
  if redirect_protocol = url_params.delete(:redirect_protocol)
    url_params[:redirect_uri].sub!(/^\w+/, redirect_protocol)
  end
  L.debug url_params
  @f.run({}, route(:oauth)[:token] + {
    grant_type: 'authorization_code',
    client_id: OAUTH(:id), 
    client_secret: OAUTH(:secret)
  }.merge(url_params).urlencode, raw: true, proc_result: block) {|curl|
    L.debug curl.res
    L.debug curl.res.body
    # TODO: refactor parse type selector: raw, json, hash, xml...
    # from_json -> (symbolize_keys: true)
    if curl.res.code == 200
      body = curl.res.body
      hash = '{['[body[0]] ? body.from_json(symbolize_keys: true) : body.to_params
      token = hash.access_token
      data = [token, Time.now.to_i + (hash.expires || hash.expires_in).to_i]
      L.debug token
      user_data(state_params, data)
      token
    else
      raise OAuthError, curl.res.body
    end
  }
end

#get_oauth_url(user_id = '__default__', url_params = {}) ⇒ Object

usually called internally



84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# File 'lib/rhack/clients/oauth.rb', line 84

def get_oauth_url(user_id='__default__', url_params={})
  state = String.rand(64)
  @oauth_states_users[state] = [user_id, url_params[:scope]]
  # TODO: change it with something more consious
  url_params[:redirect_uri] = OAUTH(:landing).dup
  L.debug url_params
  if redirect_protocol = url_params.delete(:redirect_protocol)
    url_params[:redirect_uri].sub!(/^\w+/, redirect_protocol)
  end
  L.debug url_params
  @oauth_url = route(:oauth)[:auth] + {
    response_type: 'code', 
    client_id: OAUTH(:id),
    state: state
  }.merge(url_params).urlencode
end

#user_data(state_params, data = nil) ⇒ Object

@ state_params : [string<user_id>, (strings*“,”)<scope>] persistent: state_params -> [string token, int expires]



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/rhack/clients/oauth.rb', line 64

def user_data(state_params, data=nil)
  key = "#{self.class.name.sub('RHACK::', '').underscore}:tokens"
  if data
    if data == :clear
      @oauth_tokens.delete state_params
      $redis.hdel key, state_params*':'
    else
      @oauth_tokens[state_params] = data
      $redis.hset key, state_params*':', data*','
    end
  elsif !@oauth_tokens[state_params]
    if data = $redis.hget(key, state_params*':')
      token, expire = data/','
      @oauth_tokens[state_params] = [token, expire.to_i]
    end
  end
  @users_data[state_params[0]] = @oauth_tokens[state_params]
end

#validate(user_id, url_params = {}) ⇒ Object

TODO:



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/rhack/clients/oauth.rb', line 36

def validate(user_id, url_params={})
  if action = url_params.delete(:action)
    if action_params = API(action)
      url_params = action_params.slice(:scope).merge(url_params)
    end
  end
  if data = user_data([user_id, url_params[:scope]])
    token, expires = data
    if user_id != '__app__'
      if token and expires
        # substracting a minute so that "last moment" request wouldn't fail
        if expires - 60 < Time.now.to_i
          token = false
        end
      else
        token = false
      end
    end
  end
  if token
    block_given? ? yield(token) : token
  else
    {oauth_url: get_oauth_url(user_id, url_params)}
  end
end