soul-cli 0.6.1 → 0.7.1

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.
Files changed (66) hide show
  1. package/.all-contributorsrc +73 -0
  2. package/.editorconfig +26 -0
  3. package/.env.sample +9 -0
  4. package/.eslintignore +2 -0
  5. package/.eslintrc.js +24 -0
  6. package/.github/ISSUE_TEMPLATE/bug_report.md +38 -0
  7. package/.github/ISSUE_TEMPLATE/feature_request.md +20 -0
  8. package/.github/workflows/npm-publish.yml +23 -0
  9. package/.husky/pre-commit +5 -0
  10. package/CONTRIBUTING.md +92 -0
  11. package/LICENSE +21 -0
  12. package/README.md +188 -1
  13. package/docs/api/root-examples.md +41 -0
  14. package/docs/api/rows-examples.md +225 -0
  15. package/docs/api/tables-examples.md +217 -0
  16. package/docs/api-examples.md +62 -0
  17. package/docs/auth-db-diagram.png +0 -0
  18. package/docs/auth.md +135 -0
  19. package/docs/extensions-examples.md +167 -0
  20. package/docs/logo.png +0 -0
  21. package/docs/soul-studio.png +0 -0
  22. package/docs/ws/rows-examples.md +122 -0
  23. package/docs/ws-examples.md +42 -0
  24. package/package.json +17 -2
  25. package/src/cli.js +59 -1
  26. package/src/commands.js +22 -0
  27. package/src/config/index.js +48 -3
  28. package/src/constants/api.js +26 -0
  29. package/src/constants/auth.js +5 -0
  30. package/src/constants/index.js +13 -0
  31. package/src/constants/messages.js +41 -0
  32. package/src/constants/roles.js +3 -0
  33. package/src/constants/tables.js +47 -0
  34. package/src/controllers/auth/common.js +16 -0
  35. package/src/controllers/auth/index.js +5 -0
  36. package/src/controllers/auth/tables.js +96 -0
  37. package/src/controllers/auth/token.js +243 -0
  38. package/src/controllers/auth/user.js +394 -0
  39. package/src/controllers/auth.test.js +372 -0
  40. package/src/controllers/rows.js +48 -55
  41. package/src/controllers/rows.test.js +146 -40
  42. package/src/controllers/tables.test.js +58 -28
  43. package/src/db/schema.js +118 -0
  44. package/src/index.js +33 -4
  45. package/src/middlewares/api.js +79 -0
  46. package/src/middlewares/auth.js +85 -0
  47. package/src/middlewares/broadcast.js +1 -1
  48. package/src/middlewares/validation.js +3 -2
  49. package/src/routes/auth.js +29 -0
  50. package/src/routes/rows.js +17 -5
  51. package/src/routes/tables.js +26 -4
  52. package/src/schemas/auth.js +67 -0
  53. package/src/schemas/index.js +6 -1
  54. package/src/schemas/rows.js +20 -0
  55. package/src/schemas/tables.js +18 -2
  56. package/src/server.js +3 -2
  57. package/src/services/authService.js +78 -0
  58. package/src/services/index.js +2 -1
  59. package/src/services/rowService.js +36 -7
  60. package/src/services/tableService.js +127 -1
  61. package/src/swagger/index.js +67 -0
  62. package/src/swagger/swagger.json +292 -60
  63. package/src/tests/index.js +4 -5
  64. package/src/tests/testData.js +23 -10
  65. package/src/utils/index.js +78 -0
  66. /package/{src/services/.gitkeep → docs/extensions/api-examples.js} +0 -0
