whiplash-app 0.9.4 → 0.9.6

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: 228da95848c936a8a771e6f67e6d4aa03899ab722274b2d355917593c9b83a89
4
- data.tar.gz: 2f1f50222b2b7a578d23a88efdfd5328e2d0b772bdae0696249be13457e57db5
3
+ metadata.gz: ed3192117f026dce179a249afae7d1dd8e887883f4272ce9a8ceeff2f9ae9429
4
+ data.tar.gz: 2b3626ec34d6d3fe8bfd4111c3578235ae129321b090501cd0881917506aafe8
5
5
  SHA512:
6
- metadata.gz: 31ba3a5b17e6679551d961ce009efb489e3a4a49bf0cf5cf8e9d4e978626c6ae825a38dad30d62552cf619e08a78a09066cd3ffb67a04599f5dcb6f7d01bc4a4
7
- data.tar.gz: e845ad83845b36f932d21a3fd4fa283e8ef0fc45066cc37a82f80c3c178600a3c4870c76633f9ee88aad1967b16db7e7caf280a55e91b2f0d0d7fcf4ce6965e1
6
+ metadata.gz: 8a2ad62e4666d538fed3ecefb03bd675196c4c2612255f84e38e5865d5abca52a2bbe1c026b6e52cc14c16a9c409719c4cd404f60d7d0cbbfdc0e477232ae8c2
7
+ data.tar.gz: cee2a29068bf4ca7e200085539738a902c72c096bc01af699cb8a2330e1c2511a86715fc4d2aefd15487d603f31d0011972cdf1bd6ddefc2678b0a6ec5560db5
data/README.md CHANGED
@@ -4,6 +4,8 @@ The whiplash-app gem allows your Whiplash application to access the Whiplash
4
4
  API and perform authentication, signatures and signature verification, and basic
5
5
  CRUD functions against the api.
6
6
 
7
+ For apps that provide a UI, it also provides built in authentication and several helper methods.
8
+
7
9
  ## Installation
8
10
 
9
11
  Add this line to your application's Gemfile:
@@ -22,109 +24,76 @@ Or install it yourself as:
22
24
 
23
25
  ## Usage
24
26
 
25
- **NOTE: 0.4.0 introduces a breaking change and is NOT backward compatible with previous versions.**
26
-
27
- To upgrade from < 0.4.0, you need to make two small changes:
28
- 1. `Whiplash::App` must now be instantiated.
29
- 2. Tokens are **not** automatically refreshed
27
+ There are two basic uses for this gem:
28
+ 1. Authenticating users for apps _with a UI_ (i.e. Notifications, Troubleshoot, etc)
29
+ 2. Providing offline access to applications that perform tasks (i.e Tasks, Old Integrations, etc)
30
30
 
31
- Before:
32
- ```ruby
33
- api = Whiplash::App
34
- ```
31
+ It's not uncommon for an application to do _both_ of the above (i.e. Notifications, Payments, etc)
35
32
 
36
- After:
37
- ```ruby
38
- api = Whiplash::App.new
39
- api.refresh_token! # Since you don't have one yet
40
- api.token # Confirm you've got a token
41
- . . .
42
- api.refresh_token! if api.token_expired?
43
- ```
44
-
45
- ### Authentication
33
+ ### Authentication for offline access (Oauth Client Credentials flow)
46
34
  In order to authenticate, make sure the following `ENV` vars are set:
47
35
 
48
36
  ```ruby
49
- ENV["WHIPLASH_CLIENT_ID"]
50
- ENV["WHIPLASH_CLIENT_SECRET"]
51
- ENV["WHIPLASH_CLIENT_SCOPE"]
37
+ ENV['WHIPLASH_API_URL']
38
+ ENV['WHIPLASH_CLIENT_ID']
39
+ ENV['WHIPLASH_CLIENT_SCOPE']
40
+ ENV['WHIPLASH_CLIENT_SECRET']
52
41
  ```
53
42
 
54
- Once those are set, authentication is handled in app.
55
-
56
- ### Oauth Client Credentials
57
- You can authenticate using Oauth Client Credentials (i.e. auth an entire app).
58
- You probably want this for apps that work offline, _on behalf_ of users or customers, or that don't work at the user/customer-level at all.
43
+ Once those are set, you can generate and use an access token like so:
59
44
 
60
45
  ```ruby
61
- api = Whiplash::App.new
62
- api.refresh_token! # Since you don't have one yet
63
- api.token # Confirm you've got a token
46
+ token = Whiplash::App.client_credentials_token
47
+ api = Whiplash::App.new(token)
48
+ customers = api.get!('customers')
64
49
  ```
65
50
 
