soul-cli 0.7.0 → 0.7.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.
package/README.md CHANGED
@@ -106,6 +106,8 @@ There's also a list of all endpoints examples at [docs/api-examples.md](docs/api
106
106
 
107
107
  For websocket examples, check [docs/ws-examples.md](docs/ws-examples.md)
108
108
 
109
+ For detailed information on how authentication works in Soul, please refer to the [docs/auth.md](docs/auth.md)
110
+
109
111
  ## Extending Soul
110
112
 
111
113
  Soul is able to be extended (e.g. Adding custom APIs) via extensions, you can find a list of extensions at [docs/extensions-examples.md](docs/extensions-examples.md)
@@ -0,0 +1,33 @@
1
+ ---
2
+ ---
3
+ @import "https://cdnjs.cloudflare.com/ajax/libs/github-markdown-css/5.5.1/github-markdown.min.css";
4
+
5
+ body {
6
+ margin: 0;
7
+ }
8
+
9
+ @media (prefers-color-scheme: light) {
10
+ body {
11
+ background-color: #ffffff;
12
+ }
13
+ }
14
+
15
+ @media (prefers-color-scheme: dark) {
16
+ body {
17
+ background-color: #0d1117;
18
+ }
19
+ }
20
+
21
+ .markdown-body {
22
+ box-sizing: border-box;
23
+ min-width: 200px;
24
+ max-width: 980px;
25
+ margin: 0 auto;
26
+ padding: 45px;
27
+ }
28
+
29
+ @media (max-width: 767px) {
30
+ .markdown-body {
31
+ padding: 15px;
32
+ }
33
+ }
@@ -11,7 +11,9 @@ To follow the below examples we need to download a sample database and also inst
11
11
  ```bash
12
12
  wget https://raw.githubusercontent.com/lerocha/chinook-database/master/ChinookDatabase/DataSources/Chinook_Sqlite.sqlite # Download sample sqlite database
13
13
  ```
14
+
14
15
  ### Using Soul CLI
16
+
15
17
  ```bash
16
18
  npm install -g soul-cli
17
19
  soul -d ./Chinook_Sqlite.sqlite -p 8000
@@ -26,15 +28,14 @@ npm install # Install dependencies
26
28
  npm link # might need `sudo`
27
29
  soul -d ./Chinook_Sqlite.sqlite -p 8000
28
30
  ```
29
- </details>
30
31
 
32
+ </details>
31
33
 
32
34
  ## Namespaces
33
35
 
34
- 1. [/api/tables](/docs/api/tables-examples.md) Examples for Tables endpoints
35
- 2. [/api/rows](/docs/api/rows-examples.md) Examples for Rows endpoints
36
- 3. [/api/](/docs/api/root-examples.md) Examples for Root endpoints
37
-
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
38
39
 
39
40
  ## Handling Errors
40
41
 
@@ -54,9 +55,9 @@ curl --request POST \
54
55
 
55
56
  ```json
56
57
  {
57
- "message": "table artists already exists",
58
- "error": {
59
- "code": "SQLITE_ERROR"
60
- }
58
+ "message": "table artists already exists",
59
+ "error": {
60
+ "code": "SQLITE_ERROR"
61
+ }
61
62
  }
62
63
  ```
