mints 0.0.4 → 0.0.9

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: ef89ee973a9cb2bf2e4b77ad15e3481f7fc02e566f47099c7c44b94bdd3cb757
4
- data.tar.gz: d40cf8e0445ce333ad735403f767622cc6428b7ab4f334040a542b0340d4eb49
3
+ metadata.gz: 91ef0909fa4361a6a3644378c438c64341bfbf31bc6d9ef7f0ed178bd35b5dac
4
+ data.tar.gz: 0a4c5c14a4550ac56917259ecc822d9afbe779e95507f9607c9248ce19c53caa
5
5
  SHA512:
6
- metadata.gz: d8c404e2894b99bdb95a5db340ca9f47785cfec00fa6c3648b29a9b1c00e65a4a02569ccfdd5086e1911e468c942e93db214d21d2ac11c219934c66d9d3e9478
7
- data.tar.gz: 2c24fc60a2cd29d377bd445cee14fbd611ddc728155eb7e3f2c545eec203100a64254b09e981128f28849dc7a95c1bded45bd592ebe67af3ed794f6e0b786809
6
+ metadata.gz: 1df0f3a2b3f2ff3c27a61221fab855138508991a0ea552e1111f15df723473e5eeb3ec8c46650aa1670bc00bef8242424fd88e20d90c729d12deac15d25453a4
7
+ data.tar.gz: c9fb8c066bdcb38237d394bcef4d155bd8bcc29ac3f19b1f4adb905b7483b678c1dbb1625ba8b31be6cada2b565c465f3da3a1d0e6f62cae50c7cfcbc0bfcf44
data/Gemfile CHANGED
@@ -2,4 +2,6 @@ source :rubygems
2
2
 
3
3
  gem 'json'
4
4
  gem 'httparty'
5
- gem 'addressable'
5
+ gem 'addressable'
6
+ gem 'rails-reverse-proxy', '~> 0.9.1'
7
+ gem 'redis'
data/Readme.md CHANGED
@@ -29,18 +29,56 @@ con = Mints::User.new(mints_url, api_key)
29
29
  con.login(email, password)
30
30
  con.get_contacts
31
31
  ```
32
+ ## Generate mints files
33
+ This command will generate the mints_config.yml file, API controlles and routes to have available the mints endpoints
34
+ ```bash
35
+ rails generate mints_files
36
+ ```
32
37
  ## Contact tracking usage
33
- Your app controller need to be inherited from Mints::BaseController
38
+ Your app controller needs to be inherited from Mints::BaseController
34
39
  ```ruby
35
40
  # application_controller.rb
36
41
 
37
42
  class ApplicationController < Mints::BaseController
38
43
  end