@@ -0,0 +1,47 @@
1
+ const USERS_TABLE = '_users';
2
+ const ROLES_TABLE = '_roles';
3
+ const USERS_ROLES_TABLE = '_users_roles';
4
+ const ROLES_PERMISSIONS_TABLE = '_roles_permissions';
5
+
6
+ module.exports = {
7
+ USERS_TABLE,
8
+ ROLES_TABLE,
9
+ USERS_ROLES_TABLE,
10
+ ROLES_PERMISSIONS_TABLE,
11
+
12
+ reservedTableNames: [
13
+ USERS_TABLE,
14
+ ROLES_TABLE,
15
+ USERS_ROLES_TABLE,
16
+ ROLES_PERMISSIONS_TABLE,
17
+ ],
18
+
19
+ constraints: {
20
+ UNIQUE_USERS_ROLE: 'unique_users_role',
21
+ UNIQUE_ROLES_TABLE: 'unique_ROLES_TABLE',
22
+ },
23
+
24
+ tableFields: {
25
+ ID: 'id',
26
+
27
+ // _role fields
28
+ ROLE_NAME: 'name',
29
+
30
+ // _user fields
31
+ USERNAME: 'username',
32
+ HASHED_PASSWORD: 'hashed_password',
33
+ SALT: 'salt',
34
+ IS_SUPERUSER: 'is_superuser',
35
+
36
+ // _roles_permissions fields
37
+ ROLE_ID: 'role_id',
38
+ TABLE_NAME: 'table_name',
39
+ CREATE: 'create',
40
+ READ: 'read',
41
+ UPDATE: 'update',
42
+ DELETE: 'delete',
43
+
44
+ // _users_roles fields
45
+ USER_ID: 'user_id',
46
+ },
47
+ };
@@ -0,0 +1,16 @@
1
+ const { rowService } = require('../../services');
2
+ const { dbConstants } = require('../../constants');
3
+
4
+ const { USERS_TABLE } = dbConstants;
5
+
6
+ const isUsernameTaken = (username) => {
7
+ const users = rowService.get({
8
+ tableName: USERS_TABLE,
9
+ whereString: 'WHERE username=?',
10
+ whereStringValues: [username],
11
+ });
12
+
13
+ return users.length > 0;
14
+ };
15
+
16
+ module.exports = { isUsernameTaken };
@@ -0,0 +1,5 @@
1
+ const users = require('./user');
2
+ const token = require('./token');
3
+ const tables = require('./tables');
4
+
5
+ module.exports = { ...users, ...token, ...tables };
@@ -0,0 +1,96 @@
1
+ const { tableService, rowService } = require('../../services');
2
+ const { constantRoles, dbConstants } = require('../../constants');
3
+ const schema = require('../../db/schema');
4
+
5
+ const {
6
+ USERS_TABLE,
7
+ ROLES_TABLE,
8
+ USERS_ROLES_TABLE,
9
+ ROLES_PERMISSIONS_TABLE,
10
+ constraints,
11
+ tableFields,
12
+ } = dbConstants;
13
+
14
+ const createDefaultTables = async () => {
15
+ let roleId;
16
+
17
+ // check if the default tables are already created
18
+ const roleTable = tableService.checkTableExists(ROLES_TABLE);
19
+ const usersTable = tableService.checkTableExists(USERS_TABLE);
20
+ const rolesPermissionTable = tableService.checkTableExists(
21
+ ROLES_PERMISSIONS_TABLE,
22
+ );
23
+ const usersRolesTable = tableService.checkTableExists(USERS_ROLES_TABLE);
24
+
25
+ // create _users table
26
+ if (!usersTable) {
27
+ tableService.createTable(USERS_TABLE, schema.userSchema);
28
+ }
29
+
30
+ // create _users_roles table
31
+ if (!usersRolesTable) {
32
+ tableService.createTable(
33
+ USERS_ROLES_TABLE,
34
+
35
+ schema.usersRoleSchema,
36
+ {
37
+ multipleUniqueConstraints: {
38
+ name: constraints.UNIQUE_USERS_ROLE,
39
+ fields: [tableFields.USER_ID, tableFields.USER_ID],
40
+ },
41
+ },
42
+ );
43
+ }
44
+
45
+ // create _roles table
46
+ if (!roleTable) {
47
+ tableService.createTable(ROLES_TABLE, schema.roleSchema);
48
+
49
+ // create a default role in the _roles table
50
+ const role = rowService.save({
51
+ tableName: ROLES_TABLE,
52
+ fields: { name: constantRoles.DEFAULT_ROLE },
53
+ });
54
+ roleId = role.lastInsertRowid;
55
+ }
56
+
57
+ // create _roles_permissions table
58
+ if (!rolesPermissionTable && roleId) {
59
+ tableService.createTable(
60
+ ROLES_PERMISSIONS_TABLE,
61
+ schema.rolePermissionSchema,
62
+ {
63
+ multipleUniqueConstraints: {
64
+ name: constraints.UNIQUE_ROLES_TABLE,
65
+ fields: [tableFields.ROLE_ID, tableFields.TABLE_NAME],
66
+ },
67
+ },
68
+ );
69
+
70
+ // fetch all DB tables
71
+ const tables = tableService.listTables();
72
+
73
+ // add permission for the default role (for each db table)
74
+ const permissions = [];
75
+ for (const table of tables) {
76
+ permissions.push({
77
+ role_id: roleId,
78
+ table_name: table.name,
79
+ create: 'false',
80
+ read: 'true',
81
+ update: 'false',
82
+ delete: 'false',
83
+ });
84
+ }
85
+
86
+ // store the permissions in the db
87
+ rowService.bulkWrite({
88
+ tableName: ROLES_PERMISSIONS_TABLE,
89
+ fields: permissions,
90
+ });
91
+ }
92
+ };
93
+
94
+ module.exports = {
95
+ createDefaultTables,
96
+ };
@@ -0,0 +1,243 @@
1
+ const { authService } = require('../../services');
2
+ const { responseMessages, authConstants } = require('../../constants');
3
+ const config = require('../../config');
4
+ const {
5
+ comparePasswords,
6
+ generateToken,
7
+ decodeToken,
8
+ toBoolean,
9
+ } = require('../../utils');
10
+
11
+ const { successMessage, errorMessage } = responseMessages;
12
+
13
+ const obtainAccessToken = async (req, res) => {
14
+ /*
15
+ #swagger.tags = ['Auth']
16
+ #swagger.summary = 'Obtain Access Token'
17
+ #swagger.description = 'Endpoint to generate access and refresh tokens'
18
+
19
+ #swagger.parameters['body'] = {
20
+ in: 'body',
21
+ required: true,
22
+ type: 'object',
23
+ schema: { $ref: '#/definitions/ObtainAccessTokenRequestBody' }
24
+ }
25
+ */
26
+
27
+ // extract payload
28
+ const { username, password } = req.body.fields;
29
+
30
+ try {
31
+ // check if the username exists in the Db
32
+ const users = authService.getUsersByUsername({ username });
33
+
34
+ if (users.length <= 0) {
35
+ return res
36
+ .status(401)
37
+ .send({ message: errorMessage.INVALID_USERNAME_PASSWORD_ERROR });
38
+ }
39
+
40
+ // check if the password is valid
41
+ const user = users[0];
42
+ const isMatch = await comparePasswords(password, user.hashed_password);
43
+
44
+ if (!isMatch) {
45
+ return res
46
+ .status(401)
47
+ .send({ message: errorMessage.INVALID_USERNAME_PASSWORD_ERROR });
48
+ /*
49
+ #swagger.responses[401] = {
50
+ description: 'Invalid username or password error',
51
+ schema: {
52
+ $ref: '#/definitions/InvalidCredentialErrorResponse'
53
+ }
54
+ }
55
+ */
56
+ }
57
+
58
+ let permissions, roleIds;
59
+
60
+ // if the user is not a superuser get the role and its permission from the DB
61
+ if (!toBoolean(user.is_superuser)) {
62
+ const roleData = getUsersRoleAndPermission({
63
+ userId: user.id,
64
+ res,
65
+ });
66
+
67
+ permissions = roleData.permissions;
68
+ roleIds = roleData.roleIds;
69
+ }
70
+
71
+ const payload = {
72
+ username: user.username,
73
+ userId: user.id,
74
+ isSuperuser: user.is_superuser,
75
+ roleIds,
76
+ permissions,
77
+ };
78
+
79
+ // generate an access token
80
+ const accessToken = await generateToken(
81
+ { subject: authConstants.ACCESS_TOKEN_SUBJECT, ...payload },
82
+ config.tokenSecret,
83
+ config.accessTokenExpirationTime,
84
+ );
85
+
86
+ // generate a refresh token
87
+ const refreshToken = await generateToken(
88
+ { subject: authConstants.REFRESH_TOKEN_SUBJECT, ...payload },
89
+ config.tokenSecret,
90
+ config.refreshTokenExpirationTime,
91
+ );
92
+
93
+ // set the token in the cookie
94
+ let cookieOptions = { httpOnly: true, secure: false, Path: '/' };
95
+ res.cookie(authConstants.ACCESS_TOKEN_SUBJECT, accessToken, cookieOptions);
96
+ res.cookie(
97
+ authConstants.REFRESH_TOKEN_SUBJECT,
98
+ refreshToken,
99
+ cookieOptions,
100
+ );
101
+
102
+ res
103
+ .status(201)
104
+ .send({ message: successMessage.SUCCESS, data: { userId: user.id } });
105
+
106
+ /*
107
+ #swagger.responses[201] = {
108
+ description: 'Access token and Refresh token generated',
109
+ schema: {
110
+ $ref: '#/definitions/ObtainAccessTokenSuccessResponse'
111
+ }
112
+ }
113
+ */
114
+ } catch (error) {
115
+ console.log(error);
116
+ return res.status(500).json({
117
+ message: errorMessage.SERVER_ERROR,
118
+ });
119
+ }
120
+ };
121
+
122
+ const refreshAccessToken = async (req, res) => {
123
+ /*
124
+ #swagger.tags = ['Auth']
125
+ #swagger.summary = 'Refresh Access Token'
126
+ #swagger.description = 'Endpoint to refresh access and refresh tokens'
127
+ */
128
+
129
+ try {
130
+ // extract the payload from the token and verify it
131
+ const payload = await decodeToken(
132
+ req.cookies.refreshToken,
133
+ config.tokenSecret,
134
+ );
135
+
136
+ // find the user
137
+ const users = authService.getUsersById({ userId: payload.userId });
138
+
139
+ if (users.length <= 0) {
140
+ return res
141
+ .status(401)
142
+ .send({ message: errorMessage.USER_NOT_FOUND_ERROR });
143
+
144
+ /*
145
+ #swagger.responses[401] = {
146
+ description: 'User not found error',
147
+ schema: {
148
+ $ref: '#/definitions/UserNotFoundErrorResponse'
149
+ }
150
+ }
151
+ */
152
+ }
153
+
154
+ let permissions, roleIds;
155
+ const user = users[0];
156
+
157
+ // if the user is not a superuser get the role and its permission from the DB
158
+ if (!toBoolean(user.is_superuser)) {
159
+ const roleData = getUsersRoleAndPermission({
160
+ userId: user.id,
161
+ res,
162
+ });
163
+
164
+ permissions = roleData.permissions;
165
+ roleIds = roleData.roleIds;
166
+ }
167
+
168
+ const newPayload = {
169
+ username: user.username,
170
+ userId: user.id,
171
+ isSuperuser: user.is_superuser,
172
+ roleIds,
173
+ permissions,
174
+ };
175
+
176
+ // generate an access token
177
+ const accessToken = await generateToken(
178
+ { subject: authConstants.ACCESS_TOKEN_SUBJECT, ...newPayload },
179
+ config.tokenSecret,
180
+ config.accessTokenExpirationTime,
181
+ );
182
+
183
+ // generate a refresh token
184
+ const refreshToken = await generateToken(
185
+ { subject: authConstants.REFRESH_TOKEN_SUBJECT, ...newPayload },
186
+ config.tokenSecret,
187
+ config.refreshTokenExpirationTime,
188
+ );
189
+
190
+ // set the token in the cookie
191
+ let cookieOptions = { httpOnly: true, secure: false, Path: '/' };
192
+ res.cookie(authConstants.ACCESS_TOKEN_SUBJECT, accessToken, cookieOptions);
193
+ res.cookie(
194
+ authConstants.REFRESH_TOKEN_SUBJECT,
195
+ refreshToken,
196
+ cookieOptions,
197
+ );
198
+
199
+ res
200
+ .status(200)
201
+ .send({ message: successMessage.SUCCESS, data: { userId: user.id } });
202
+
203
+ /*
204
+ #swagger.responses[200] = {
205
+ description: 'Access token refreshed',
206
+ schema: {
207
+ $ref: '#/definitions/RefreshAccessTokenSuccessResponse'
208
+ }
209
+ }
210
+ */
211
+ } catch (error) {
212
+ res.status(403).send({ message: errorMessage.INVALID_REFRESH_TOKEN_ERROR });
213
+ /*
214
+ #swagger.responses[401] = {
215
+ description: 'Invalid refresh token error',
216
+ schema: {
217
+ $ref: '#/definitions/InvalidRefreshTokenErrorResponse'
218
+ }
219
+ }
220
+ */
221
+ }
222
+ };
223
+
224
+ const getUsersRoleAndPermission = ({ userId, res }) => {
225
+ const userRoles = authService.getUserRoleByUserId({ userId });
226
+
227
+ if (userRoles <= 0) {
228
+ res.status(401).send({ message: errorMessage.ROLE_NOT_FOUND_ERROR });
229
+ throw new Error(errorMessage.ROLE_NOT_FOUND_ERROR);
230
+ }
231
+
232
+ const roleIds = userRoles.map((role) => role.role_id);
233
+
234
+ // get the permission of the role
235
+ const permissions = authService.getPermissionByRoleIds({ roleIds });
236
+
237
+ return { userRoles, roleIds, permissions };
238
+ };
239
+
240
+ module.exports = {
241
+ obtainAccessToken,
242
+ refreshAccessToken,
243
+ };