soul-cli 0.7.8 → 0.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -62,6 +62,15 @@
62
62
  "contributions": [
63
63
  "code"
64
64
  ]
65
+ },
66
+ {
67
+ "login": "thoughtsunificator",
68
+ "name": "Romain Lebesle",
69
+ "avatar_url": "https://avatars.githubusercontent.com/u/85041649?v=4",
70
+ "profile": "http://thoughtsunificator.me",
71
+ "contributions": [
72
+ "code"
73
+ ]
65
74
  }
66
75
  ],
67
76
  "contributorsPerLine": 7,
@@ -0,0 +1,8 @@
1
+ meta {
2
+ name: auth
3
+ seq: 2
4
+ }
5
+
6
+ auth {
7
+ mode: inherit
8
+ }
@@ -0,0 +1,25 @@
1
+ meta {
2
+ name: obtain-access-token
3
+ type: http
4
+ seq: 1
5
+ }
6
+
7
+ post {
8
+ url: {{base_url}}/api/auth/token/obtain
9
+ body: json
10
+ auth: inherit
11
+ }
12
+
13
+ body:json {
14
+ {
15
+ "fields": {
16
+ "username": "john",
17
+ "password": "johns_passowrd"
18
+ }
19
+ }
20
+ }
21
+
22
+ settings {
23
+ encodeUrl: true
24
+ timeout: 0
25
+ }
@@ -0,0 +1,6 @@
1
+ {
2
+ "version": "1",
3
+ "name": "soul",
4
+ "type": "collection",
5
+ "ignore": ["node_modules", ".git"]
6
+ }
@@ -0,0 +1,3 @@
1
+ vars {
2
+ base_url: http://localhost:8000
3
+ }
@@ -0,0 +1,8 @@
1
+ meta {
2
+ name: rows
3
+ seq: 1
4
+ }
5
+
6
+ auth {
7
+ mode: inherit
8
+ }
@@ -0,0 +1,25 @@
1
+ meta {
2
+ name: list-rows-with-ordering
3
+ type: http
4
+ seq: 1
5
+ }
6
+
7
+ get {
8
+ url: {{base_url}}/api/tables/:tableName/rows/?_ordering=-CustomerId.LastName&_extend=CustomerId
9
+ body: none
10
+ auth: inherit
11
+ }
12
+
13
+ params:query {
14
+ _ordering: -CustomerId.LastName
15
+ _extend: CustomerId
16
+ }
17
+
18
+ params:path {
19
+ tableName: Invoice
20
+ }
21
+
22
+ settings {
23
+ encodeUrl: true
24
+ timeout: 0
25
+ }
@@ -0,0 +1,8 @@
1
+ meta {
2
+ name: tables
3
+ seq: 3
4
+ }
5
+
6
+ auth {
7
+ mode: inherit
8
+ }
@@ -0,0 +1,16 @@
1
+ meta {
2
+ name: list-tables
3
+ type: http
4
+ seq: 1
5
+ }
6
+
7
+ get {
8
+ url: {{base_url}}/api/tables
9
+ body: none
10
+ auth: inherit
11
+ }
12
+
13
+ settings {
14
+ encodeUrl: true
15
+ timeout: 0
16
+ }
package/.env.sample CHANGED
@@ -15,7 +15,7 @@ DB=foobar.db
15
15
  ACCESS_TOKEN_EXPIRATION_TIME=10H
16
16
  REFRESH_TOKEN_EXPIRATION_TIME=2D
17
17
 
18
- INITIAL_USER_USERNAME
18
+ INITIAL_USER_USERNAME
19
19
  INITIAL_USER_PASSWORD
20
20
  TOKEN_SECRET
21
21
 
package/README.md CHANGED
@@ -7,18 +7,44 @@
7
7
 