Binary file
package/docs/auth.md ADDED
@@ -0,0 +1,135 @@
1
+ ## User Authentication in Soul
2
+
3
+ Soul incorporates a robust user authentication system that handles user accounts, groups, permissions, and cookie-based user sessions. This section provides an overview of how the default implementation works.
4
+
5
+ Authentication is switched off by default in Soul, but is enabled when either of the `-a` or `--auth` flags are provided at the command line.
6
+
7
+ ### Overview
8
+
9
+ The Soul authentication system handles both authentication and authorization. Briefly, authentication verifies a user is who they claim to be, and authorization determines what an authenticated user is allowed to do. Here, the term "authentication" is used to refer to both tasks.
10
+
11
+ The auth system consists of:
12
+
13
+ - Users
14
+ - Roles and Permissions: A generic way of applying labels and permissions to more than one user.
15
+ - A password hashing system
16
+ - APIs for logging in users or restricting content
17
+ - JWT based access tokens
18
+
19
+ The authentication system in Soul aims to be very generic and doesn't provide some features commonly found in web authentication systems, such as:
20
+
21
+ - Password strength checking
22
+ - Throttling of login attempts
23
+ - Authentication against third-parties (OAuth, for example)
24
+ - Object-level permissions
25
+
26
+ ![auth-db-diagram](./auth-db-diagram.png)
27
+
28
+ <center style="font-size: 12px; color: gray">Figure 1: Soul Authentication Database Diagram</center>
29
+
30
+ #### Users
31
+
32
+ The `_users` table serves as the central component of the authentication system. Each row in the `_users` table represents an individual who interacts with your Soul instance. This table is crucial for enabling various functionalities, such as access restriction, and user registration.
33
+
34
+ **_Superusers_**, distinguished by the `is_superuser` attribute set to true, are a special type of user in Soul. They can bypass any permissions and restrictions, effectively granting them "God-mode" within the system, including being able to access the `/api/tables` and `/api` end-points. Authorization limitations do not apply to superusers.
35
+
36
+ The attributes of the `_users` table are:
37
+
38
+ - id int
39
+ - username varchar
40
+ - \_hashed_password varchar
41
+ - \_salt varchar
42
+ - is_superuser boolean
43
+ - created_at datetime
44
+ - updated_at datetime
45
+
46
+ Note that when Soul boots up, it looks for a table called `_users` (Otherwise Soul creates `_users` table) which holds the Users mentioned above.
47
+
48
+ ##### Modifying Superusers
49
+
50
+ Due to the sensitive nature of the superuser status, it is not possible to change the `is_superuser` attribute of a user through the API.
51
+
52
+ Instead, you can update superusers using the command line.
53
+
54
+ ```
55
+ $ node src/server.js updateuser --id=1 --password=newstrongstring // To update password of a superuser with id 1
56
+ $ node src/server.js updateuser --id=1 --is_superuser=true // To promote a user with id 1 to superuser
57
+ ```
58
+
59
+ #### Roles
60
+
61
+ Roles are a generic way of categorizing users so you can assign permissions to those users. A user can belong to any number of roles.
62
+
63
+ If we have an `editor` role, and a `_roles_permissions` entry for the `posts` table that allows `update`, then any user with that role will be able to update `posts`.
64
+
65
+ The attributes of the `_roles` table are:
66
+
67
+ - id int
68
+ - name varchar
69
+ - created_at datetime
70
+ - updated_at datetime
71
+
72
+ ##### Roles Permissions
73
+
74
+ Using a table called `_roles_permissions` we can assign permissions to roles.
75
+
76
+ The attributes of this table are:
77
+
78
+ - id int
79
+ - role_id int
80
+ - table_name varchar
81
+ - create boolean
82
+ - read boolean
83
+ - update boolean
84
+ - delete boolean
85
+
86
+ There is unique constraint on the combination of `role_id` and `table_name` attributes,
87
+ to prevent duplication of permissions for the same role and table.
88
+
89
+ ###### Default Role
90
+
91
+ Once a new table is created, Soul will automatically create a new `_roles_permissions` row for the `default` role and the new table, with the following permissions:
92
+
93
+ - create: false
94
+ - read: true
95
+ - update: false
96
+ - delete: false
97
+
98
+ Which basically means that any user can read the table data, but can't create, update or delete data.
99
+
100
+ Soul uses the `default` role to assign permissions to new users.
101
+
102
+ The same happens when Soul boots up, but for all existing tables, making sure that all tables have the `default` role assigned to them.
103
+
104
+ ##### Users Roles
105
+
106
+ To assign roles to users we have a join table called `_users_roles` with the following attributes:
107
+
108
+ - id int
109
+ - user_id int
110
+ - role_id int
111
+
112
+ #### Authentication
113
+
114
+ Soul uses cookies and middleware to hook the authentication system into request objects.
115
+
116
+ These provide a `req.user` attribute on every request, which represents the current user. If the current user has not logged in, it is set to null.
117
+
118
+ #### Obtain Access Token
119
+
120
+ To be able to use private APIs, users need to obtain an access token, which is a JWT token consisting of this payload:
121
+
122
+ - username
123
+ - is_superuser
124
+ - roles
125
+
126
+ For security reasons, Access tokens have a very short lifetime, and once expired, they can be refreshed using another API called Refresh Access token. Refresh tokens have a much longer lifetime, and both access and refresh tokens are provided to the user upon logging in.
127
+
128
+ #### Register New Users
129
+
130
+ To register new users, you need to create a new user using the `/api/tables/_users/rows/` endpoint, and then assign roles to that user using the `/api/tables/_users_roles/rows/` endpoint.
131
+ Note that you need to be logged in using a user with a role that has creating users permission.
132
+
133
+ Additionally, it's important to note that the `/api/tables/_users/rows/` endpoint functions slightly differently compared to other `/api/tables/<table_name>/rows/` endpoints. When creating or updating user data through this endpoint, we need to provide the raw passwords, which are then automatically hashed before being stored in the `_hashed_password` field. This extra step enhances the security of the stored passwords.
134
+
135
+ 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.
@@ -20,6 +20,7 @@ npm i -g wscat # Install websocket client
20
20
  ```
21
21
 
22
22
  ### Using Soul CLI
23
+
23
24
  ```bash