39
44
  ```
40
- This controller will make the following class variables available:
45
+ This heritance will make the following class variables available:
46
+
47
+ | Variable | Description |
48
+ | --- | :---: |
49
+ | @host | Host defined in mints_config.yml file |
50
+ | @api_key | API key defined in mints_config.yml file |
51
+ | @mints_pub | An already instanced public client |
52
+ | @contact_token | A token used by mints to identify the contact |
53
+ | @visit_id | An identifier of the visit registered |
54
+ | @mints_contact | An already instanced contact client (not usable until call the contact login method) |
55
+
56
+ And the following controller methods:
57
+ | Method | Parameters | Return value | Description |
58
+ | --- | :---: | :---: | :---: |
59
+ | mints_contact_signed_in? | none | boolean | Indicates if the contact has an active session |
60
+ | mints_contact_login | email, password| void | Starts a contact session |
61
+ | mints_contact_logout | none | void | Ends a contact session |
62
+
63
+ ## Admin controller usage
64
+ If want to have a private section where only a mints user can acces and use the private user api is needed to inherit from the AdminBaseController.
65
+
66
+ ```ruby
67
+ # admin_controller.rb
68
+
69
+ class AdminController < Mints::AdminBaseController
70
+ end
71
+ ```
72
+
73
+ This heritance will make the following class variables available:
74
+ | Variable | Description |
75
+ | --- | :---: |
76
+ | @host | Host defined in mints_config.yml file |
77
+ | @api_key | API key defined in mints_config.yml file |
78
+ | @mints_user | An already instanced user client (not usable until call the user login method) |
41
79
 
42
- | Variable | Description |
43
- | --- | :---: |
44
- | @mints_pub | An already instanced public client |
45
- | @contact_token | A token used by mints to identify the contact |
46
- | @visit_id | An identifier of the visit registered |
80
+ And the following controller methods:
81
+ | Method | Parameters | Return value | Description |
82
+ | --- | :---: | :---: | :---: |
83
+ | mints_user_login | email, password| void | Starts a user session |
84
+ | mints_user_logout | none | void | Ends a user session |
@@ -1,6 +1,7 @@
1
1
  require "httparty"
2
2
  require "json"
3
3
  require "addressable"
4
+ require "redis"
4
5
  module Mints
5
6
  class Client
6
7
  attr_reader :host
@@ -9,26 +10,56 @@ module Mints
9
10
  attr_reader :base_url
10
11
  attr_accessor :session_token
11
12
 
12
- def initialize(host, api_key, scope = nil, session_token = nil)
13
+ def initialize(host, api_key, scope = nil, session_token = nil, debug = false)
13
14
  @host = host
14
15
  @api_key = api_key
15
16
  @session_token = session_token
17
+ @debug = debug
16
18
  self.set_scope(scope)
17
19
  end
18
20
 
19
21
  def raw(action, url, options = nil, data = nil, base_url = nil)
20
- base_url = @base_url if !base_url
21
-
22
+ base_url = @base_url if !base_url
23
+ uri = ""
22
24
  if (options && options.class == Hash)
23
25
  uri = Addressable::URI.new
24
26
  uri.query_values = options
25
- else
26
- uri = ""
27
27
  end
28
-
28
+
29
29
  full_url = "#{@host}#{base_url}#{url}#{uri}"
30
- if action === 'get'
31
- response = self.send("#{@scope}_#{action}", "#{full_url}")
30
+ response = nil
31
+ if action === 'get'
32
+
33
+ config = YAML.load_file("#{Rails.root}/mints_config.yml")
34
+ url_need_cache = false
35
+ result_from_cache = false
36
+ time = 0
37
+
38
+ if config['redis_cache']['use_cache']
39
+ config['redis_cache']['groups'].each do |group|
40
+ group['urls'].each do |url|
41
+ if full_url.match url
42
+ time = group['time']
43
+ url_need_cache = true
44
+ @redis_server = Redis.new(host: config['redis_cache']['redis_host'])
45
+ if @redis_server.get(full_url)
46
+ response = @redis_server.get(full_url)
47
+ result_from_cache = true
48
+ else
49
+ response = self.send("#{@scope}_#{action}", "#{full_url}")
50
+ @redis_server.setex(full_url,time,response)
51
+ end
52
+ break
53
+ end
54
+ end
55
+ break if url_need_cache
56
+ end
57
+ end
58
+
59
+ if !url_need_cache
60
+ response = self.send("#{@scope}_#{action}", "#{full_url}")
61
+ end
62
+
32
63
  elsif action === 'create' or action === 'post'
33
64
  action = 'post'
34
65
  response = self.send("#{@scope}_#{action}", "#{full_url}", data)
@@ -36,17 +67,19 @@ module Mints
36
67
  action = 'put'
37
68
  response = self.send("#{@scope}_#{action}", "#{full_url}", data)
38
69
  end
39
- if (response.response.code == "404")
40
- raise 'NotFoundError'
41
- end
42
- parsed_response = JSON.parse(response.body)
43
- if parsed_response.key?('data')
44
- return parsed_response['data']
45
- end
46
- return parsed_response
70
+ if result_from_cache
71
+ return parsed_response = JSON.parse(response)
72
+ else
73
+ if (response.response.code == "404")
74
+ raise 'NotFoundError'
75
+ end
76
+ parsed_response = JSON.parse(response.body)
77
+ return parsed_response
78
+ end
47
79
  end
48
80
 
49
- def method_missing(name, *args, &block)
81
+ def method_missing(name, *args, &block)
82
+ puts name
50
83
  name.to_s.include?("__") ? separator = "__" : separator = "_"
51
84
  # split the name to identify their elements
52
85
  name_spplited = name.to_s.split(separator)
@@ -144,16 +177,38 @@ module Mints
144
177
  ##### HTTTP CLIENTS ######
145
178
  # Simple HTTP GET
146
179
  def http_get(url, headers = nil)
180
+ if @debug
181
+ puts "Url:"
182
+ puts url
183
+ puts "Headers:"
184
+ puts headers
185
+ end
147
186
  return headers ? HTTParty.get(url, :headers => headers) : HTTParty.get(url)
148
187
  end
149
188
 
150
189
  # Simple HTTP POST
151
190
  def http_post(url, headers = nil, data = nil)
191
+ if @debug
192
+ puts "Url:"
193
+ puts url
194
+ puts "Headers:"
195
+ puts headers
196
+ puts "Data:"
197
+ puts data
198
+ end
152
199
  return headers ? HTTParty.post(url, :headers=> headers, :body => data) : HTTParty.post(url, :body => data)
153
200
  end
154
201
 
155
202
  # Simple HTTP PUT
156
203
  def http_put(url, headers = nil, data = nil)
204
+ if @debug
205
+ puts "Url:"
206
+ puts url
207
+ puts "Headers:"
208
+ puts headers
209
+ puts "Data:"
210
+ puts data
211
+ end
157
212
  return headers ? HTTParty.put(url, :headers=> headers, :body => data) : HTTParty.put(url, :body => data)
158
213
  end
159
214
 
@@ -161,7 +216,8 @@ module Mints
161
216
  def contact_get(url)
162
217
  headers = {
163
218
  "ApiKey" => @api_key,
164
- "Accept" => "application/json"
219
+ "Accept" => "application/json",
220
+ "ContactToken" => @contact_token
165
221
  }
166
222
  headers["Authorization"] = "Bearer #{@session_token}" if @session_token
167
223
  return self.http_get(url, headers)
@@ -170,7 +226,8 @@ module Mints
170
226
  def contact_post(url, data)
171
227
  headers = {
172
228
  "ApiKey" => @api_key,
173
- "Accept" => "application/json"
229
+ "Accept" => "application/json",
230
+ "ContactToken" => @contact_token
174
231
  }
175
232
  headers["Authorization"] = "Bearer #{@session_token}" if @session_token
176
233
  return self.http_post(url, headers, data)
@@ -179,7 +236,8 @@ module Mints
179
236
  def contact_put(url, data)
180
237
  headers = {
181
238
  "ApiKey" => @api_key,
182
- "Accept" => "application/json"
239
+ "Accept" => "application/json",
240
+ "ContactToken" => @contact_token
183
241
  }
184
242
  headers["Authorization"] = "Bearer #{@session_token}" if @session_token
185
243
  return self.http_post(url, headers, data)
@@ -208,7 +266,7 @@ module Mints
208
266
  headers = {
209
267
  "ApiKey" => @api_key,
210
268
  "Accept" => "application/json",
211
- "Contet-Type" => "application/json"
269
+ "Content-Type" => "application/json"
212
270
  }
213
271
  headers["Authorization"] = "Bearer #{@session_token}" if @session_token
214
272
  return self.http_put(url, headers, data)
@@ -218,10 +276,10 @@ module Mints
218
276
  def public_get(url, headers = nil)
219
277
  h = {
220
278
  "Accept" => "application/json",
221
- "Contet-Type" => "application/json",
222
- "ApiKey" => @api_key,
223
- "ContactToken" => @session_token
279
+ "Content-Type" => "application/json",
280
+ "ApiKey" => @api_key
224
281
  }
282
+ h["ContactToken"] = @contact_token if @contact_token
225
283
  if headers
226
284
  headers.each do |k,v|
227
285
  h[k] = v
@@ -233,10 +291,10 @@ module Mints
233
291
  def public_post(url, headers = nil, data)
234
292
  h = {
235
293
  "Accept" => "application/json",
236
- "Contet-Type" => "application/json",
237
- "ApiKey" => @api_key,
238
- "ContactToken" => @session_token
294
+ "Content-Type" => "application/json",
295
+ "ApiKey" => @api_key
239
296
  }
297
+ h["ContactToken"] = @session_token if @session_token
240
298
  if headers
241
299
  headers.each do |k,v|
242
300
  h[k] = v
@@ -248,10 +306,10 @@ module Mints
248
306
  def public_put(url, headers = nil, data)
249
307
  h = {
250
308
  "Accept" => "application/json",
251
- "Contet-Type" => "application/json",
252
- "ApiKey" => @api_key,
253
- "ContactToken" => @session_token
309
+ "Content-Type" => "application/json",
310
+ "ApiKey" => @api_key
254
311
  }
312
+ h["ContactToken"] = @contact_token if @contact_token
255
313
  if headers
256
314
  headers.each do |k,v|
257
315
  h[k] = v
@@ -1,4 +1,5 @@
1
1
  require_relative "./client.rb"
2
+ include ActionController::Cookies
2
3
  module Mints
3
4
  class Contact
4
5
  attr_reader :client
@@ -6,22 +7,8 @@ module Mints
6
7
  # === Initialize.
7
8
  # Class constructor
8
9
  #
9
- def initialize(host, api_key, session_token = nil)
10
- @client = Mints::Client.new(host, api_key, "contact", session_token)
11
- end
12
-
13
- ##
14
- # === Register.
15
- # Register a new contact
16
- #
17
- def register(given_name, last_name, email, password)
18
- data = {
19
- given_name: given_name,
20
- last_name: last_name,
21
- email: email,
22
- password: password
23
- }
24
- return @client.raw("post", "/contacts/register", nil, {data: data})
10
+ def initialize(host, api_key, session_token = nil, debug = false)
11
+ @client = Mints::Client.new(host, api_key, "contact", session_token, debug)
25
12
  end
26
13
 
27
14
  ##
@@ -1,4 +1,13 @@
1
1
  # Mints connection configuration
2
2
  mints:
3
3
  host: http://your_host_goes_here.com
4
- api_key: your_mints_api_key_goes_here
4
+ api_key: your_mints_api_key_goes_here
5
+ redis_cache:
6
+ use_cache: boolean_value_to_enable_and_disable_cache
7
+ redis_host: your_redis_host
8
+ groups:
9
+ - urls:
10
+ - group_of_urls
11
+ time: time_that_will_be_applied_to_urls_in_seconds
12
+ sdk:
13
+ debug: false
@@ -0,0 +1,3 @@
1
+ require 'reverse_proxy/client'
2
+ class Api::V1::MintsContactController < Mints::ContactAPIController
3
+ end
@@ -1,6 +1,20 @@
1
1
  class MintsFilesGenerator < Rails::Generators::Base
2
2
  source_root(File.expand_path(File.dirname(__FILE__)))
3
+ include Rails::Generators::Actions
3
4
  def create_mints_files
4
5
  copy_file 'mints_config.yml', 'mints_config.yml'
6
+ copy_file 'mints_user_controller.rb', './app/controllers/api/mints_user_controller.rb'
7
+ copy_file 'mints_contact_controller.rb', './app/controllers/api/v1/mints_contact_controller.rb'
8
+ copy_file 'mints_public_controller.rb', './app/controllers/api/v1/mints_public_controller.rb'
9
+ route <<-eos
10
+ # Mints auto-generated routes (proxy to send request to mints.cloud)
11
+ namespace :api, defaults: { format: :json } do
12
+ match '/user/v1/*path' => 'mints_user#index', via: [:get, :post, :put, :patch, :delete]
13
+ namespace :v1 do
14
+ match '/contacts/*path' => 'mints_contact#index', via: [:get, :post, :put, :patch, :delete]
15
+ match '/*path' => 'mints_public#index', via: [:get, :post, :put, :patch, :delete]
16
+ end
17
+ end
18
+ eos
5
19
  end
6
20
  end
@@ -0,0 +1,3 @@
1
+ require 'reverse_proxy/client'
2
+ class Api::V1::MintsPublicController < Mints::PublicAPIController
3
+ end
@@ -0,0 +1,3 @@
1
+ require 'reverse_proxy/client'
2
+ class Api::MintsUserController < Mints::UserAPIController
3
+ end
@@ -1,6 +1,10 @@
1
1
  require_relative "./pub.rb"
2
2
  require_relative "./contact.rb"
3
3
  require_relative "./user.rb"
4
- require_relative "./mints/controllers/mints_base_controller.rb"
4
+ require_relative "./mints/controllers/base_controller.rb"
5
+ require_relative "./mints/controllers/admin_base_controller.rb"
6
+ require_relative "./mints/controllers/public_api_controller.rb"
7
+ require_relative "./mints/controllers/contact_api_controller.rb"
8
+ require_relative "./mints/controllers/user_api_controller.rb"
5
9
  module Mints
6
10
  end
@@ -0,0 +1,56 @@
1
+ module Mints
2
+ class AdminBaseController < ActionController::Base
3
+ before_action :set_mints_user_client
4
+
5
+ # def mints_user_signed_in?
6
+ # # Check status in mints
7
+ # response = @mints_user.status
8
+ # status = response['success'] ? response['success'] : false
9
+ # unless status
10
+ # # if mints response is negative delete the session cookie
11
+ # cookies.delete(:mints_user_session_token)
12
+ # end
13
+ # return status
14
+ # end
15
+
16
+ ##
17
+ # === Mints user Login.
18
+ # Starts a user session in mints.cloud and set a session cookie
19
+ def mints_user_login(email, password)
20
+ # Login in mints
21
+ response = @mints_user.login(email, password)
22
+ # Get session token from response
23
+ session_token = response['api_token']
24
+ # Set a permanent cookie with the session token
25
+ cookies.permanent[:mints_user_session_token] = session_token
26
+ end
27
+
28
+ ##
29
+ # === Mints user Logout.
30
+ # Destroy session from mints.cloud and delete local session cookie
31
+ def mints_user_logout
32
+ # Logout from mints
33
+ # @mints_user.logout
34
+ # Delete local cookie
35
+ cookies.delete(:mints_user_session_token)
36
+ end
37
+
38
+ private
39
+
40
+ ##
41
+ # === Set Mints user client.
42
+ # Initialize the public client and set the user token
43
+ def set_mints_user_client
44
+ if File.exists?("#{Rails.root}/mints_config.yml")
45
+ config = YAML.load_file("#{Rails.root}/mints_config.yml")
46
+ @host = config["mints"]["host"]
47
+ @api_key = config["mints"]["api_key"]
48
+ @debug = config["sdk"]["debug"] ? config["sdk"]["debug"] : false
49
+ else
50
+ raise 'MintsBadCredentialsError'
51
+ end
52
+ # Initialize mints user client
53
+ @mints_user = Mints::User.new(@host, @api_key, nil, @debug)
54
+ end
55
+ end
56
+ end
@@ -0,0 +1,91 @@
1
+ module Mints
2
+ class BaseController < ActionController::Base
3
+ before_action :set_contact_token
4
+ before_action :set_mints_pub_client
5
+ before_action :register_visit
6
+ before_action :set_mints_contact_client
7
+
8
+ def mints_contact_signed_in?
9
+ # Check status in mints
10
+ response = @mints_contact.status
11
+ status = response['success'] ? response['success'] : false
12
+ unless status
13
+ # if mints response is negative delete the session cookie
14
+ cookies.delete(:mints_contact_session_token)
15
+ end
16
+ return status
17
+ end
18
+
19
+ ##
20
+ # === Mints Contact Login.
21
+ # Starts a contact session in mints.cloud and set a session cookie
22
+ def mints_contact_login(email, password)
23
+ # Login in mints
24
+ response = @mints_contact.login(email, password)
25
+ # Get session token from response
26
+ session_token = response['session_token']
27
+ id_token = response['contact']['id_token']
28
+ # Set a permanent cookie with the session token
29
+ cookies.permanent[:mints_contact_session_token] = session_token
30
+ cookies.permanent[:mints_contact_id] = id_token
31
+ @contact_token = id_token
32
+ end
33
+
34
+ ##
35
+ # === Mints Contact Logout.
36
+ # Destroy session from mints.cloud and delete local session cookie
37
+ def mints_contact_logout
38
+ # Logout from mints
39
+ @mints_contact.logout
40
+ # Delete local cookie
41
+ cookies.delete(:mints_contact_session_token)
42
+ cookies.delete(:mints_contact_id)
43
+ @contact_token = nil
44
+ end
45
+
46
+ private
47
+
48
+ ##
49
+ # === Register visit.
50
+ # Call register visit method from the public client and set/renew the cookie mints_contact_id
51
+ def register_visit
52
+ response = @mints_pub.register_visit(request)
53
+ @contact_token = response['user_token']
54
+ @visit_id = response['visit_id']
55
+ cookies.permanent[:mints_contact_id] = @contact_token
56
+ end
57
+
58
+ ##
59
+ # === Set mints pub.
60
+ # Initialize the public client and set the contact token
61
+ def set_mints_pub_client
62
+ if File.exists?("#{Rails.root}/mints_config.yml")
63
+ config = YAML.load_file("#{Rails.root}/mints_config.yml")
64
+ @host = config["mints"]["host"]
65
+ @api_key = config["mints"]["api_key"]
66
+ @debug = config["sdk"]["debug"] ? config["sdk"]["debug"] : false
67
+ else
68
+ raise 'MintsBadCredentialsError'
69
+ end
70
+ # Initialize mints pub client, credentials taken from mints_config.yml file
71
+ @mints_pub = Mints::Pub.new(@host, @api_key, nil, @debug)
72
+ # Set contact token from cookie
73
+ @mints_pub.client.session_token = @contact_token
74
+ end
75
+
76
+ ##
77
+ # === Set contact token.
78
+ # Set contact token variable from the mints_contact_id cookie value
79
+ def set_contact_token
80
+ @contact_token = cookies[:mints_contact_id]
81
+ end
82
+
83
+ ##
84
+ # === Set mints contact client.
85
+ # Initialize the public client and set the contact token
86
+ def set_mints_contact_client
87
+ # Initialize mints clontact client
88
+ @mints_contact = Mints::Contact.new(@host, @api_key, nil, @debug)
89
+ end
90
+ end
91
+ end
@@ -0,0 +1,88 @@
1
+ require 'reverse_proxy/controller'
2
+ require 'reverse_proxy/client'
3
+ module Mints
4
+ class ContactAPIController < ActionController::API
5
+ include AbstractController::Helpers
6
+ include ActionController::Cookies
7
+ include ReverseProxy::Controller
8
+ before_action :set_config_variables
9
+
10
+ def index
11
+ headers = {
12
+ 'host' => "#{@host.gsub('http://', '').gsub('https://', '')}",
13
+ 'ApiKey' => "#{@api_key}",
14
+ 'Content-Type'=> 'application/json',
15
+ 'Accept'=> 'application/json'
16
+ }
17
+ if cookies[:mints_contact_session_token]
18
+ session_token = cookies[:mints_contact_session_token]
19
+ headers["Authorization"] = "Bearer #{session_token}"
20
+ end
21
+
22
+ url_need_cache = false
23
+ result_from_cache = false
24
+ time = 0
25
+ full_url = request.original_url
26
+
27
+ if request.method == "GET"
28
+ if @use_cache
29
+ @redis_config['groups'].each do |group|
30
+ group['urls'].each do |url|
31
+ if full_url.match url
32
+ time = group['time']
33
+ url_need_cache = true
34
+ break
35
+ end
36
+ end
37
+ break if url_need_cache
38
+ end
39
+ end
40
+ end
41
+
42
+ if url_need_cache
43
+ if @redis_server.get(full_url)
44
+ response = @redis_server.get(full_url)
45
+ result_from_cache = true
46
+ render json: response
47
+ else
48
+ reverse_proxy "#{@host}", headers: headers, verify_ssl: false do |config|
49
+ # Request succeded!
50
+ config.on_response do |code, response|
51
+ @redis_server.setex(full_url,time,response.body)
52
+ end
53
+ # Request failed!
54
+ config.on_missing do |code, response|
55
+ # We got a 404!
56
+ if code == 404
57
+ raise ActionController::RoutingError.new('Not Found')
58
+ end
59
+ end
60
+ end
61
+ end
62
+ else
63
+ reverse_proxy "#{@host}", headers: headers, verify_ssl: false do |config|
64
+ # Request failed!
65
+ config.on_missing do |code, response|
66
+ # We got a 404!
67
+ if code == 404
68
+ raise ActionController::RoutingError.new('Not Found')
69
+ end
70
+ end
71
+ end
72
+ end
73
+ end
74
+
75
+ private
76
+
77
+ def set_config_variables
78
+ if File.exists?("#{Rails.root}/mints_config.yml")
79
+ config = YAML.load_file("#{Rails.root}/mints_config.yml")
80
+ @host = config["mints"]["host"]
81
+ @api_key = config["mints"]["api_key"]
82
+ @redis_server = Redis.new(host: config['redis_cache']['redis_host']) if config['redis_cache']['use_cache']
83
+ @redis_config = config['redis_cache']
84
+ @use_cache = config['redis_cache']['use_cache']
85
+ end
86
+ end
87
+ end
88
+ end
@@ -0,0 +1,84 @@
1
+ require 'reverse_proxy/controller'
2
+ require 'reverse_proxy/client'
3
+ require 'redis'
4
+ module Mints
5
+ class PublicAPIController < ActionController::API
6
+ include ReverseProxy::Controller
7
+ before_action :set_config_variables
8
+
9
+ def index
10
+ headers = {
11
+ 'host' => "#{@host.gsub('http://', '').gsub('https://', '')}",
12
+ 'ApiKey' => "#{@api_key}",
13
+ 'Content-Type'=> 'application/json',
14
+ 'Accept'=> 'application/json'
15
+ }
16
+
17
+ url_need_cache = false
18
+ result_from_cache = false
19
+ time = 0
20
+ full_url = request.original_url
21
+
22
+ if request.method == "GET"
23
+ if @use_cache
24
+ @redis_config['groups'].each do |group|
25
+ group['urls'].each do |url|
26
+ if full_url.match url
27
+ time = group['time']
28
+ url_need_cache = true
29
+ break
30
+ end
31
+ end
32
+ break if url_need_cache
33
+ end
34
+ end
35
+ end
36
+
37
+ if url_need_cache
38
+ if @redis_server.get(full_url)
39
+ response = @redis_server.get(full_url)
40
+ result_from_cache = true
41
+ render json: response
42
+ else
43
+ reverse_proxy "#{@host}", headers: headers, verify_ssl: false do |config|
44
+ # Request succeded!
45
+ config.on_response do |code, response|
46
+ @redis_server.setex(full_url,time,response.body)
47
+ end
48
+ # Request failed!
49
+ config.on_missing do |code, response|
50
+ # We got a 404!
51
+ if code == 404
52
+ raise ActionController::RoutingError.new('Not Found')
53
+ end
54
+ end
55
+ end
56
+ end
57
+ else
58
+ reverse_proxy "#{@host}", headers: headers, verify_ssl: false do |config|
59
+ # Request failed!
60
+ config.on_missing do |code, response|
61
+ # We got a 404!
62
+ if code == 404
63
+ raise ActionController::RoutingError.new('Not Found')
64
+ end
65
+ end
66
+ end
67
+ end
68
+
69
+ end
70
+
71
+ private
72
+
73
+ def set_config_variables
74
+ if File.exists?("#{Rails.root}/mints_config.yml")
75
+ config = YAML.load_file("#{Rails.root}/mints_config.yml")
76
+ @host = config["mints"]["host"]
77
+ @api_key = config["mints"]["api_key"]
78
+ @redis_server = Redis.new(host: config['redis_cache']['redis_host']) if config['redis_cache']['use_cache']
79
+ @redis_config = config['redis_cache']
80
+ @use_cache = config['redis_cache']['use_cache']
81
+ end
82
+ end
83
+ end
84
+ end
@@ -0,0 +1,88 @@
1
+ require 'reverse_proxy/controller'
2
+ require 'reverse_proxy/client'
3
+ module Mints
4
+ class UserAPIController < ActionController::API
5
+ include AbstractController::Helpers
6
+ include ActionController::Cookies
7
+ include ReverseProxy::Controller
8
+ before_action :set_config_variables
9
+
10
+ def index
11
+ headers = {
12
+ 'host' => "#{@host.gsub('http://', '').gsub('https://', '')}",
13
+ 'ApiKey' => "#{@api_key}",
14
+ 'Content-Type'=> 'application/json',
15
+ 'Accept'=> 'application/json'
16
+ }
17
+ if cookies[:mints_contact_session_token]
18
+ session_token = cookies[:mints_user_session_token]
19
+ headers["Authorization"] = "Bearer #{session_token}"
20
+ end
21
+
22
+ url_need_cache = false
23
+ result_from_cache = false
24
+ time = 0
25
+ full_url = request.original_url
26
+
27
+ if request.method == "GET"
28
+ if url_need_cache
29
+ @redis_config['groups'].each do |group|
30
+ group['urls'].each do |url|
31
+ if full_url.match url
32
+ time = group['time']
33
+ url_need_cache = true
34
+ break
35
+ end
36
+ end
37
+ break if url_need_cache
38
+ end
39
+ end
40
+ end
41
+
42
+ if url_need_cache
43
+ if @redis_server.get(full_url)
44
+ response = @redis_server.get(full_url)
45
+ result_from_cache = true
46
+ render json: response
47
+ else
48
+ reverse_proxy "#{@host}", headers: headers, verify_ssl: false do |config|
49
+ # Request succeded!
50
+ config.on_response do |code, response|
51
+ @redis_server.setex(full_url,time,response.body)
52
+ end
53
+ # Request failed!
54
+ config.on_missing do |code, response|
55
+ # We got a 404!
56
+ if code == 404
57
+ raise ActionController::RoutingError.new('Not Found')
58
+ end
59
+ end
60
+ end
61
+ end
62
+ else
63
+ reverse_proxy "#{@host}", headers: headers, verify_ssl: false do |config|
64
+ # Request failed!
65
+ config.on_missing do |code, response|
66
+ # We got a 404!
67
+ if code == 404
68
+ raise ActionController::RoutingError.new('Not Found')
69
+ end
70
+ end
71
+ end
72
+ end
73
+ end
74
+
75
+ private
76
+
77
+ def set_config_variables
78
+ if File.exists?("#{Rails.root}/mints_config.yml")
79
+ config = YAML.load_file("#{Rails.root}/mints_config.yml")
80
+ @host = config["mints"]["host"]
81
+ @api_key = config["mints"]["api_key"]
82
+ @redis_server = Redis.new(host: config['redis_cache']['redis_host'])
83
+ @redis_config = config['redis_cache']
84
+ @use_cache = config['redis_cache']['use_cache'] if config['redis_cache']['use_cache']
85
+ end
86
+ end
87
+ end
88
+ end
data/lib/pub.rb CHANGED
@@ -42,17 +42,8 @@ module Mints
42
42
  # * +contact_token+ - [String] Cookie 'mints_contact_id' value (mints_contact_token)
43
43
  # ==== Return
44
44
  # Returns a Client object
45
- def initialize(host=nil, api_key=nil, contact_token=nil)
46
- if host === nil and api_key === nil
47
- if File.exists?("#{Rails.root}/mints_config.yml")
48
- config = YAML.load_file("#{Rails.root}/mints_config.yml")
49
- host = config["mints"]["host"]
50
- api_key = config["mints"]["api_key"]
51
- else
52
- raise 'MintsBadCredentialsError'
53
- end
54
- end
55
- @client = Mints::Client.new(host, api_key, contact_token)
45
+ def initialize(host, api_key, contact_token = nil, debug = false)
46
+ @client = Mints::Client.new(host, api_key, contact_token, debug)
56
47
  end
57
48
 
58
49
  ##
@@ -64,13 +55,13 @@ module Mints
64
55
  # * +ip+ - [String] It's the visitor IP
65
56
  # * +user_agent+ - The visitor's browser user agent
66
57
  # * +url+ - [String] URL visited
67
- def register_visit(request, ip=nil, user_agent=nil, url=nil)
58
+ def register_visit(request, ip = nil, user_agent = nil, url = nil)
68
59
  data = {
69
60
  ip_address: ip || request.remote_ip,
70
61
  user_agent: user_agent || request.user_agent,
71
62
  url: url || request.fullpath
72
63
  }
73
- response = @client.raw("post", "/register-visit", nil, data)
64
+ response = @client.raw("post", "/register-visit", nil, data.to_json)
74
65
  return response
75
66
  end
76
67
 
@@ -103,7 +94,7 @@ module Mints
103
94
  # ==== Parameters
104
95
  # * +options+ - [Hash] List of {Resource collection Options}[#class-Mints::Pub-label-Resource+collections+options+] shown above can be used as parameter
105
96
  def get_content_templates(options = nil)
106
- return @client.raw("get", "/content/content-templates")
97
+ return @client.raw("get", "/content/content-templates", options)
107
98
  end
108
99
 
109
100
  ##
@@ -123,7 +114,7 @@ module Mints
123
114
  #
124
115
  # ==== Parameters
125
116
  # * +options+ - [Hash] List of {Resource collection Options}[#class-Mints::Pub-label-Resource+collections+options+] shown above can be used as parameter
126
- def content_instances(options)
117
+ def get_content_instances(options)
127
118
  return @client.raw("get", "/content/content-instances", options)
128
119
  end
129
120
 
@@ -134,7 +125,7 @@ module Mints
134
125
  # ==== Parameters
135
126
  # * +slug+ - [String] It's the string identifier generated by Mints
136
127
  # * +options+ - [Hash] List of {Single Resource Options}[#class-Mints::Pub-label-Single+resource+options] shown above can be used as parameter
137
- def content_instance(slug, options = nil)
128
+ def get_content_instance(slug, options = nil)
138
129
  return @client.raw("get", "/content/content-instances/#{slug}", options)
139
130
  end
140
131
 
@@ -161,13 +152,12 @@ module Mints
161
152
 
162
153
  ##
163
154
  # === Get Forms.
164
- # Get a collection of forms.
155
+ # Get a collection of forms
165
156
  #
166
157
  # ==== Parameters
167
- # * +slug+ - [String] It's the string identifier generated by Mints
168
158
  # * +options+ - [Hash] List of {Resource collection Options}[#class-Mints::Pub-label-Resource+collections+options+] shown above can be used as parameter
169
159
  def get_forms(options = nil)
170
- return @client.raw("get", "/content/forms/{slug}", options)
160
+ return @client.raw("get", "/content/forms", options)
171
161
  end
172
162
 
173
163
  ##
@@ -178,7 +168,7 @@ module Mints
178
168
  # * +slug+ - [String] It's the string identifier generated by Mints
179
169
  # * +options+ - [Hash] List of {Single Resource Options}[#class-Mints::Pub-label-Single+resource+options] shown above can be used as parameter
180
170
  def get_form(slug, options = nil)
181
- return @client.raw("get", "/content/forms/{slug}", options)
171
+ return @client.raw("get", "/content/forms/#{slug}", options)
182
172
  end
183
173
 
184
174
  ##
@@ -281,7 +271,7 @@ module Mints
281
271
  #
282
272
  # ==== Parameters
283
273
  # * +options+ - [Hash] List of {Resource collection Options}[#class-Mints::Pub-label-Resource+collections+options+] shown above can be used as parameter
284
- def get_tags(options)
274
+ def get_tags(options = nil)
285
275
  return @client.raw("get", "/config/tags", options)
286
276
  end
287
277
 
@@ -28,8 +28,8 @@ module Mints
28
28
  # * +tags+ - [Boolean] attach tags to response
29
29
  class User
30
30
  attr_reader :client
31
- def initialize(host, api_key, session_token = nil)
32
- @client = Mints::Client.new(host, api_key, 'user', session_token)
31
+ def initialize(host, api_key, session_token = nil, debug = false)
32
+ @client = Mints::Client.new(host, api_key, 'user', session_token, debug)
33
33
  end
34
34
 
35
35
  def login(email, password)
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: mints
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.0.4
4
+ version: 0.0.9
5
5
  platform: ruby
6
6
  authors:
7
- - Ruben Gomez Garcia, Omar Mora
7
+ - Ruben Gomez Garcia, Omar Mora, Luis Payan
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2020-05-12 00:00:00.000000000 Z
11
+ date: 2020-05-28 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: json
@@ -50,6 +50,26 @@ dependencies:
50
50
  - - ">="
51
51
  - !ruby/object:Gem::Version
52
52
  version: 0.18.0
53
+ - !ruby/object:Gem::Dependency
54
+ name: redis
55
+ requirement: !ruby/object:Gem::Requirement
56
+ requirements:
57
+ - - "~>"
58
+ - !ruby/object:Gem::Version
59
+ version: 4.2.2
60
+ - - ">="
61
+ - !ruby/object:Gem::Version
62
+ version: 4.2.2
63
+ type: :runtime
64
+ prerelease: false
65
+ version_requirements: !ruby/object:Gem::Requirement
66
+ requirements:
67
+ - - "~>"
68
+ - !ruby/object:Gem::Version
69
+ version: 4.2.2
70
+ - - ">="
71
+ - !ruby/object:Gem::Version
72
+ version: 4.2.2
53
73
  - !ruby/object:Gem::Dependency
54
74
  name: addressable
55
75
  requirement: !ruby/object:Gem::Requirement
@@ -70,6 +90,26 @@ dependencies:
70
90
  - - ">="
71
91
  - !ruby/object:Gem::Version
72
92
  version: 2.7.0
93
+ - !ruby/object:Gem::Dependency
94
+ name: rails-reverse-proxy
95
+ requirement: !ruby/object:Gem::Requirement
96
+ requirements:
97
+ - - "~>"
98
+ - !ruby/object:Gem::Version
99
+ version: 0.9.1
100
+ - - ">="
101
+ - !ruby/object:Gem::Version
102
+ version: 0.9.1
103
+ type: :runtime
104
+ prerelease: false
105
+ version_requirements: !ruby/object:Gem::Requirement
106
+ requirements:
107
+ - - "~>"
108
+ - !ruby/object:Gem::Version
109
+ version: 0.9.1
110
+ - - ">="
111
+ - !ruby/object:Gem::Version
112
+ version: 0.9.1
73
113
  description:
74
114
  email:
75
115
  executables: []
@@ -81,9 +121,16 @@ files:
81
121
  - lib/client.rb
82
122
  - lib/contact.rb
83
123
  - lib/generators/mints_config.yml
124
+ - lib/generators/mints_contact_controller.rb
84
125
  - lib/generators/mints_files_generator.rb
126
+ - lib/generators/mints_public_controller.rb
127
+ - lib/generators/mints_user_controller.rb
85
128
  - lib/mints.rb
86
- - lib/mints/controllers/mints_base_controller.rb
129
+ - lib/mints/controllers/admin_base_controller.rb
130
+ - lib/mints/controllers/base_controller.rb
131
+ - lib/mints/controllers/contact_api_controller.rb
132
+ - lib/mints/controllers/public_api_controller.rb
133
+ - lib/mints/controllers/user_api_controller.rb
87
134
  - lib/pub.rb
88
135
  - lib/user.rb
89
136
  homepage: https://github.com/rubengomez/mints-ruby-sdk
@@ -1,35 +0,0 @@
1
- module Mints
2
- class BaseController < ActionController::Base
3
- before_action :set_contact_token
4
- before_action :set_mints_pub
5
- before_action :register_visit
6
-
7
- private
8
- ##
9
- # === Register visit.
10
- # Call register visit method from the public client and set/renew the cookie mints_contact_id
11
- def register_visit
12
- response = @mints_pub.register_visit(request)
13
- @contact_token = response['user_token']
14
- @visit_id = response['visit_id']
15
- cookies.permanent[:mints_contact_id] = @contact_token
16
- end
17
-
18
- ##
19
- # === Set mints pub.
20
- # Initialize the public client and set the contact token
21
- def set_mints_pub
22
- # Initialize mints pub client, credentials taken from mints_config.yml file
23
- @mints_pub = Mints::Pub.new
24
- # Set contact token from cookie
25
- @mints_pub.client.session_token = @contact_token
26
- end
27
-
28
- ##
29
- # === Set contact token.
30
- # Set contact token variable from the mints_contact_id cookie value
31
- def set_contact_token
32
- @contact_token = cookies[:mints_contact_id]
33
- end
34
- end
35
- end