-
Notifications
You must be signed in to change notification settings - Fork 9
/
budgea.rb
327 lines (280 loc) · 11.8 KB
/
budgea.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
# encoding: UTF-8
# MIT License
#
# Copyright (c) 2014-2020 Budget Insight
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
begin
require 'rubygems'
require 'rest_client'
rescue LoadError
puts %{
I'm so sorry to ask you for the rest_client gem. \
In fact ruby has no efficent HTTP client at this time (w/o big bug or missing feature)
$ gem install rest_client -v 1.7.3
}
exit 1
end
require 'base64'
require 'open-uri'
require 'json'
# Usage
#
# Normal flow with `client_id` and `client_secret`
# ```
# require 'budgea'
# management_token = "XXXXXX"
# budgea_client = Budgea::Client.new 'XXX.biapi.pro', { client_id: ENV['BUDGEA_CLIENT_ID'],
# client_secret: ENV['BUDGEA_CLIENT_SECRET'],
# redirect_uri: 'https://lvh.me:3000/user/settings' }
#
# puts client.get_authentication_url('', types: 'providers') # Example with a 'provider' Webview
# puts client.get_authentication_button('', types: 'providers') # Example with a 'provider' Webview
# ```
#
# With a management token
# ```
# require 'budgea'
# management_token = "XXXXXX" # TODO LIEN VERS PAGE MANAGEMENT TOKEN
# budgea_client = Budgea::Client.new 'XXXXXX.biapi.pro', { access_token: management_token, access_token_type: 'bearer' }
#
# budgea_client.get('/clients') # Adminitration endpoints in API Reference
# ```
module Budgea
class Client
VERSION = '2.1.0'.freeze
attr_accessor :client_id
attr_accessor :client_secret
attr_accessor :access_token
attr_writer :access_token_type
def access_token_type
@access_token_type || 'bearer'
end
def initialize(domain, settings = {})
@settings = {
connect_endpoint: '/auth/webview/connect',
manage_endpoint: '/auth/webview/manage',
token_endpoint: '/auth/token/access',
code_endpoint: '/auth/token/code',
base_url: "https://#{domain}/2.0",
http_headers: { 'User-Agent': "BudgeaAPI Client #{VERSION}" },
client_id: nil,
client_secret: nil,
access_token_param_name: 'token',
redirect_uri: nil,
transfer_endpoint: '/auth/webview/transfer',
transfer_redirect_uri: nil
}.merge(settings)
@access_token = @settings[:access_token] ? @settings[:access_token] : nil
@access_token_type = @settings[:access_token_type] ? @settings[:access_token_type] : 'bearer'
end
def handle_callback(params = {})
raise AuthFailed, params['error'] || 'Authentication failed' if params['error']
return false unless params.key?('code')
new_params = { code: params['code'], redirect_uri: @settings[:redirect_uri], grant_type: 'authorization_code' }
uri = URI.parse(@settings[:base_url] + @settings[:token_endpoint])
#::RestClient.proxy = 'http://localhost:8888'
resource = ::RestClient::Resource.new uri.to_s, @settings[:client_id], @settings[:client_secret]
response = resource.post(new_params)
raise ConnectionError, 'Can’t reach remote URI' unless response.code == 200
json_response = JSON.parse response.to_str
raise AuthFailed, json_response['error'] || 'Authentication failed' if json_response['error']
@access_token = json_response['access_token']
@access_token_type = json_response['token_type']
params[:state] || true
end
# Method: get_connect_url
#
# Parameter `connector_capabilities` can be either `bank` or `document`
# Default value is `bank`, no need to specify it in this case
#
# Usage:
# client.get_connect_url('') # Add a bank
# OR
# client.get_connect_url('', connector_capabilities: 'document') # Add a provider
#
def get_connect_url(state = '', connector_capabilities: nil)
query_string_params = {
response_type: 'code',
client_id: @settings[:client_id],
redirect_uri: @settings[:redirect_uri],
state: state
}
query_string_params[:connector_capabilities] = connector_capabilities.to_s if connector_capabilities.present?
endpoint_uri_with_params(@settings[:authorization_endpoint], query_string_params)
end
# Compatibility alias for get_connect_url
def get_authentication_url(state = '', connector_capabilities: nil)
get_connect_url(state, connector_capabilities)
end
# Usage
# client.get_connect_button('Partager ses comptes') # Add a bank
# OR
# client.get_connect_button('Partager ses fournisseurs', connector_capabilities: 'document') # Add a provider
#
def get_connect_button(text, connector_capabilities: nil)
authentication_url = get_connect_url('', connector_capabilities: connector_capabilities)
button = "
<a href='#{authentication_url}'
style=\"display: inline-block; background: #ff6100; padding: 8px 16px; border-radius: 4px; color: white; text-decoration: none; font: 12pt/14pt 'Roboto', sans-serif\">
#{text}
</a>"
button.html_safe
end
# Compatibility alias for get_connect_url
def get_authentication_button(text, connector_capabilities: nil)
get_connect_button(text, connector_capabilities)
end
def get_manage_url(state = '', connector_capabilities: nil)
code_endpoint_response = get(@settings[:code_endpoint])
code_endpoint_response = JSON.parse(code_endpoint_response) if code_endpoint_response.is_a?(String)
query_string_params = {
response_type: 'code',
client_id: @settings[:client_id],
redirect_uri: @settings[:redirect_uri],
state: state,
code: code_endpoint_response['code']
}
query_string_params[:connector_capabilities] = connector_capabilities.to_s if connector_capabilities.present?
endpoint_uri_with_params(@settings[:authorization_endpoint], query_string_params)
end
# Compatibility alias for get_manage_url
def get_settings_url(text, connector_capabilities: nil)
get_manage_url(text, connector_capabilities)
end
def get_transfer_url(state = '')
code_endpoint_response = get(@settings[:code_endpoint])
code_endpoint_response = JSON.parse(code_endpoint_response) if code_endpoint_response.is_a?(String)
query_string_params = {
redirect_uri: @settings[:transfer_redirect_uri],
state: state,
code: code_endpoint_response['code']
}
endpoint_uri_with_params(@settings[:transfer_endpoint], query_string_params)
end
# Compatibility alias for get_transfer_url
def get_transfers_url(state = '')
get_transfer_url(text, connector_capabilities)
end
def get(uri, params = {})
fetch(uri, params)
end
def fetch(uri, params = {}, method = :get, http_headers = {})
http_headers.merge!(@settings[:http_headers])
# http_headers.merge!({:content_type => :json, :accept => :json})
http_headers[:accept] = :json
if @access_token
case @access_token_type
when 'url'
raise ArgumentException, 'You need to give parameters as Hash if you want to give the token within the URI.' unless params.is_a?(Hash)
params[@access_token_param_name] = @access_token
when 'bearer'
http_headers['Authorization'] = "Bearer #{@access_token}"
when 'oauth'
http_headers['Authorization'] = "OAuth #{@access_token}"
else
raise InvalidAccessTokenType, "Invalid access token type: #{@access_token_type}"
end
end
# RestClient.proxy = 'http://localhost:8888'
uri = absurl(uri)
ressource = RestClient::Resource.new uri.to_s
response = nil
begin
final_params = params.merge(http_headers)
response = ressource.send(method, params.merge(final_params))
rescue RestClient::Exception => e
message = JSON.parse(e.response.to_str)
raise(AuthRequired, message) if response.code.in?([401, 403])
return message
end
if response.headers[:content_type] == 'application/json'
JSON.parse(response.to_str)
else
response.to_str
end
end
def get_accounts(_expand = nil)
ret = get('/users/me/accounts')
ret['accounts'] ? ret['accounts'].map { |account| Account.new(self, account) } : ret
end
def get_transactions(account_id = nil)
ret = if account_id
get("/users/me/accounts/#{account_id}/transactions", 'expand' => 'category')
else
get('/users/me/transactions/', 'expand' => 'category')
end
ret['transactions'] ? ret['transactions'].map { |transaction| Transaction.new(self, transaction) } : ret
end
private
def absurl(url)
url.start_with?('http') ? File.join(@settings[:base_url], url) : url
end
def endpoint_uri_with_params(endpoint_path, query_string_params)
endpoint_url = File.join(@settings[:base_url], endpoint_path)
uri = URI.parse(endpoint_url)
uri.query = URI.encode_www_form(query_string_params)
uri.to_s
end
end
class Transaction
attr_reader :id, :date, :value, :nature
attr_reader :original_wording, :simplified_wording, :stemmed_wording
attr_reader :category, :client
attr_reader :state, :date_scraped, :rdate, :coming, :active, :comment
def initialize(client, resp)
@client = client
@id = resp['id']
@date = resp['date']
@value = resp['value']
@nature = resp['nature']
@original_wording = resp['original_wording']
@simplified_wording = resp['simplified_wording']
@stemmed_wording = resp['stemmed_wording']
@category = client.get('category', nil)
@state = resp['state']
@date_scraped = resp['date_scraped']
@rdate = resp['rdate']
@coming = resp['coming']
@active = resp['active']
@comment = resp['comment']
end
end
class Account
attr_reader :client
attr_reader :id, :number, :name, :balance, :last_update
def initialize(client, response)
@client = client
@id = response['id']
@number = response['number']
@name = response['name']
@balance = response['balance']
@last_update = response['last_update']
end
def transactions
ret = client.get_transactions(id)
ret['transactions'] ? ret['transactions'].map { |transaction| Transaction.new(client, transaction) } : ret
end
end
class BudgeaException < RuntimeError; end
class ConnectionError < BudgeaException; end
class InvalidAccessTokenType < BudgeaException; end
class AuthRequired < BudgeaException; end
class AuthFailed < BudgeaException; end
end