24
25
  npm install -g soul-cli
25
26
  soul -d ./Chinook_Sqlite.sqlite -p 8000
@@ -34,9 +35,9 @@ npm install # Install dependencies
34
35
  npm link # might need `sudo`
35
36
  soul -d ./Chinook_Sqlite.sqlite -p 8000
36
37
  ```
37
- </details>
38
38
 
39
+ </details>
39
40
 
40
41
  ## Namespaces
41
42
 
42
- 1. [/ws/tables](/docs/ws/rows-examples.md) Examples for Rows websockets
43
+ 1. [/ws/tables](ws/rows-examples.md) Examples for Rows websockets
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "soul-cli",
3
- "version": "0.7.0",
3
+ "version": "0.7.2",
4
4
  "description": "A SQLite REST and Realtime server",
5
5
  "main": "src/server.js",
6
6
  "bin": {
package/src/commands.js CHANGED
@@ -7,8 +7,7 @@ const runCLICommands = () => {
7
7
  // if the updatesuperuser command is passed from the CLI execute the updatesuperuser function
8
8
  if (argv._.includes('updatesuperuser')) {
9
9
  const { id, password, is_superuser } = argv;
10
-
11
- if (!password && !is_superuser) {
10
+ if (!password && is_superuser === undefined) {
12
11
  console.log(
13
12
  'Please provide either the --password or --is_superuser flag when using the updateuser command.',
14
13
  );
@@ -76,10 +76,10 @@ const createDefaultTables = async () => {
76
76
  permissions.push({
77
77
  role_id: roleId,
78
78
  table_name: table.name,
79
- create: 'false',
80
- read: 'true',
81
- update: 'false',
82
- delete: 'false',
79
+ create: 0,
80
+ read: 1,
81
+ update: 0,
82
+ delete: 0,
83
83
  });
84
84
  }
85
85
 
@@ -55,7 +55,7 @@ const obtainAccessToken = async (req, res) => {
55
55
  */
56
56
  }
57
57
 
58
- let permissions, roleIds;
58
+ let roleIds;
59
59
 
60
60
  // if the user is not a superuser get the role and its permission from the DB
61
61
  if (!toBoolean(user.is_superuser)) {
@@ -64,7 +64,6 @@ const obtainAccessToken = async (req, res) => {
64
64
  res,
65
65
  });
66
66
 
67
- permissions = roleData.permissions;
68
67
  roleIds = roleData.roleIds;
69
68
  }
70
69
 
@@ -73,7 +72,6 @@ const obtainAccessToken = async (req, res) => {
73
72
  userId: user.id,
74
73
  isSuperuser: user.is_superuser,
75
74
  roleIds,
76
- permissions,
77
75
  };
78
76
 
79
77
  // generate an access token
@@ -151,7 +149,7 @@ const refreshAccessToken = async (req, res) => {
151
149
  */
152
150
  }
153
151
 
154
- let permissions, roleIds;
152
+ let roleIds;
155
153
  const user = users[0];
156
154
 
157
155
  // if the user is not a superuser get the role and its permission from the DB
@@ -161,7 +159,6 @@ const refreshAccessToken = async (req, res) => {
161
159
  res,
162
160
  });
163
161
 
164
- permissions = roleData.permissions;
165
162
  roleIds = roleData.roleIds;
166
163
  }
167
164
 
@@ -170,7 +167,6 @@ const refreshAccessToken = async (req, res) => {
170
167
  userId: user.id,
171
168
  isSuperuser: user.is_superuser,
172
169
  roleIds,
173
- permissions,
174
170
  };
175
171
 
176
172
  // generate an access token
@@ -25,7 +25,7 @@ const updateSuperuser = async (fields) => {
25
25
 
26
26
  try {
27
27
  // find the user by using the id field
28
- const users = authService.getRoleByUserId({ id });
28
+ const users = authService.getUsersById({ userId: id });
29
29
 
30
30
  // abort if the id is invalid
31
31
  if (users.length === 0) {
@@ -657,7 +657,7 @@ const updateRowInTableByPK = async (req, res, next) => {
657
657
  if (typeof value === 'string') {
658
658
  value = `'${value}'`;
659
659
  }
660
- return `${key} = ${value}`;
660
+ return `'${key}' = ${value}`;
661
661
  })
662
662
  .join(', ');
663
663
 
package/src/index.js CHANGED
@@ -44,7 +44,11 @@ if (corsOrigin.includes('*')) {
44
44
  corsOrigin = '*';
45
45
  }
46
46
 
47
- const corsOptions = { origin: corsOrigin };
47
+ const corsOptions = {
48
+ origin: corsOrigin,
49
+ credentials: true,
50
+ allowedHeaders: ['Content-Type', 'Authorization'],
51
+ };
48
52
 
49
53
  app.use(cors(corsOptions));
50
54
 
@@ -6,9 +6,16 @@ const {
6
6
  responseMessages,
7
7
  } = require('../constants/');
8
8
  const { removeFields } = require('../utils');
9
+ const { customValidator } = require('../middlewares/validation');
10
+ const schema = require('../schemas/auth');
9
11
 
10
12
  const { httpVerbs } = apiConstants;
11
- const { reservedTableNames, USERS_TABLE, tableFields } = dbConstants;
13
+ const {
14
+ reservedTableNames,
15
+ USERS_TABLE,
16
+ ROLES_PERMISSIONS_TABLE,
17
+ tableFields,
18
+ } = dbConstants;
12
19
  const { errorMessage } = responseMessages;
13
20
 
14
21
  const processRowRequest = async (req, res, next) => {
@@ -39,6 +46,21 @@ const processRowRequest = async (req, res, next) => {
39
46
  );
40
47
  }
41
48
 
49
+ // Validate fields for the _roles_permission API on POST and PUT requests
50
+ if (
51
+ resource === ROLES_PERMISSIONS_TABLE &&
52
+ (method === httpVerbs.POST || method === httpVerbs.PUT)
53
+ ) {
54
+ const validation = customValidator(schema.updateRolePermissions)(req);
55
+
56
+ if (validation.errorStatus) {
57
+ return res.status(400).json({
58
+ message: validation.message,
59
+ error: validation.details,
60
+ });
61
+ }
62
+ }
63
+
42
64
  next();
43
65
  };
44
66
 
@@ -1,6 +1,7 @@
1
1
  const config = require('../config');
2
2
  const { decodeToken, toBoolean } = require('../utils/index');
3
3
  const { apiConstants, responseMessages } = require('../constants');
4
+ const { authService } = require('../services');
4
5
 
5
6
  const { errorMessage } = responseMessages;
6
7
 
@@ -42,12 +43,16 @@ const hasAccess = async (req, res, next) => {
42
43
  .send({ message: errorMessage.NOT_AUTHORIZED_ERROR });
43
44
  }
44
45
 
45
- // if the user is not a super user, check the users permission on the resource
46
- const permissions = payload.permissions.filter((row) => {
47
- return row.table_name === tableName;
46
+ // if the user is not a super user, fetch the permission of the user from the DB
47
+ const rolePermissions = authService.getPermissionByRoleIds({
48
+ roleIds: payload.roleIds,
48
49
  });
49
50
 
50
- if (permissions.length <= 0) {
51
+ const resourcePermission = rolePermissions.filter(
52
+ (row) => row.table_name === tableName,
53
+ );
54
+
55
+ if (resourcePermission.length <= 0) {
51
56
  return res
52
57
  .status(403)
53
58
  .send({ message: errorMessage.PERMISSION_NOT_DEFINED_ERROR });
@@ -56,7 +61,7 @@ const hasAccess = async (req, res, next) => {
56
61
  // If the user has permission on the table in at least in one of the roles then allow access on the table
57
62
  let hasPermission = false;
58
63
 
59
- permissions.some((resource) => {
64
+ resourcePermission.some((resource) => {
60
65
  const httpMethod =
61
66
  apiConstants.httpMethodDefinitions[verb].toLowerCase();
62
67
 
@@ -19,6 +19,24 @@ const validator = (schema) => (req, res, next) => {
19
19
  }
20
20
  };
21
21
 
22
+ const customValidator = (schema) => (req) => {
23
+ const response = { errorStatus: false, message: '', error: '' };
24
+
25
+ const { body, params, query, cookies } = req;
26
+ const data = { body, params, query, cookies };
27
+
28
+ const { error } = schema.validate(data);
29
+
30
+ if (error) {
31
+ response.errorStatus = true;
32
+ response.message = error.message;
33
+ response.error = error.details;
34
+ }
35
+
36
+ return response;
37
+ };
38
+
22
39
  module.exports = {
23
40
  validator,
41
+ customValidator,
24
42
  };
@@ -59,9 +59,30 @@ const registerUser = Joi.object({
59
59
  }).required(),
60
60
  });
61
61
 
62
+ const updateRolePermissions = Joi.object({
63
+ query: Joi.object({}).required(),
64
+ params: Joi.object({ name: Joi.string(), pks: Joi.string() }).required(),
65
+ body: Joi.object({
66
+ fields: Joi.object({
67
+ role_id: Joi.number().required(),
68
+ table_name: Joi.string().required(),
69
+ create: Joi.number().valid(0, 1).required(),
70
+ read: Joi.number().valid(0, 1).required(),
71
+ update: Joi.number().valid(0, 1).required(),
72
+ delete: Joi.number().valid(0, 1).required(),
73
+ }).required(),
74
+ }).required(),
75
+
76
+ cookies: Joi.object({
77
+ accessToken: Joi.string().required(),
78
+ refreshToken: Joi.string().optional(),
79
+ }).required(),
80
+ });
81
+
62
82
  module.exports = {
63
83
  obtainAccessToken,
64
84
  refreshAccessToken,
65
85
  changePassword,
66
86
  registerUser,
87
+ updateRolePermissions,
67
88
  };