66
- ### Oauth Authorization Code
67
- You can also authenticate using Oauth Authorization Code (i.e. auth an individual user). This is most common for user-facing app's with a front end.
51
+ ### Authentication for online access
52
+ In order to use the API, you only need to set the following:
68
53
 
69
54
  ```ruby
70
- # Authenticate using Devise Omniauthenticateable strategy; you'll get oauth creds back as a hash
71
- api = Whiplash::App.new(oauth_credentials_hash)
72
- api.token # Confirm you've got a token
55
+ ENV['WHIPLASH_API_URL']
73
56
  ```
74
57
 
75
- ### API URL
76
- In order to set your api url, you can use the following environment URL:
77
- ```
78
- ENV["WHIPLASH_API_URL"]
79
- ```
80
- If it isn't set, then the API URL defaults to either `https://sandbox.getwhiplash.com` (test or dev environment) or `https://www.getwhiplash.com` (prod environment).
58
+ As long as all of your apps are on the same subdomain, they will share auth cookies:
81
59
 
82
- ### Sending Customer ID and Shop ID headers
83
- You can send the headers in `headers` array, like `{customer_id: 123, shop_id: 111}`.
84
- Alternatively, you can set them on instantiation like `Whiplash::App.new(token, {customer_id: 123, shop_id: 111})`.
85
-
86
- ### Rails AR type calls
87
-
88
- In order to make the use of the gem seem more "AR-ish", we've added AR oriented methods that can be used for basic object creation/deletion/updating/viewing. The basic gist of these AR style CRUD methods is that they will all follow the same pattern. If you are performing a collection action, such as `create` or `find`, the pattern is this:
89
-
90
- ```ruby
91
- api.create(resource, params, headers)
60
+ ```json
61
+ {
62
+ "oauth_token": "XXXXXXX",
63
+ "user": {"id":151,"email":"mark@getwhiplash.com","role":"admin","locale":"en","first_name":"Mark","last_name":"Dickson","partner_id":null, "customer_ids":[1, 2, 3]},
64
+ "customer": {"id": 123, "name": "BooYaa"},
65
+ "warehouse": {"id": 1, "name": "Ann Arbor"}
66
+ }
92
67
  ```
93
68
 
94
- For member actions, such as `show`, or `destroy` methods, the pattern is this:
69
+ You get a variety of helper methods for free:
95
70
 
96
- ```ruby
97
- api.find(resource, id, headers)
98
- api.destroy(resource, id, headers)
99
- ```
100
-
101
- Finally, for `update` calls, it's a mixture of those:
71
+ `init_whiplash_api` - This instantiates `@whiplash_api` which can be used to make requests, out of the box
72
+ `current_user` - This is a **hash** with the above fields; you typically shouldn't need much more user info than this'
73
+ `current_customer` - This is a **hash** with the above fields; you typically shouldn't need much more user info than this
74
+ `current_warehouse` - This is a **hash** with the above fields; you typically shouldn't need much more user info than this
75
+ `require_user` - Typically you'd use this in a `before_action`. You almost always want this in `ApplicationController`.
76
+ `set_locale!` - Sets the locale based on the value in the user hash
77
+ `set_current_user_cookie!` - Updates the current user cookie with fresh data from the api. You typically won't need this, unless your app updates fields like `locale`.
78
+ `set_current_customer_cookie!` - Updates the current customer cookie with fresh data from the api; typically used after you've changed customer
79
+ `set_current_warehouse_cookie!` - Updates the current customer cookie with fresh data from the api; typically used after you've changed warehouse
80
+ `unset_current_customer_cookie!` - Deletes the current customer cookie, with appropriate domain settings
81
+ `unset_current_warehouse_cookie!` - Deletes the current warehouse cookie, with appropriate domain settings
82
+ `core_url` - Shorthand for `ENV['WHIPLASH_API_URL']`
83
+ `core_url_for` - Link back to Core like `core_url_for('login')`
102
84
 
103
- ```ruby
104
- api.update(resource, id, params_to_update, headers)
105
- ```
106
85
 
107
- So, basic AR style calls can be performed like so:
86
+ ### Sending Customer ID and Shop ID headers
87
+ You can send the headers in `headers` array, like `{customer_id: 123, shop_id: 111}`.
88
+ Alternatively, you can set them on instantiation like `Whiplash::App.new(token, {customer_id: 123, shop_id: 111})`
108
89
 
109
- ```ruby
110
- api.find_all('orders', {}, { customer_id: 187 })
111
- api.find('orders', 1)
112
- api.create('orders', { key: "value", key2: "value" }, { customer_id: 187 } )
113
- api.update('orders', 1, { key: "value"}, { customer_id: 187 } )
114
- api.destroy('orders', 1, { customer_id: 187 } )
115
- api.count('customers')
116
- ```
117
90
 
118
91
  ### CRUD Wrapper methods
119
- In reality, all of these methods are simply wrapper methods around simple `GET/POST/PUT/DELETE` wrappers on Faraday, so if you want to get more granular,you can also make calls that simply reference the lower level REST verb:
120
92
 
121
93
  ```ruby
