model_driven_api 2.2.4 → 2.2.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: f796ea92049910892b48c1904c58192bb7a4b0021a0c0beef89c8e6106f7f64b
4
- data.tar.gz: 5054f69acc854b47ab9a5825bb950d035882b05ea6285b81592989ab31d29343
3
+ metadata.gz: c52d5fb636dc5d7e3641c28b51a3456b8420ac9f91dcc2843a52d1b2ac14c9f1
4
+ data.tar.gz: 3611f35e1a6f99f545c8cd40136a0ae3a4b7ff7ddd5d904c8d9cd1ba19eab786
5
5
  SHA512:
6
- metadata.gz: bbea75413aa62fceddd25f003e23fd6ec16a37f7027be2af549e2f565d91fd8ad8ef93dc07e2bb5cb8b8121aeaf276370ec649222dec8b4893c87a815c4e8a73
7
- data.tar.gz: 871479573af6861b9c0aaf9d323668aab7f75afc68452501dd9c1d9253a96cdfc90cd74891e46e0273dfa0abd14357260fe79ab0ffebc92a11766baf2fae28b5
6
+ metadata.gz: 57ee0c2b9c2505f6eb7c827c0c24fa8a10e3af9d07400d8ed8226be3a4d7a5caffc524052ab80ef3ba555b6119da555918135e1c376027cff83067fd9264d69b
7
+ data.tar.gz: 744eb2730193c381c31f023f3f095499f89725c0d40e932ed012f2593a4488a8a64a4fb3a6f69a336266b9648c9b72b1707a64a04966c8adb09161b0ab86c465
data/README.md CHANGED
@@ -1,86 +1,205 @@
1
1
  # Model Driven Api
2
- I've always been interested in effortless, no-fuss, conventions' based development, DRYness, and pragmatic programming, I've always thought that at this point of the technology evolution, we need not to configure too much to have our software run, having the software adapt to data layers and from there building up APIs, visualizations, etc. in an automatic way. This is a first step to have a schema driven API or better model drive, based on the underlining database, the data it has to serve and some sane dafults, or conventions. This effort also gives, thanks to meta programming, an insight on the actual schema, via the info API, the translations available and the DSL which can change the way the data is presented, leading to a strong base for automatica built of UIs consuming the API (react, vue, angular based PWAs, maybe! ;-) ).
3
2
 
4
- Doing this means also narrowing a bit the scope of the tools, taking decisions, at least for the first implementations and versions of this engine, so, this works well if the data is relational, this is a prerequisite (postgres, mysql, mssql, etc.).
3
+ ## Goal
4
+
5
+ To have a comprehensive and meaningful Model driven API right out of the box by just creating migrations in your rails app or engine. With all the CRUD operations in place out of the box and easily expandable with custom actions if needed.
6
+
7
+ ## TL;DR 5-10 minutes adoption
5
8
 