8
8
  [![justforfunnoreally.dev badge](https://img.shields.io/badge/justforfunnoreally-dev-9ff)](https://justforfunnoreally.dev)
9
9
  [![All Contributors](https://img.shields.io/github/all-contributors/thevahidal/soul?color=ee8449&style=flat-square)](#contributors)
10
- [![trackgit](https://us-central1-trackgit-analytics.cloudfunctions.net/token/ping/la8rmyedi6oogy87pxla)](https://trackgit.com)
11
10
 
12
- ## Installation
11
+ ## Usage
12
+
13
+ ### Docker
14
+
15
+ > This is the preferred method as the dependency [better-sqlite3](https://github.com/WiseLibs/better-sqlite3) is making of lot of assumptions about the system it will be installed and running on which in most cases will lead to errors when installing soul.
16
+
17
+ Using the following Dockerfile:
18
+
19
+ <details>
20
+ <summary>Dockerfile</summary>
21
+
22
+ ```nginx
23
+ # node:19-alpine amd64
24
+ FROM node@sha256:d0ba7111bc031323ce2706f8e424afc868db289ba40ff55b05561cf59c123be1 AS node
25
+
26
+ WORKDIR /app
27
+
28
+ ENV NODE_ENV="production"
29
+
30
+ COPY package-lock.json package.json ./
31
+
32
+ RUN apk update && apk add python3=3.11.10-r1 build-base=0.5-r3 && npm ci
13
33
 
14
- Install Soul CLI with npm
34
+ COPY . .
35
+
36
+ CMD [ "npm", "start" ]
37
+ ```
38
+ </details>
39
+
40
+ You can proceed [to building the application](https://docs.docker.com/get-started/workshop/02_our_app/#build-the-apps-image).
41
+
42
+ ### npm
15
43
 
16
44
  ```bash
17
45
  npm install -g soul-cli
18
46
  ```
19
47
 
20
- ## Usage
21
-
22
48
  ### 1. Running Soul
23
49
 
24
50
  Soul is command line tool, after installing it,
@@ -68,16 +94,16 @@ Run the Soul command with the necessary parameters:
68
94
 
69
95
  ```
70
96
 
71
- Note: When configuring your JWT Secret, it is recommended to use a long string value for enhanced security. It is advisable to use a secret that is at least 10 characters in length.
97
+ > Note: When configuring your JWT Secret, it is recommended to use a long string value for enhanced security. It is advisable to use a secret that is at least 10 characters in length.
72
98
 
73
99
  In this example:
74
100
 
75
- The `-a` flag instructs Soul to run in auth mode.
76
- The `--ts` flag allows you to pass a JWT secret value for the `access and refresh tokens` generation and verification. Replace <your_jwt_secret_value> with your desired secret value.
77
- The `--atet` flag sets the JWT expiration time for the access token. In this case, it is set to four hours (4H), meaning the token will expire after 4 hours.
78
- The `--rtet` flag sets the JWT expiration time for the refresh token. In this case, it is set to three days (3D), meaning the token will expire after 3 days.
79
- The `--iuu` flag is used to pass a username for the initial user
80
- The `--iup` flag is used to pass a password for the initial user
101
+ - The `-a` flag instructs Soul to run in auth mode.
102
+ - The `--ts` flag allows you to pass a JWT secret value for the `access and refresh tokens` generation and verification. Replace <your_jwt_secret_value> with your desired secret value.
103
+ - The `--atet` flag sets the JWT expiration time for the access token. In this case, it is set to four hours (4H), meaning the token will expire after 4 hours.
104
+ - The `--rtet` flag sets the JWT expiration time for the refresh token. In this case, it is set to three days (3D), meaning the token will expire after 3 days.
105
+ - The `--iuu` flag is used to pass a username for the initial user
106
+ - The `--iup` flag is used to pass a password for the initial user
81
107
 
82
108
  Here are some example values for the `atet` and `rtet` flags
83
109
 
@@ -104,7 +130,7 @@ soul -d foobar.db updatesuperuser --id=1 --is_superuser=false // Revoke the supe
104
130
  There might be cases where you want to pass a custom path for your `.env` file. For this, you can use the `--env` flag when running the `soul` command, providing the absolute file path of your `.env` file.
105
131
 
106
132
  ```shell
107
- soul -d foobar.db --env=/Users/Documents/Projects/React-Project/.env
133
+ soul -d foobar.db --env=/absolute/path/of/your/.env/file
108
134
  ```
109
135
 
110
136
  NOTE:
@@ -141,13 +167,15 @@ A collection of projects that revolve around the Soul ecosystem.
141
167
 
142
168
  - [RCO-Soul](https://github.com/DeepBlueCLtd/RCO-Soul) The purpose of this project is to demonstrate how to run a React admin client using Soul as a REST API service.
143
169
 
170
+ - [dber](https://github.com/findyourmagic/dber) Database design tool based on entity relation diagram
171
+
144
172
  ## Development
145
173
 
146
174
  ```bash
147
175
  git clone https://github.com/thevahidal/soul # Clone project
148
176
 
149
177
  cp .env.sample .env # Duplicate sample environment variables
150
- nano .env # Update the environment variables
178
+ vim .env # Update the environment variables
151
179
 
152
180
  npm install # Install dependencies
153
181
  npm run dev # Start the dev server
@@ -155,12 +183,22 @@ npm run dev # Start the dev server
155
183
 
156
184
  ## Testing
157
185
 
158
- Set the `AUTH` variable to `true` in your `.env` file and use the command below to run the tests
186
+ 1. Set the `AUTH` variable to true in your `.env` file.
187
+ 2. Provide a username for the `INITIAL_USER_USERNAME` environment variable. The username should be a valid, meaningful username.
188
+ 3. Provide a strong password for the `INITIAL_USER_PASSWORD` environment variable. The password should be at least 8 characters long and contain a combination of lowercase letters, uppercase letters, numbers, and special characters, for example: "Str0ng$Pw!".
189
+ 4. Provider a secret for the `TOKEN_SECRET` environment variable.
190
+ 5. Use the following command to run the tests:
159
191
 
160
192
  ```
161
193
  npm run test
162
194
  ```
163
195
 
196
+ Make sure to replace the placeholders with the appropriate values for your environment.
197
+
198
+ ## Hosting Static Content Using Soul
199
+
200
+ You can host static content using Soul by utilizing its extensions feature. This allows you to expose your static application through Soul, enabling users to access your content without hosting multiple applications. please check [this](./docs/self-hosting.md) document
201
+
164
202
  ## Community
165
203
 
166
204
  [Join](https://bit.ly/soul-discord) the discussion in our Discord server and help making Soul together.
@@ -191,6 +229,7 @@ Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/d
191
229
  <td align="center" valign="top" width="14.28%"><a href="https://godot.id"><img src="https://avatars.githubusercontent.com/u/40712686?v=4?s=100" width="100px;" alt="Hanz"/><br /><sub><b>Hanz</b></sub></a><br /><a href="https://github.com/thevahidal/soul/commits?author=HanzCEO" title="Code">💻</a></td>
192
230
  <td align="center" valign="top" width="14.28%"><a href="https://github.com/KoenDG"><img src="https://avatars.githubusercontent.com/u/1440619?v=4?s=100" width="100px;" alt="Koen De Groote"/><br /><sub><b>Koen De Groote</b></sub></a><br /><a href="https://github.com/thevahidal/soul/commits?author=KoenDG" title="Code">💻</a></td>
193
231
  <td align="center" valign="top" width="14.28%"><a href="https://github.com/TahaKhanAbdalli"><img src="https://avatars.githubusercontent.com/u/50602678?v=4?s=100" width="100px;" alt="Muhammad Taha Khan"/><br /><sub><b>Muhammad Taha Khan</b></sub></a><br /><a href="https://github.com/thevahidal/soul/commits?author=TahaKhanAbdalli" title="Code">💻</a></td>
232
+ <td align="center" valign="top" width="14.28%"><a href="http://thoughtsunificator.me"><img src="https://avatars.githubusercontent.com/u/85041649?v=4?s=100" width="100px;" alt="Romain Lebesle"/><br /><sub><b>Romain Lebesle</b></sub></a><br /><a href="https://github.com/thevahidal/soul/commits?author=thoughtsunificator" title="Code">💻</a></td>
194
233
  </tr>
195
234
  </tbody>
196
235
  </table>
Binary file
@@ -0,0 +1,164 @@
1
+ ## Authentication / Authorization
2
+
3
+ These endpoints are for Soul in the Auth mode. For that you need to enable auth mode by setting the `AUTH=true` environment variable or using the `-a` argument when starting a Soul server.
4
+
5
+ ### 1. Obtain an access token
6
+
7
+ To obtain an access token call `/auth/token/obtain/` endpoint with `POST` method.
8
+
9
+ ```bash
10
+ curl -v --request POST \
11
+ --url http://localhost:8000/api/auth/token/obtain \
12
+ --header 'Content-Type: application/json' \
13
+ --data '{
14
+ "fields": {
15
+ "username": "damien",
16
+ "password": "strongpass"
17
+ }
18
+ }'
19
+ ```
20
+
21
+ Response
22
+
23
+ ```
24
+ ...
25
+ < Set-Cookie: accessToken=<jwt-access-token>; Path=/; HttpOnly
26
+ < Set-Cookie: refreshToken=<jwt-refresh-token>; Path=/; HttpOnly
27
+ ...
28
+ ```
29
+
30
+ > You can see that when login is successful, Soul sets two cookies one for the access token and the other for the refresh token.
31
+
32
+ ```json
33
+ {
34
+ "message": "Success",
35
+ "data": {
36
+ "userId": 1
37
+ }
38
+ }
39
+ ```
40
+
41
+ #### Body Params
42
+
43
+ - `fields` containing `username` and `password` e.g.
44
+
45
+ ```json
46
+ "fields": {
47
+ "username": "damien",
48
+ "password": "strongpass"
49
+ }
50
+ ```
51
+
52
+ > Here's how the jwt access token payload looks like:
53
+
54
+ ```json
55
+ {
56
+ "subject": "accessToken",
57
+ "username": "damien",
58
+ "userId": 1,
59
+ "isSuperuser": "false",
60
+ "roleIds": [1],
61
+ "iat": 1717427688,
62
+ "exp": 1717463688
63
+ }
64
+ ```
65
+
66
+ ### 2. Refresh token
67
+
68
+ To refresh and obtain a new access token call `/auth/token/refresh/` endpoint with `GET` method.
69
+
70
+ ```bash
71
+ curl -v http://localhost:8000/api/auth/token/refresh \
72
+ --cookie 'refreshToken=<jwt-refresh-token>'
73
+ ```
74
+
75
+ Response
76
+
77
+ ```
78
+ ...
79
+ < Set-Cookie: accessToken=<jwt-access-token>; Path=/; HttpOnly
80
+ < Set-Cookie: refreshToken=<jwt-refresh-token>; Path=/; HttpOnly
81
+ ...
82
+ ```
83
+
84
+ > There you get a new token pair
85
+
86
+ ```json
87
+ {
88
+ "message": "Success",
89
+ "data": {
90
+ "userId": 1
91
+ }
92
+ }
93
+ ```
94
+
95
+ #### Cookies
96
+
97
+ - `refreshToken` the refresh token that you acquired before
98
+
99
+ ### 3. Change password
100
+
101
+ To change your account password call `/auth/change-password/` endpoint with `PUT` method.
102
+
103
+ ```bash
104
+ curl --request PUT \
105
+ --url http://localhost:8000/api/auth/change-password \
106
+ --header 'Content-Type: application/json' \
107
+ --data '{
108
+ "fields": {
109
+ "currentPassword": "strongpass",
110
+ "newPassword": "anotherstrongpass"
111
+ }
112
+ }' \
113
+ --cookie 'accessToken=<jwt-access-token>'
114
+ ```
115
+
116
+ Response
117
+
118
+ ```json
119
+ {
120
+ "message": "Password updated successfully",
121
+ "data": {
122
+ "id": 1,
123
+ "username": "damien"
124
+ }
125
+ }
126
+ ```
127
+
128
+ #### Body Params
129
+
130
+ - `fields` containing `currentPassword` and `newPassword` e.g.
131
+
132
+ ```json
133
+ "fields": {
134
+ "currentPassword": "strongpass",
135
+ "newPassword": "anotherstrongpass"
136
+ }
137
+ ```
138
+
139
+ #### Cookies
140
+
141
+ - `accessToken` the access token that you acquired before
142
+
143
+ ### 4. Logout
144
+
145
+ In order to logout from your account e.g. remove access and refresh cookies and also revoke your refresh token (access token lifetime is very short and doesn't need to be revoked) call `/auth/logout/` endpoint with `GET` method.
146
+
147
+ ```bash
148
+ curl http://localhost:8000/api/auth/logout \
149
+ --cookie 'accessToken=<jwt-access-token>' \
150
+ --cookie 'refreshToken=<jwt-refresh-token>'
151
+ ```
152
+
153
+ Response
154
+
155
+ ```json
156
+ {
157
+ "message": "Logout successful"
158
+ }
159
+ ```
160
+
161
+ #### Cookies
162
+
163
+ - `accessToken` the access token that you acquired before
164
+ - `refreshToken` the refresh token that you acquired before
@@ -1,41 +1 @@
1
1
  ## Root
2
-
3
- ### 1. Transaction
4
-
5
- To start a transaction call `/transaction` endpoint with `POST` method.
6
-
7
- ```bash
8
- curl --request POST \
9
- --url http://localhost:8000/api/transaction \
10
- --header 'Content-Type: application/json' \
11
- --data '{
12
- "transaction": [
13
- {
14
- "statement": "INSERT INTO Artist (ArtistId, Name) VALUES (:id, :name)",
15
- "values": { "id": 100000, "name": "Glen Hansard" }
16
- },
17
- {
18
- "query": "SELECT * FROM Artist ORDER BY ArtistId DESC LIMIT 1"
19
- }
20
- ]
21
- }'
22
- ```
23
-
24
- Response
25
-
26
- ```json
27
- {
28
- "data": [
29
- {
30
- "changes": 1,
31
- "lastInsertRowid": 100000
32
- },
33
- [
34
- {
35
- "ArtistId": 100000,
36
- "Name": "Glen Hansard"
37
- }
38
- ]
39
- ]
40
- }
41
- ```
@@ -0,0 +1,137 @@
1
+ ## Rows in Auth mode
2
+
3
+ ### 1. List Rows of a Table in Auth mode
4
+
5
+ To list rows in auth mode we call `/tables/<table-name>/rows/` endpoint with `GET` method and pass the jwt access token via Cookies.
6
+
7
+ > Note that your account needs to have access to read this table.
8
+ > Access (Authorization) in Soul is handled via "\_roles" table aka Roles.
9
+ > If you want to learn about granting permissions proceed to the next example.
10
+
11
+ ```bash
12
+ curl 'localhost:8000/api/tables/Album/rows/' \
13
+ --cookie 'accessToken=<jwt-access-token>'
14
+ ```
15
+
16
+ Response
17
+
18
+ ```json
19
+ {
20
+ "data": [
21
+ {
22
+ "AlbumId": 1,
23
+ "Title": "For Those About To Rock We Salute You",
24
+ "ArtistId": 1
25
+ },
26
+ { "AlbumId": 2, "Title": "Balls to the Wall", "ArtistId": 2 }
27
+ // ...
28
+ ],
29
+ "total": 347,
30
+ "next": "/tables/Album?page=2",
31
+ "previous": null
32
+ }
33
+ ```
34
+
35
+ #### Cookies
36
+
37
+ - `accessToken` the access token that you acquired before
38
+
39
+ ### 2. Granting access to users
40
+
41
+ Only super users (e.g. `is_superuser=true`) or those with roles that have access to '\_roles' table can grant access to other users.
42
+
43
+ > Head over to [README, _Updating Super Users_ section](/README.md#3-updating-super-users) to learn how to promote someone to a super user.
44
+
45
+ #### 2.1. Create a new Role
46
+
47
+ To create a new Role call `/tables/_roles/rows/` endpoint with `POST` method.
48
+
49
+ ```bash
50
+ curl --request POST \
51
+ --url http://localhost:8000/api/tables/_roles/rows/ \
52
+ --header 'Content-Type: application/json' \
53
+ --header 'Cookie: accessToken=<jwt-access-token>' \
54
+ --data '{
55
+ "fields": {
56
+ "name": "editor"
57
+ }
58
+ }'
59
+ ```
60
+
61
+ Response
62
+
63
+ ```json
64
+ {
65
+ "message": "Row inserted",
66
+ "data": {
67
+ "changes": 1,
68
+ "lastInsertRowid": 2
69
+ }
70
+ }
71
+ ```
72
+
73
+ Now that we have our `editor` Role, we can give it some permissions. Here we want to give it permission to `read` `Album` table.
74
+
75
+ #### 2.2. Create permissions for a Role
76
+
77
+ To create permissions for a Role call `/tables/_roles_permissions/rows/` endpoint with `POST` method.
78
+
79
+ ```bash
80
+ curl --request POST \
81
+ --url http://localhost:8000/api/tables/_roles_permissions/rows/ \
82
+ --header 'Content-Type: application/json' \
83
+ --header 'Cookie: accessToken=<jwt-access-token>' \
84
+ --data '{
85
+ "fields": {
86
+ "role_id": 2,
87
+ "table_name": "Album",
88
+ "create": 0,
89
+ "read": 1,
90
+ "update": 0,
91
+ "delete": 0
92
+ }
93
+ }'
94
+ ```
95
+
96
+ Response
97
+
98
+ ```json
99
+ {
100
+ "message": "Row inserted",
101
+ "data": {
102
+ "changes": 1,
103
+ "lastInsertRowid": 6
104
+ }
105
+ }
106
+ ```
107
+
108
+ #### 2.3. Assign Role to a User
109
+
110
+ To assign roles to a user call `/tables/_users_roles/rows/` endpoint with `POST` method.
111
+
112
+ ```bash
113
+ curl --request POST \
114
+ --url http://localhost:8000/api/tables/_users_roles/rows/ \
115
+ --header 'Content-Type: application/json' \
116
+ --header 'Cookie: accessToken=<jwt-access-token>' \
117
+ --data '{
118
+ "fields": {
119
+ "user_id": 1,
120
+ "role_id": 2
121
+ }
122
+ }'
123
+ ```
124
+
125
+ Response
126
+
127
+ ```json
128
+ {
129
+ "message": "Row inserted",
130
+ "data": {
131
+ "changes": 1,
132
+ "lastInsertRowid": 2
133
+ }
134
+ }
135
+ ```
136
+
137
+ Now that we assigned `editor` role to a user, he / she can read the `Album` table.
@@ -1,6 +1,6 @@
1
1
  # API Examples
2
2
 
3
- Soul is consist of 3 main namespaces: `/tables`, `/rows` and `/`. In this document we'll try to go over all of them so you can get familiar with how Soul works.
3
+ Soul consists of 4 main namespaces: Tables (`/tables/`), Rows (`/tables/{table-name}/rows/`), Auth (`/auth/`), and Root (`/`). In this document, we'll try to go over all of them so you can get familiar with how Soul works.
4
4
 
5
5
  ## Setup Environment
6
6
 
@@ -33,9 +33,11 @@ soul -d ./Chinook_Sqlite.sqlite -p 8000
33
33
 
34
34
  ## Namespaces
35
35
 
36
- 1. [/api/tables](api/tables-examples.md) Examples for Tables endpoints
37
- 2. [/api/rows](api/rows-examples.md) Examples for Rows endpoints
38
- 3. [/api/](api/root-examples.md) Examples for Root endpoints
36
+ 1. [/api/tables/](api/tables-examples.md) Examples for Tables endpoints
37
+ 2. [/api/{table-name}/rows/](api/rows-examples.md) Examples for Rows endpoints
38
+ 3. [/api/auth/](api/auth-examples.md) Examples for Authentication / Authorization endpoints
39
+ 1. [/api/{table-name}/rows/](api/rows-auth-examples.md) Examples for Rows endpoints in Auth mode
40
+ 4. [/api/](api/root-examples.md) Examples for Root endpoints
39
41
 
40
42
  ## Handling Errors
41
43
 
package/docs/auth.md CHANGED
@@ -135,3 +135,9 @@ Additionally, it's important to note that the `/api/tables/_users/rows/` endpoin
135
135
  When creating a user, the required fields are `username` and `password`. However, you also have the flexibility to include additional optional fields. To do this, you will need to modify the schema of the `_users` table in your database using a suitable database editor GUI tool. Simply add the desired field(s) to the database schema for the `_users` table. Once the schema is updated, you can pass the optional field(s) from your client application during user creation.
136
136
 
137
137
  Furthermore, when retrieving user data, the endpoint automatically filters out sensitive information such as the `_hashed_password` and `_salt` fields. This precautionary measure is in place to address security concerns and ensure that only necessary and non-sensitive information is included in the returned results.
138
+
139
+ #### Revoked Refresh Tokens
140
+
141
+ When you send a request to log in to Soul using the `/token/obtain` endpoint, you will receive `Access` and `Refresh` tokens. These tokens can be stored in a secure client environment. You can then send a request to the `/token/refresh` endpoint to refresh your access token when it expires.
142
+
143
+ When you log out of Soul, the `Access` and `Refresh` tokens are removed. However, there might be instances where you log out before the refresh token expires, allowing these tokens to be reused by other users. To handle this issue, Soul saves removed refresh tokens temporarily in a table named `revoked_access_tokens`. Each time you attempt to refresh your access token, Soul checks if the `Refresh` token you are using is valid. If you try to reuse a revoked refresh token, Soul will throw an error.
@@ -0,0 +1,54 @@
1
+ # Hosting Static Content Using Soul
2
+
3
+ You can host static content using Soul by utilizing its extensions feature. This allows you to expose your static application through Soul, enabling users to access your content without hosting multiple applications.
4
+
5
+ Here are diagrams showing how to access Soul APIs when running standalone and how to expose a static client via extensions.
6
+
7
+ **Accessing Soul APIs**
8
+ ![soul standalone](../assets/images/soul-standalone.png)
9
+
10
+ **Accessing a React Admin Application via Soul**
11
+ ![soul RA app](../assets/images/soul-RA-app.png)
12
+
13
+ ## Steps
14
+
15
+ In this guide, we will demonstrate how to host a static `React Admin` application.
16
+
17
+ 1. Create an `_extensions` folder and add an `api.js` file to it.:
18
+ ```sh
19
+ mkdir _extensions && touch _extensions/api.js
20
+ ```
21
+ 2. Add the following code to the `api.js` file:
22
+
23
+ ```js
24
+ const reactAdminApp = {
25
+ method: "GET",
26
+ path: "/api/client",
27
+ handler: (req, res, db) => {
28
+ const clientPath = path.join(__dirname, "../dist", "index.html");
29
+ res.app.use(express.static(path.join(__dirname, "../dist")));
30
+ res.sendFile(clientPath);
31
+ },
32
+ };
33
+ ```
34
+
35
+ 3. Build your React Admin client:
36
+
37
+ ```sh
38
+ npm run build
39
+ ```
40
+
41
+ 4. Copy the `dist` folder from your `React Admin` project to the `_extensions` folder:
42
+
43
+ ```sh
44
+ cp -r dist <path/to/_extensions>
45
+ ```
46
+
47
+ 5. Run your Soul application:
48
+ ```sh
49
+ soul -d foobar.db --extensions /path/to/_extensions/
50
+ ```
51
+ 6. To verify that the app is working, open the following URL in your browser:
52
+ ```
53
+ http://localhost:<port>/api/client
54
+ ```
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "soul-cli",
3
- "version": "0.7.8",
3
+ "version": "0.8.2",
4
4
  "description": "A SQLite REST and Realtime server",
5
5
  "main": "src/server.js",
6
6
  "bin": {
@@ -51,7 +51,7 @@
51
51
  "eslint-config-prettier": "^9.0.0",
52
52
  "husky": "^8.0.3",
53
53
  "jest": "^29.4.3",
54
- "nodemon": "^2.0.20",
54
+ "nodemon": "^3.1.3",
55
55
  "prettier": "3.1.0",
56
56
  "supertest": "^6.3.3",
57
57
  "swagger-autogen": "^2.23.1"
@@ -10,7 +10,8 @@ module.exports = {
10
10
 
11
11
  errorMessage: {
12
12
  USERNAME_TAKEN_ERROR: 'This username is taken',
13
- WEAK_PASSWORD_ERROR: 'This password is weak, please use another password',
13
+ WEAK_PASSWORD_ERROR:
14
+ 'This password is weak, it should be at least 8 characters long and contain a combination of lowercase letters, uppercase letters, numbers, and special characters',
14
15
  DEFAULT_ROLE_NOT_CREATED_ERROR:
15
16
  'Please restart soul so a default role can be created',
16
17
  INVALID_USERNAME_PASSWORD_ERROR: 'Invalid username or password',
@@ -78,7 +78,7 @@ describe('Auth Endpoints', () => {
78
78
 
79
79
  expect(res.status).toEqual(400);
80
80
  expect(res.body.message).toBe(
81
- 'This password is weak, please use another password',
81
+ 'This password is weak, it should be at least 8 characters long and contain a combination of lowercase letters, uppercase letters, numbers, and special characters',
82
82
  );
83
83
 
84
84
  expect(res.body).not.toHaveProperty('password');
@@ -1,12 +1,11 @@
1
- const db = require('../db/index');
2
1
  const version = require('../../package.json').version;
3
2
 
4
3
  // Root endpoint
5
4
  const root = async (req, res) => {
6
- /*
5
+ /*
7
6
  #swagger.tags = ['Root']
8
- #swagger.summary = 'Timestamp'
9
- #swagger.description = 'Endpoint to return server timestamp'
7
+ #swagger.summary = 'Timestamp'
8
+ #swagger.description = 'Endpoint to return server timestamp'
10
9
  */
11
10
 
12
11
  res.json({
@@ -18,77 +17,17 @@ const root = async (req, res) => {
18
17
  });
19
18
  };
20
19
 
21
- // Run any query transactions
22
- // inspired by https://github.com/proofrock/ws4sqlite
23
- // e.g. body:
24
- // "transaction": [
25
- // {
26
- // "statement": "INSERT INTO users (id, firstName, lastName) VALUES (:id, :firstName, :lastName)",
27
- // "values": { "id": 1, "firstName": "John", "lastName": "Doe" }
28
- // },
29
- // {
30
- // "query": "SELECT * FROM users"
31
- // }
32
- // }
33
- //
34
- // response:
35
- // "data": [
36
- // {
37
- // "changes": 1,
38
- // "lastInsertRowid": 1
39
- // },
40
- // [
41
- // {
42
- // "id": 1,
43
- // "createdAt": "2022-10-10 10:55:29",
44
- // "updatedAt": "2022-10-10 10:55:29",
45
- // "firstName": "John",
46
- // "lastName": "Doe"
47
- // }
48
- // ]
49
- // ]
50
- //
51
-
52
- const transaction = async (req, res) => {
53
- /*
20
+ const health = async (req, res) => {
21
+ /*
54
22
  #swagger.tags = ['Root']
55
- #swagger.summary = 'Transaction'
56
- #swagger.description = 'Endpoint to run any transaction, e.g. [{ "query": "" }, { "statement": "", "values": {} }, { "query": "" }]',
57
- #swagger.parameters['body'] = {
58
- in: 'body',
59
- required: true,
60
- schema: { $ref: "#/definitions/TransactionRequestBody" }
61
- }
23
+ #swagger.summary = 'Health Check'
24
+ #swagger.description = 'Endpoint to return server health status'
62
25
  */
63
- const { transaction } = req.body;
64
- const results = [];
65
- try {
66
- db.transaction(() => {
67
- transaction.forEach((query) => {
68
- if (query.statement) {
69
- const { statement, values } = query;
70
- const data = db.prepare(statement).run(values);
71
- results.push(data);
72
- } else if (query.query) {
73
- const { query: queryString } = query;
74
- const data = db.prepare(queryString).all();
75
- results.push(data);
76
- }
77
- });
78
- })();
79
26
 
80
- res.json({
81
- data: results,
82
- });
83
- } catch (error) {
84
- res.status(400).json({
85
- message: error.message,
86
- error: error,
87
- });
88
- }
27
+ res.send('OK');
89
28
  };
90
29
 
91
30
  module.exports = {
92
31
  root,
93
- transaction,
32
+ health,
94
33
  };
@@ -15,29 +15,10 @@ describe('Root Endpoints', () => {
15
15
  });
16
16
  });
17
17
 
18
- describe('Transaction Endpoint', () => {
19
- it('POST /transaction should commit transaction and return an array of changes and lastInsertRowid', async () => {
20
- const res = await requestWithSupertest.post('/api/transaction').send({
21
- transaction: [
22
- {
23
- statement: `CREATE TABLE students (id INTEGER PRIMARY KEY, firstName TEXT, lastName TEXT)`,
24
- values: {},
25
- },
26
- {
27
- statement: `INSERT INTO students (id, firstName, lastName) VALUES (:id, :firstName, :lastName)`,
28
- values: { id: 1, firstName: 'John', lastName: 'Doe' },
29
- },
30
- {
31
- query: `SELECT * FROM students`,
32
- },
33
- ],
34
- });
35
-
18
+ describe('Health Endpoints', () => {
19
+ it('GET /health should return server version and timestamp', async () => {
20
+ const res = await requestWithSupertest.get('/api/health');
36
21
  expect(res.status).toEqual(200);
37
- expect(res.type).toEqual(expect.stringContaining('json'));
38
- expect(res.body).toHaveProperty('data');
39
- expect(res.body.data).toEqual(expect.any(Array));
40
- expect(res.body.data[0]).toHaveProperty('changes');
41
- expect(res.body.data[0]).toHaveProperty('lastInsertRowid');
22
+ expect(res.type).toEqual(expect.stringContaining('text'));
42
23
  });
43
24
  });
@@ -163,18 +163,38 @@ const listTableRows = async (req, res, next) => {
163
163
  // if _ordering is provided, order rows by it
164
164
  // e.g. ?_ordering=name will order by name
165
165
  // e.g. ?_ordering=-name will order by name descending
166
+ // e.g. ?_ordering=publisher.name will order by publisher name, considering that publisher is a foreign key to publishers table
166
167
  let orderString = '';
168
+ let extendString = '';
169
+ let joins = {};
170
+
167
171
  if (_ordering) {
168
- orderString += ` ORDER BY ${_ordering.replace('-', '')} ${
169
- _ordering.startsWith('-') ? 'DESC' : 'ASC'
170
- }`;
172
+ const isDesc = _ordering.startsWith('-');
173
+ const cleanOrder = _ordering.replace('-', '');
174
+
175
+ if (cleanOrder.includes('.')) {
176
+ // Handle foreign key sort, e.g. publisher.name
177
+ const [relation, field] = cleanOrder.split('.');
178
+
179
+ const { foreignKey, joinedTableName, joinedTableFields } =
180
+ rowService.getForeignKeyInfo(tableName, relation);
181
+
182
+ extendString += ` LEFT JOIN ${joinedTableName} ON ${joinedTableName}.${foreignKey.to} = ${tableName}.${relation}`;
183
+ joins[relation] = { foreignKey, joinedTableName, joinedTableFields };
184
+ orderString += ` ORDER BY ${joinedTableName}.${field} ${
185
+ isDesc ? 'DESC' : 'ASC'
186
+ }`;
187
+ } else {
188
+ // regular field sort
189
+ orderString += ` ORDER BY ${cleanOrder} ${isDesc ? 'DESC' : 'ASC'}`;
190
+ }
191
+
171
192
  params += `_ordering=${_ordering}&`;
172
193
  }
173
194
 
174
195
  // if _schema is provided, return only those fields
175
196
  // e.g. ?_schema=name,age will return only name and age fields
176
197
  // if _schema is not provided, return all fields
177
-
178
198
  let schemaString = '';
179
199
  if (_schema) {
180
200
  const schemaFields = _schema.split(',');
@@ -217,31 +237,27 @@ const listTableRows = async (req, res, next) => {
217
237
  // }
218
238
 
219
239
  let foreignKeyError = { error: '', message: '' };
220
- let extendString = '';
221
240
 
222
241
  if (_extend) {
223
242
  const extendFields = _extend.split(',');
224
243
  extendFields.forEach((extendedField) => {
225
244
  try {
226
- const foreignKey = db
227
- .prepare(`PRAGMA foreign_key_list(${tableName})`)
228
- .all()
229
- .find((fk) => fk.from === extendedField);
230
-
231
- if (!foreignKey) {
232
- throw new Error(
233
- `Foreign key not found for extended field '${extendedField}'`,
245
+ let foreignKey, joinedTableName, joinedTableFields;
246
+ if (joins[extendedField]) {
247
+ foreignKey = joins[extendedField].foreignKey;
248
+ joinedTableName = joins[extendedField].joinedTableName;
249
+ joinedTableFields = joins[extendedField].joinedTableFields;
250
+ } else {
251
+ const foreignKeyInfo = rowService.getForeignKeyInfo(
252
+ tableName,
253
+ extendedField,
234
254
  );
255
+ foreignKey = foreignKeyInfo.foreignKey;
256
+ joinedTableName = foreignKeyInfo.joinedTableName;
257
+ joinedTableFields = foreignKeyInfo.joinedTableFields;
258
+ extendString += ` LEFT JOIN ${joinedTableName} ON ${joinedTableName}.${foreignKey.to} = ${tableName}.${extendedField}`;
235
259
  }
236
260
 
237
- const { table: joinedTableName } = foreignKey;
238
-
239
- const joinedTableFields = db
240
- .prepare(`PRAGMA table_info(${joinedTableName})`)
241
- .all();
242
-
243
- extendString += ` LEFT JOIN ${joinedTableName} ON ${joinedTableName}.${foreignKey.to} = ${tableName}.${extendedField}`;
244
-
245
261
  // joined fields will be returned in a new object called {field}_data e.g. author_id_data
246
262
  const extendFieldsString =
247
263
  'json_object( ' +
@@ -77,6 +77,35 @@ describe('Rows Endpoints', () => {
77
77
  );
78
78
  });
79
79
 
80
+ it('GET /tables/:name/rows?_ordering:userId.firstName&_extend=userId: should return the rows ordered by the related table field', async () => {
81
+ const accessToken = await generateToken(
82
+ { username: 'John', isSuperuser: true },
83
+ config.tokenSecret,
84
+ '1H',
85
+ );
86
+
87
+ const params = {
88
+ _ordering: 'userId.firstName',
89
+ _extend: 'userId',
90
+ };
91
+ const query = queryString(params);
92
+ const res = await requestWithSupertest
93
+ .get(`/api/tables/posts/rows?${query}`)
94
+ .set('Cookie', [`accessToken=${accessToken}`]);
95
+
96
+ expect(res.status).toEqual(200);
97
+ expect(res.type).toEqual(expect.stringContaining('json'));
98
+ expect(res.body).toHaveProperty('data');
99
+ expect(res.body.data).toEqual(expect.any(Array));
100
+
101
+ const firstUserFirstName = res.body.data[1].userId_data.firstName;
102
+ const secondUserFirstName = res.body.data[2].userId_data.firstName;
103
+ const thirdUserFirstName = res.body.data[3].userId_data.firstName;
104
+
105
+ expect(firstUserFirstName <= secondUserFirstName).toBe(true);
106
+ expect(secondUserFirstName <= thirdUserFirstName).toBe(true);
107
+ });
108
+
80
109
  it('GET /tables/:name/rows: should return a null field', async () => {
81
110
  const accessToken = await generateToken(
82
111
  { username: 'John', isSuperuser: true },
@@ -268,8 +297,9 @@ describe('Rows Endpoints', () => {
268
297
  );
269
298
 
270
299
  const res = await requestWithSupertest
271
- .delete('/api/tables/users/rows/1')
300
+ .delete('/api/tables/posts/rows/1')
272
301
  .set('Cookie', [`accessToken=${accessToken}`]);
302
+
273
303
  expect(res.status).toEqual(200);
274
304
  expect(res.type).toEqual(expect.stringContaining('json'));
275
305
  });
package/src/index.js CHANGED
@@ -28,10 +28,8 @@ const {
28
28
 
29
29
  const { runCLICommands } = require('./commands');
30
30
  const { authConstants } = require('./constants');
31
+
31
32
  const app = express();
32
- app.get('/health', (req, res) => {
33
- res.send('OK');
34
- });
35
33
 
36
34
  app.use(bodyParser.json());
37
35
  app.use(cookieParser());
@@ -1,16 +1,10 @@
1
1
  const express = require('express');
2
2
 
3
3
  const controllers = require('../controllers/index');
4
- const { validator } = require('../middlewares/validation');
5
- const schema = require('../schemas/index');
6
4
 
7
5
  const router = express.Router();
8
6
 
9
7
  router.get('/', controllers.root);
10
- router.post(
11
- '/transaction',
12
- validator(schema.transaction),
13
- controllers.transaction
14
- );
8
+ router.get('/health', controllers.health);
15
9
 
16
10
  module.exports = router;
@@ -5,7 +5,7 @@ const listTableRows = Joi.object({
5
5
  _page: Joi.number().integer().min(1).default(1),
6
6
  _limit: Joi.number().integer().min(1).default(10),
7
7
  _search: Joi.string(),
8
- _ordering: Joi.string().regex(/^[\w-]+$/),
8
+ _ordering: Joi.string().regex(/^[\w.-]+$/),
9
9
  _schema: Joi.string(),
10
10
  _extend: Joi.string(),
11
11
  _filters: Joi.string(),
@@ -94,5 +94,23 @@ module.exports = (db) => {
94
94
  const result = statement.run(...pks);
95
95
  return result;
96
96
  },
97
+
98
+ getForeignKeyInfo(tableName, field) {
99
+ const foreignKey = db
100
+ .prepare(`PRAGMA foreign_key_list(${tableName})`)
101
+ .all()
102
+ .find((fk) => fk.from === field);
103
+
104
+ if (!foreignKey) {
105
+ throw new Error(`Foreign key not found for field '${field}'`);
106
+ }
107
+
108
+ const joinedTableName = foreignKey.table;
109
+ const joinedTableFields = db
110
+ .prepare(`PRAGMA table_info(${joinedTableName})`)
111
+ .all();
112
+
113
+ return { foreignKey, joinedTableName, joinedTableFields };
114
+ },
97
115
  };
98
116
  };
@@ -152,7 +152,8 @@ const doc = {
152
152
  },
153
153
 
154
154
  WeakPasswordErrorResponse: {
155
- message: 'This password is weak, please use another password',
155
+ message:
156
+ 'This password is weak, it should be at least 8 characters long and contain a combination of lowercase letters, uppercase letters, numbers, and special characters',
156
157
  },
157
158
 
158
159
  UsernameTakenErrorResponse: {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "swagger": "2.0",
3
3
  "info": {
4
- "version": "0.7.2",
4
+ "version": "0.8.1",
5
5
  "title": "Soul API",
6
6
  "description": "API Documentation for <b>Soul</b>, a SQLite REST and realtime server. "
7
7
  },
@@ -30,17 +30,6 @@
30
30
  "consumes": ["application/json"],
31
31
  "produces": ["application/json"],
32
32
  "paths": {
33
- "/health": {
34
- "get": {
35
- "description": "",
36
- "parameters": [],
37
- "responses": {
38
- "200": {
39
- "description": "OK"
40
- }
41
- }
42
- }
43
- },
44
33
  "/api/": {
45
34
  "get": {
46
35
  "tags": ["Root"],
@@ -54,27 +43,15 @@
54
43
  }
55
44
  }
56
45
  },
57
- "/api/transaction": {
58
- "post": {
46
+ "/api/health": {
47
+ "get": {
59
48
  "tags": ["Root"],
60
- "summary": "Transaction",
61
- "description": "Endpoint to run any transaction, e.g. [{ \"query\": \"\" }, { \"statement\": \"\", \"values\": {} }, { \"query\": \"\" }]",
62
- "parameters": [
63
- {
64
- "name": "body",
65
- "in": "body",
66
- "required": true,
67
- "schema": {
68
- "$ref": "#/definitions/TransactionRequestBody"
69
- }
70
- }
71
- ],
49
+ "summary": "Health Check",
50
+ "description": "Endpoint to return server health status",
51
+ "parameters": [],
72
52
  "responses": {
73
53
  "200": {
74
54
  "description": "OK"
75
- },
76
- "400": {
77
- "description": "Bad Request"
78
55
  }
79
56
  }
80
57
  }
@@ -890,7 +867,7 @@
890
867
  "properties": {
891
868
  "message": {
892
869
  "type": "string",
893
- "example": "This password is weak, please use another password"
870
+ "example": "This password is weak, it should be at least 8 characters long and contain a combination of lowercase letters, uppercase letters, numbers, and special characters"
894
871
  }
895
872
  }
896
873
  },
@@ -1,11 +1,18 @@
1
- const { createTestTable, insertIntoTestTable } = require('.');
1
+ const {
2
+ createTestTable,
3
+ insertIntoTestTable,
4
+ createTestRelatedTable,
5
+ insertIntoTestRelatedTable,
6
+ } = require('.');
2
7
 
3
8
  const setup = () => {
4
9
  console.log('Test suite started');
5
10
  console.log('Creating test table...');
6
11
  createTestTable();
12
+ createTestRelatedTable();
7
13
  console.log('Inserting a row into test table...');
8
14
  insertIntoTestTable();
15
+ insertIntoTestRelatedTable();
9
16
  };
10
17
 
11
18
  module.exports = setup;
@@ -30,6 +30,12 @@ const createTestTable = (table = 'users') => {
30
30
  ).run();
31
31
  };
32
32
 
33
+ const createTestRelatedTable = (table = 'posts') => {
34
+ db.prepare(
35
+ `CREATE TABLE ${table} (id INTEGER PRIMARY KEY, userId INTEGER, title TEXT, content TEXT, createdAt TEXT, FOREIGN KEY(userId) REFERENCES users(id))`,
36
+ ).run();
37
+ };
38
+
33
39
  const insertIntoTestTable = (table = 'users') => {
34
40
  const statement = db.prepare(
35
41
  `INSERT INTO ${table} (firstName, lastName, createdAt) VALUES (?, ?, ?)`,
@@ -40,9 +46,26 @@ const insertIntoTestTable = (table = 'users') => {
40
46
  }
41
47
  };
42
48
 
49
+ const insertIntoTestRelatedTable = (table = 'posts') => {
50
+ const statement = db.prepare(
51
+ `INSERT INTO ${table} (userId, title, content, createdAt) VALUES (?, ?, ?, ?)`,
52
+ );
53
+
54
+ for (let i = 1; i <= testNames.length; i++) {
55
+ statement.run(
56
+ '' + i,
57
+ `Post Title ${i}`,
58
+ `This is the content of post ${i}.`,
59
+ new Date().toISOString(),
60
+ );
61
+ }
62
+ };
63
+
43
64
  module.exports = {
44
65
  dropTestTable,
45
66
  dropTestDatabase,
46
67
  createTestTable,
68
+ createTestRelatedTable,
47
69
  insertIntoTestTable,
70
+ insertIntoTestRelatedTable,
48
71
  };