122
94
  api.get('orders')
123
95
  ```
124
- Which will return all orders and roughly correspond to an index call. If you need to use `Whiplash::App` for nonRESTful calls, simply drop the full endpoint in as your first argument:
125
96
 
126
- ```ruby
127
- api.get('orders/non_restful_action', {}, {})
128
97
  ```
129
98
  `POST`, `PUT`, and `DELETE` calls can be performed in much the same way:
130
99
  ```ruby
@@ -133,6 +102,37 @@ api.put(endpoint, params, headers) # PUT request to the specified endpoint passi
133
102
  api.delete(endpoint, params, headers) # DELETE request to the specified endpoint. Params would probably just be an id.
134
103
  ```
135
104
 
105
+ ### Bang methods
106
+
107
+ In typical Rails/Ruby fashion, `!` methods `raise`. Typically, you'll want to set some global `rescue`s and use the `!` version of crud requests:
108
+
109
+ ```ruby
110
+ rescue_from WhiplashApiError, with: :handle_whiplash_api_error
111
+
112
+ def handle_whiplash_api_error(exception)
113
+ # Any special exceptions we want to handle directly
114
+ case exception.class.to_s
115
+ when 'WhiplashApiError::Unauthorized'
116
+ return redirect_to core_url_for('logout')
117
+ end
118
+
119
+ @status_code = WhiplashApiError.codes&.invert&.dig(exception&.class)
120
+ @error = exception.message
121
+ respond_to do |format|
122
+ format.html {
123
+ flash[:error] = @error
124
+ redirect_back(fallback_location: root_path)
125
+ }
126
+ format.json {
127
+ render json: exception, status: @status_code
128
+ }
129
+ format.js {
130
+ render template: 'resources/exception'
131
+ }
132
+ end
133
+ end
134
+ ```
135
+
136
136
  ### Signing and Verifying.
137
137
  `whiplash-app` supports signing and verifying signatures like so:
138
138
  ```ruby
@@ -143,30 +143,6 @@ and verifications are done like so:
143
143
  Whiplash::App.verified?(request)
144
144
  ```
145
145
 
146
- ### Caching
147
- `whiplash-app` is Cache agnostic, relying on the `moneta` gem to provide a local store, if needed.
148
- However, if you intend to specify `REDIS` as your key-value store of choice, it's dead simple. Simply declare the following variables:
149
- ```
150
- ENV["REDIS_HOST"]
151
- ENV["REDIS_PORT"]
152
- ENV["REDIS_PASSWORD"]
153
- ENV["REDIS_NAMESPACE"]
154
- ```
155
- If those are provided, `moneta` will use your redis connection and will namespace your cache storage under the redis namespace. By default, if you do not declare a `REDIS_NAMESPACE` value, the app will default to the `WHIPLASH_CLIENT_ID`.
156
-
157
- **For user-facing apps, best practice is to store the `oauth_credentials_hash` in a session variable.**
158
-
159
- ### Gotchas
160
- Due to the way Faraday handles params, this would not, as expected, route to `orders#show` in the Whiplash App, but would instead route to `orders#index`, so it wouldn't return the expected singular order with an ID of 1, but all orders for that customer.
161
- ```ruby
162
- api.get('orders', {id: 1}, {customer_id: 187})
163
- ```
164
- Instead, you'd want to do:
165
- ```ruby
166
- api.get('orders/1', {}, {customer_id: 187})
167
- ```
168
-
169
-
170
146
  ## Development
171
147
 
172
148
  After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
@@ -8,7 +8,9 @@ module Whiplash
8
8
  helper_method :cookie_domain,
9
9
  :core_url,
10
10
  :core_url_for,
11
- :current_user
11
+ :current_customer,
12
+ :current_user,
13
+ :current_warehouse
12
14
  end
13
15
 
14
16
  private
@@ -25,6 +27,28 @@ module Whiplash
25
27
  [core_url, path].join('/')
26
28
  end
27
29
 
30
+ def current_customer
31
+ return if cookies[:customer].blank?
32
+ begin
33
+ customer_hash = JSON.parse(cookies[:customer])
34
+ @current_customer ||= customer_hash
35
+ rescue StandardError => e
36
+ Rails.logger.warn "Customer could not be initialized: #{e.message}"
37
+ nil
38
+ end
39
+ end
40
+
41
+ def current_customer_full
42
+ return if cookies[:customer].blank?
43
+ begin
44
+ customer_hash = JSON.parse(cookies[:customer])
45
+ @current_customer ||= @whiplash_api.get!("customers/#{customer_hash['id']}").body
46
+ rescue StandardError => e
47
+ Rails.logger.warn "Customer could not be initialized: #{e.message}"
48
+ nil
49
+ end
50
+ end
51
+
28
52
  def current_user