6
- # Goal
9
+ 1. Add this line to your application's Gemfile or as a dependency for your engine gem: ```gem 'model_driven_api'```
10
+ 2. Run from the shell: ```bundle```
11
+ 3. Add needed models, like:
12
+ ```bash
13
+ rails g migration AddLocation name:string:index description:text:index
14
+ rails g migration AddProduct name:string:index code:string:uniq location:references
15
+ # Any other migration(s) you need...
16
+ ```
17
+ 4. Run the migrations: ```rails db:migrate```
18
+ 5. Bring up your dev server: ```rails s```
19
+ 6. Use **[Insomnia](https://github.com/Kong/insomnia)** rest client to try the endpoints by importing [the API v2 tests](test/insomnia/ApiV2Tests.json) and editing the environment variables as needed.
7
20
 
8
- To have a comprehensive and meaningful API right out of the box by just creating migrations in your rails app or engine.
21
+ This will setup a *User* model, *Role* model, *Permissions* model and the HABTM table between these + any added model you created at the step 3.
9
22
 
10
- # v2?
23
+ The default admin user created during the migration step has a randomly generated password you can find in a .passwords file in the root of your project, that's the initial password, in production you can replace that one, but for testing it proved handy to have it promptly available.
24
+
25
+
26
+ I've always been interested in effortless, no-fuss, conventions' based development, DRYness, and pragmatic programming, I've always thought that at this point of the technology evolution, we need not to configure too much to have our software run, having the software adapt to data layers and from there building up APIs, visualizations, etc. in an automatic way. This is a first step to have a schema driven API or better model drive, based on the underlining database, the data it has to serve and some sane dafults, or conventions. This effort also gives, thanks to meta programming, an insight on the actual schema, via the info API, the translations available and the DSL which can change the way the data is presented, leading to a strong base for automatica built of UIs consuming the API (react, vue, angular based PWAs, maybe! ;-) ).
27
+
28
+ Doing this means also narrowing a bit the scope of the tools, taking decisions, at least for the first implementations and versions of this engine, so, this works well if the data is relational, this is a prerequisite (postgres, mysql, mssql, etc.).
29
+
30
+ ## v2?
11
31
 
12
32
  Yes, this is the second version of such an effort and you can note it from the api calls, which are all under the ```/api/v2``` namespace the [/api/v1](https://github.com/gabrieletassoni/thecore_api) one, was were it all started, many ideas are ported from there, such as the generation of the automatic model based crud actions, as well as custom actions definitions and all the things that make also this gem useful for my daily job were already in place, but it was too coupled with [thecore](https://github.com/gabrieletassoni/thecore)'s [rails_admin](https://github.com/sferik/rails_admin) UI, making it impossible to create a complete UI-less, API only application, out of the box and directly based of the DB schema, with all the bells and whistles I needed (mainly self adapting, data and schema driven API functionalities).
13
33
  So it all began again, making a better thecore_api gem into this model_driven_api gem, more polished, more functional and self contained.
14
34
 
15
- # Standards Used
35
+ ## What has changed
36
+
37
+ * Replace v1 with **v2** in the url
38
+ * **Custom actions** defined in model's concerns now are triggered by a do querystring, for example: ```/api/v2/:model?do=custom_action``` or ```/api/v2/:model/:id?do=custom_action```
39
+ * Searches using Ransack can be done either by GET or POST, but POST is preferred.
40
+
41
+ ## Standards Used
16
42
 
17
43
  * [JWT](https://github.com/jwt/ruby-jwt) for authentication.
18
44
  * [CanCanCan](https://github.com/CanCanCommunity/cancancan) for authorization.
19
45
  * [Ransack](https://github.com/activerecord-hackery/ransack) query engine for complex searches going beyond CRUD's listing scope.
20
46
  * Catch all routing rule to automatically add basic crud operations to any AR model in the app.
21
47
 
22
- ## Usage
23
- How to use my plugin.
48
+ ## API
49
+
50
+ All the **Models** of *WebApp* follow the same endpoint specification as a standard. The only deviations to the normally expected **CRUD** endpoints are for the **authenticate** controller and the **info** controller described below. This is due to their specific nature, which is not the common **CRUD** interaction, but to provide specifically a way to retrieve the **[JWT](https://jwt.io/)** or retrieve low level information on the **structure** of the API.
51
+
52
+ ### Return Values
24
53
 
25
- ## Installation
26
- Add this line to your application's Gemfile:
54
+ The expected return values are:
27
55
 
28
- ```ruby
29
- gem 'model_driven_api'
56
+ - **200** *success*: the request performed the expected action.
57
+ - **401** *unauthenticated*: username, password or token are invalid.
58
+ - **403** *unauthorized*: the user performing the action is authenticated, but doesn't have the permission to perform it.
59
+ - **404** *not found*: the record or custom action is not present in the
60
+ - **422** *invalid*: the specified body of the request has not passed the validations for the model.
61
+ - **500** *errors on the platform*: usually this means you found a bug in the code.
62
+
63
+ ### Getting the Token
64
+
65
+ The first thing that must be done by the client is to get a Token using the credentials:
66
+
67
+ ```bash
68
+ POST http://localhost:3000/api/v2/authenticate
30
69
  ```
31
70
 
32
- And then execute:
71
+ with a POST body like the one below:
72
+
73
+ ```json
74
+ {
75
+ "auth": {
76
+ "email": "<REPLACE>",
77
+ "password": "<REPLACE>"
78
+ }
79
+ }
80
+ ```
81
+
82
+ This action will return in the **header** a *Token* you can use for the following requests.
83
+ Bear in mind that the *Token* will expire within 15 minutes and that at **each successful** request a ***new*** token is returned using the same **header**, so, at each interaction between client server, just making an authenticated and successful request, will give you back a way of continuing to make **authenticated requests** without the extra overhead of an authentication for each one and without having to keep long expiry times for the *Token*.
84
+
85
+ Keep in mind that the Token, if decoded, bears the information about the expiration time as part of the payload.
86
+
87
+ #### Authenticated Requests
88
+
89
+ Once the JWT has been retrieved, the **Authenticated Request**s must use it in a header of Bearer Type like this one:
90
+
91
+ ```
92
+ Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJleHAiOjE1OTA3NzQyMzR9.Z-1yECp55VD560UcB7gIhgVWJNjn8HUerG5s4TVSRko
93
+ ```
94
+
95
+ ### CRUD Actions
96
+
97
+ All the interactions with the **Models** are **Authenticated Request** (see below for reference on **Getting the Token**), all the models have the following six **CRUD** actions and the **custom** actions defined for them in addition (see below for reference to custom actions in the **Schema** section of the **Info** controller):
98
+
99
+ #### List
100
+
101
+ Returns a list of all the records for the models specified by the expected fields as per **DSL** section below.
102
+ Example request for **users** model:
103
+
33
104
  ```bash
34
- $ bundle
105
+ GET http://localhost:3000/api/v2/users
35
106
  ```
36
107
 
37
- Or install it yourself as:
108
+ #### Search
109
+
110
+ Returns a list of all the records for the models specified by the expected fields as per **DSL** section below, the returned records are **filtered** by the **search predicates** you can find in the body of the request:
111
+ Example request for **users** model:
112
+
38
113
  ```bash
39
- $ gem install model_driven_api
114
+ POST http://localhost:3000/api/v2/users/search
115
+ ```
116
+
117
+ Example of the body of the request (*q* means **question**, the *_eq* particle means **equals**, so in this simple example I'm looking for records which have the *id* attribute set to 1, mimicking the **Show** action below):
118
+
119
+ ```json
120
+ {
121
+ "q":{
122
+ "id_eq": 1
123
+ }
124
+ }
40
125
  ```
41
126
 
42
- Then run the migrations:
127
+ The complete documentation of the predicates that can be used is provided by the **[Ransack](https://github.com/activerecord-hackery/ransack)** library, the filtering, ordering, grouping options are really infinite.
128
+
129
+ #### Create
130
+
131
+ Creates a record for the specified **Model**.
132
+ Validations on the data sent are triggered.
133
+ Example request for **users** model:
134
+
43
135
  ```bash
44
- $ rails db:migrate
136
+ POST http://localhost:3000/api/v2/users
45
137
  ```
46
138
 
47
- This will setup a User model, Role model and the HABTM table between the two.
139
+ Example of the body of the request:
48
140
 
49
- Then, if you fire up your ```rails server``` you can already get a jwt and perform different operations.
50
- The default admin user created during the migration step has a randomly generated password you can find in a .passwords file in the root of your project, that's the initial password, in production you can replace that one, but for testing it proved handy to have it promptly available.
141
+ ```json
142
+ {
143
+ "user": {
144
+ "email": "prova@example.com",
145
+ "admin": false,
146
+ "password": "prova63562",
147
+ "password_confirmation": "prova63562"
148
+ }
149
+ }
150
+ ```
51
151
 
52
- ## Consuming the API
152
+ #### Show
53
153
 
54
- ### Getting the Token
154
+ Retrieves a single record as specified by the expected fields as per **DSL** section below.
155
+ Example request for **users** model (retrieves the record with ID = 1):
55
156
 
56
- The first thing that must be done by the client is to get a Token using the credentials:
157
+ ```bash
158
+ GET http://localhost:3000/api/v2/users/1
159
+ ```
160
+
161
+ #### Edit
162
+
163
+ Changes the value of one or more attributes for the specified model. In the body of the PUT request you can just use the attributes you want to change, it's **not** necessary to use all the attributes of the record.
164
+ Example request for **users** model with ID = 1:
57
165
 
58
166
  ```bash
59
- POST http://localhost:3000/api/v2/authenticate
167
+ PUT http://localhost:3000/api/v2/users/1
60
168
  ```
61
169
 
62
- with a POST body like the one below:
170
+ Example of the body of the request:
63
171
 
64
172
  ```json
65
173
  {
66
- "auth": {
67
- "email": "<REPLACE>",
68
- "password": "<REPLACE>"
69
- }
174
+ "user": {
175
+ "email": "ciao@example.com"
176
+ }
70
177
  }
71
178
  ```
72
179
 
73
- This action will return in the header a *Token* you can use for the following requests.
74
- Bear in mind that the *Token* will expire within 15 minutes and that at each succesful request a new token is returned using the same *Token* header, so, at each interaction between client server, just making an authenticated and succesful request, will give you back a way of continuing to make authenticated requests without the extra overhead of an authentication for each one and without having to keep long expiry times for the *Token*.
180
+ #### Delete
181
+
182
+ Deletes the specified record.
183
+ Example request for **users** model with ID = 1:
184
+
185
+ ```bash
186
+ DELETE http://localhost:3000/api/v2/users/1
187
+ ```
188
+
189
+ #### Custom Actions
190
+
191
+ Are triggered by a **do** querystring, for example: `GET /api/v2/:model?do=custom_action` or `GET /api/v2/:model/:id?do=custom_action` respectively for a custom action which works on the entire records collection or a custom action which works on the specific record identified by :id.
75
192
 
76
193
  ### Info API
77
194
 
78
- The info API **api/v2/info/** can be used to retrieve general information about the REST API:
195
+ The info API **/api/v2/info/** can be used to retrieve general information about the REST API.
79
196
 
80
197
  #### Version
81
198
 
82
- By issuing a GET on this api, you will get a response containing the version of the model_driven_api.
83
- This is a request which doesn't require authentication, it could be used as a checkpoint for consuming the resources exposed by this engine.
199
+ By issuing a GET on this api, you will get a response containing the version of *WebApp*.
200
+ This is a request which **doesn't require authentication**, it could be used as a checkpoint for consuming the resources exposed by this engine.
201
+
202
+ Example:
84
203
 
85
204
  ```bash
86
205
  GET http://localhost:3000/api/v2/info/version
@@ -125,7 +244,7 @@ Something like this can be retrieved:
125
244
 
126
245
  #### Schema
127
246
 
128
- **Authenticated Request** This action will send back the *authorized* models accessible by the current user at least for the [:read ability](https://github.com/ryanb/cancan/wiki/checking-abilities). The list will also show the field types of the model and the associations.
247
+ **Authenticated Request** This action will send back the *authorized* models accessible by the **User** owner of the *Token* at least for the [:read ability](https://github.com/ryanb/cancan/wiki/checking-abilities). The list will also show the field types of the model and the associations.
129
248
 
130
249
  By issuing this GET request:
131
250
 
@@ -183,20 +302,130 @@ You will get something like:
183
302
  }
184
303
  ```
185
304
 
186
- The *methods* key will list the **custom actions** that can be used in addition to normal CRUD operations, these can be bulk actions and anything that can serve a purpose, usually to simplify the interaction between client and server (i.e. getting in one request the result of a complex computations which usually would be sorted out using more requests). Later on this topic.
305
+ The ***associations***: key lists the relations between each model and the associated models, be them a n:1 (belongs_to) or a n:m (has_many) one.
306
+ The ***methods*** key will list the **custom actions** that can be used in addition to normal CRUD operations, these are usually **bulk actions** or any computation that can serve a specific purpose outside the basic CRUD scope used usually to simplify the interaction between client and server (i.e. getting in one request the result of a complex computations which usually would be sorted out using more requests).
307
+
308
+ #### DSL
309
+
310
+ **Authenticated Request** This action will send back, for each model, which are the fields to be expected in the returning JSON of each request which has a returning value.
311
+ This information can complement the **Schema** action above output by giving information on what to expect as returned fields, associations and aggregates (methods) from each **READ** action of the **CRUD**. It can be used both to *validate* the returned values of a **LIST** or a **SHOW** or to *drive* UI generation of the clients.
312
+
313
+ By issuing this GET request:
314
+
315
+ ```bash
316
+ GET http://localhost:3000/api/v2/info/dsl
317
+ ```
318
+
319
+ You will get something like:
320
+
321
+ ```json
322
+ {
323
+ "users": {
324
+ "except": [
325
+ "lock_version",
326
+ "created_at",
327
+ "updated_at"
328
+ ],
329
+ "include": [
330
+ "roles"
331
+ ]
332
+ },
333
+ "roles": {
334
+ "except": [
335
+ "lock_version",
336
+ "created_at",
337
+ "updated_at"
338
+ ],
339
+ "include": [
340
+ {
341
+ "users": {
342
+ "only": [
343
+ "id"
344
+ ]
345
+ }
346
+ }
347
+ ]
348
+ },
349
+ "role_users": null
350
+ }
351
+ ```
352
+
353
+ #### Translations
354
+
355
+ **Authenticated Request** This action will send back, all the **translations** of *model* names, *attribute* names and any other translation defined in the backend.
356
+ This can be used by the UI clients to be aligned with the translations found in the Backend.
357
+ The locale for which the translation is requested can be specified by the querystring *locale*, it defaults to **it**.
358
+ For **Model** translations, the ones used more, the key to look for is ***activerecord*** and subkeys **models** and **attributes**.
359
+
360
+ By issuing this GET request:
361
+
362
+ ```bash
363
+ GET http://localhost:3000/api/v2/info/translations?locale=it
364
+ ```
365
+
366
+ You will get smething like (incomplete for briefness):
367
+
368
+ ```json
369
+ {
370
+ "activerecord": {
371
+ "attributes": {
372
+ "user": {
373
+ "confirmation_sent_at": "Conferma inviata a",
374
+ "confirmation_token": "Token di conferma",
375
+ "confirmed_at": "Confermato il",
376
+ "created_at": "Data di Creazione",
377
+ "current_password": "Password corrente",
378
+ "current_sign_in_at": "Accesso corrente il",
379
+ "current_sign_in_ip": "IP accesso corrente",
380
+ "email": "E-Mail",
381
+ "encrypted_password": "Password criptata",
382
+ "failed_attempts": "Tentativi falliti",
383
+ "last_sign_in_at": "Ultimo accesso il",
384
+ "last_sign_in_ip": "Ultimo IP di accesso",
385
+ "locked_at": "Bloccato il",
386
+ "password": "Password",
387
+ "password_confirmation": "Conferma Password",
388
+ "remember_created_at": "Ricordami creato il",
389
+ "remember_me": "Ricordami",
390
+ "reset_password_sent_at": "Reset password inviata a",
391
+ "reset_password_token": "Token di reset password",
392
+ "sign_in_count": "Numero di accessi",
393
+ "unconfirmed_email": "Email non confermata",
394
+ "unlock_token": "Token di sblocco",
395
+ "updated_at": "Aggiornato il",
396
+ "username": "Nome Utente",
397
+ "code": "Codice",
398
+ "roles": "Ruoli",
399
+ "admin": "Amministratore?",
400
+ "locked": "Bloccato?",
401
+ "third_party": "Ente Terzo?"
402
+ },
403
+ "role": {
404
+ "users": "Utenti",
405
+ "name": "Nome",
406
+ "permissions": "Permessi"
407
+ },
408
+ "permission": {
409
+ "predicate": "Predicato",
410
+ "action": "Azione",
411
+ "model": "Modello"
412
+ },
413
+
414
+ [ ... ]
415
+ }
416
+ ```
187
417
 
188
418
  ## Testing
189
419
 
190
420
  If you want to manually test the API using [Insomnia](https://insomnia.rest/) you can find the chained request in Insomnia v4 json format inside the **test/insomnia** folder.
191
- In the next few days, I'll publish also the rspec tests.
421
+ Once loaded the tests inside the insomnia application, please right click on the folder, then in the menu select *</> Environment* and change ```base_url```, ```email``` and ```password``` as needed to set them for all the subsequent actions.
192
422
 
193
423
  ## TODO
194
424
 
195
- * Integrate a settings gem
196
- * Add DSL for users and roles
425
+ * Add a Trust management for API consumers, to have some low level interactions happen between API client and server done without the need for giving a USERNAME and a PASSWORD.
197
426
 
198
427
  ## References
199
- THanks to all these people for ideas:
428
+ Thanks to all these people for ideas:
200
429
 
201
430
  * [Billy Cheng](https://medium.com/@billy.sf.cheng/a-rails-6-application-part-1-api-1ee5ccf7ed01) For a way to have a nice and clean implementation of the JWT on top of Devise.
202
431
  * [Daniel](https://medium.com/@tdaniel/passing-refreshed-jwts-from-rails-api-using-headers-859f1cfe88e9) For a smart way to manage token expiration.
@@ -1,3 +1,4 @@
1
+ require 'model_driven_api/version'
1
2
  class Api::V2::InfoController < Api::V2::ApplicationController
2
3
  # Info uses a different auth method: username and password
3
4
  skip_before_action :authenticate_request, only: [:version], raise: false
@@ -1,12 +1,12 @@
1
1
  class JsonWebToken
2
2
  class << self
3
3
  def encode(payload, expiry = 15.minutes.from_now.to_i)
4
- JWT.encode(payload.merge(exp: expiry), Rails.application.secrets.secret_key_base)
4
+ ::JWT.encode(payload.merge(exp: expiry), ::Rails.application.credentials.dig(:secret_key_base))
5
5
  end
6
6
 
7
7
  def decode(token)
8
- body = JWT.decode(token, Rails.application.secrets.secret_key_base)[0]
9
- HashWithIndifferentAccess.new body
8
+ body = ::JWT.decode(token, ::Rails.application.credentials.dig(:secret_key_base))[0]
9
+ ::HashWithIndifferentAccess.new body
10
10
  rescue
11
11
  nil
12
12
  end
@@ -1,6 +1,7 @@
1
1
  require 'thecore_backend_commons'
2
2
  require 'rack/cors'
3
3
  require 'ransack'
4
+ require 'jwt'
4
5
  require 'json_web_token'
5
6
  require "kaminari"
6
7
  require "multi_json"
@@ -1,3 +1,3 @@
1
1
  module ModelDrivenApi
2
- VERSION = '2.2.4'
2
+ VERSION = '2.2.9'
3
3
  end
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: model_driven_api
3
3
  version: !ruby/object:Gem::Version
4
- version: 2.2.4
4
+ version: 2.2.9
5
5
  platform: ruby
6
6
  authors:
7
7
  - Gabriele Tassoni
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2020-05-22 00:00:00.000000000 Z
11
+ date: 2020-10-26 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: thecore_backend_commons