29
53
  return if cookies[:user].blank?
30
54
  begin
@@ -35,6 +59,28 @@ module Whiplash
35
59
  end
36
60
  end
37
61
 
62
+ def current_warehouse
63
+ return if cookies[:warehouse].blank?
64
+ begin
65
+ warehouse_hash = JSON.parse(cookies[:warehouse])
66
+ @current_warehouse ||= warehouse_hash
67
+ rescue StandardError => e
68
+ Rails.logger.warn "Warehouse could not be initialized: #{e.message}"
69
+ @current_warehouse = nil
70
+ end
71
+ end
72
+
73
+ def current_warehouse_full
74
+ return if cookies[:warehouse].blank?
75
+ begin
76
+ warehouse_hash = JSON.parse(cookies[:warehouse])
77
+ @whiplash_api.get!("warehouses/#{warehouse_hash['id']}").body
78
+ rescue StandardError => e
79
+ Rails.logger.warn "Warehouse could not be initialized: #{e.message}"
80
+ nil
81
+ end
82
+ end
83
+
38
84
  def http_scheme
39
85
  URI(core_url).scheme
40
86
  end
@@ -59,10 +105,25 @@ module Whiplash
59
105
  I18n.locale = current_user.try('locale') || I18n.default_locale
60
106
  end
61
107
 
108
+ def set_current_customer_cookie!(customer_id, expires_at = nil)
109
+ customer = @whiplash_api.get!("customers/#{customer_id}").body
110
+ user = @whiplash_api.get!("me").body
111
+ fields_we_care_about = %w(id name)
112
+ customer_hash = customer.slice(*fields_we_care_about)
113
+ expires_at ||= user['current_sign_in_expires_at']
114
+
115
+ shared_values = {
116
+ expires: DateTime.parse(expires_at),
117
+ secure: http_scheme == 'https',
118
+ samesite: :strict,
119
+ domain: cookie_domain
120
+ }
121
+ cookies[:customer] = shared_values.merge(value: customer_hash.to_json)
122
+ end
62
123
 
63
124
  def set_current_user_cookie!(expires_at = nil)
64
125
  user = @whiplash_api.get!("me").body
65
- fields_we_care_about = %w(id email role locale first_name last_name partner_id warehouse_id customer_ids)
126
+ fields_we_care_about = %w(id email role locale first_name last_name partner_id customer_ids)
66
127
  user_hash = user.slice(*fields_we_care_about)
67
128
  expires_at ||= user['current_sign_in_expires_at']
68
129
 
@@ -75,6 +136,30 @@ module Whiplash
75
136
  cookies[:user] = shared_values.merge(value: user_hash.to_json)
76
137
  end
77
138
 
139
+ def set_current_warehouse_cookie!(warehouse_id, expires_at = nil)
140
+ warehouse = @whiplash_api.get!("warehouses/#{warehouse_id}").body
141
+ user = @whiplash_api.get!("me").body
142
+ fields_we_care_about = %w(id name)
143
+ warehouse_hash = warehouse.slice(*fields_we_care_about)
144
+ expires_at ||= user['current_sign_in_expires_at']
145
+
146
+ shared_values = {
147
+ expires: DateTime.parse(expires_at),
148
+ secure: http_scheme == 'https',
149
+ samesite: :strict,
150
+ domain: cookie_domain
151
+ }
152
+ cookies[:warehouse] = shared_values.merge(value: warehouse_hash.to_json)
153
+ end
154
+
155
+ def unset_current_customer_cookie!
156
+ cookies.delete(:customer, domain: cookie_domain)
157
+ end
158
+
159
+ def unset_current_warehouse_cookie!
160
+ cookies.delete(:warehouse, domain: cookie_domain)
161
+ end
162
+
78
163
  end
79
164
  end
80
165
  end
@@ -1,5 +1,5 @@
1
1
  module Whiplash
2
2
  class App
3
- VERSION = "0.9.4"
3
+ VERSION = "0.9.6"
4
4
  end
5
5
  end
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: whiplash-app
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.9.4
4
+ version: 0.9.6
5
5
  platform: ruby
6
6
  authors:
7
7
  - Don Sullivan, Mark Dickson
8
8
  autorequire:
9
9
  bindir: exe
10
10
  cert_chain: []
11
- date: 2024-01-10 00:00:00.000000000 Z
11
+ date: 2024-01-12 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: oauth2