soul-cli 0.6.0 → 0.7.0

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 (64) 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 +186 -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/extensions-examples.md +167 -0
  18. package/docs/logo.png +0 -0
  19. package/docs/soul-studio.png +0 -0
  20. package/docs/ws/rows-examples.md +122 -0
  21. package/docs/ws-examples.md +42 -0
  22. package/package.json +17 -2
  23. package/src/cli.js +59 -1
  24. package/src/commands.js +22 -0
  25. package/src/config/index.js +48 -3
  26. package/src/constants/api.js +26 -0
  27. package/src/constants/auth.js +5 -0
  28. package/src/constants/index.js +13 -0
  29. package/src/constants/messages.js +41 -0
  30. package/src/constants/roles.js +3 -0
  31. package/src/constants/tables.js +47 -0
  32. package/src/controllers/auth/common.js +16 -0
  33. package/src/controllers/auth/index.js +5 -0
  34. package/src/controllers/auth/tables.js +96 -0
  35. package/src/controllers/auth/token.js +243 -0
  36. package/src/controllers/auth/user.js +394 -0
  37. package/src/controllers/auth.test.js +372 -0
  38. package/src/controllers/rows.js +30 -31
  39. package/src/controllers/rows.test.js +209 -18
  40. package/src/controllers/tables.test.js +58 -28
  41. package/src/db/schema.js +118 -0
  42. package/src/index.js +32 -7
  43. package/src/middlewares/api.js +79 -0
  44. package/src/middlewares/auth.js +85 -0
  45. package/src/middlewares/broadcast.js +1 -1
  46. package/src/middlewares/validation.js +3 -2
  47. package/src/routes/auth.js +29 -0
  48. package/src/routes/rows.js +17 -5
  49. package/src/routes/tables.js +26 -4
  50. package/src/schemas/auth.js +67 -0
  51. package/src/schemas/index.js +6 -1
  52. package/src/schemas/rows.js +20 -0
  53. package/src/schemas/tables.js +18 -2
  54. package/src/server.js +3 -2
  55. package/src/services/authService.js +78 -0
  56. package/src/services/index.js +2 -1
  57. package/src/services/rowService.js +36 -7
  58. package/src/services/tableService.js +127 -1
  59. package/src/swagger/index.js +67 -0
  60. package/src/swagger/swagger.json +292 -60
  61. package/src/tests/index.js +4 -5
  62. package/src/tests/testData.js +72 -27
  63. package/src/utils/index.js +78 -0
  64. /package/{src/services/.gitkeep → docs/extensions/api-examples.js} +0 -0
@@ -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
+ };
@@ -0,0 +1,394 @@
1
+ const { rowService, authService } = require('../../services');
2
+ const {
3
+ apiConstants,
4
+ dbConstants,
5
+ responseMessages,
6
+ authConstants,
7
+ } = require('../../constants');
8
+ const config = require('../../config');
9
+ const {
10
+ hashPassword,
11
+ checkPasswordStrength,
12
+ comparePasswords,
13
+ } = require('../../utils');
14
+
15
+ const { USERS_TABLE, USERS_ROLES_TABLE, tableFields } = dbConstants;
16
+
17
+ const { SALT_ROUNDS } = authConstants;
18
+
19
+ const { successMessage, errorMessage, infoMessage } = responseMessages;
20
+
21
+ const updateSuperuser = async (fields) => {
22
+ const { id, password, is_superuser } = fields;
23
+ let newHashedPassword, newSalt;
24
+ let fieldsString = '';
25
+
26
+ try {
27
+ // find the user by using the id field
28
+ const users = authService.getRoleByUserId({ id });
29
+
30
+ // abort if the id is invalid
31
+ if (users.length === 0) {
32
+ console.log(errorMessage.USER_NOT_FOUND_ERROR);
33
+ process.exit(1);
34
+ }
35
+
36
+ // check if the is_superuser field is passed
37
+ if (is_superuser !== undefined) {
38
+ fieldsString = `${tableFields.IS_SUPERUSER} = '${is_superuser}'`;
39
+ }
40
+
41
+ // if the password is sent from the CLI, update it
42
+ if (password) {
43
+ // check if the password is weak
44
+ if (
45
+ [apiConstants.PASSWORD.TOO_WEAK, apiConstants.PASSWORD.WEAK].includes(
46
+ checkPasswordStrength(password),
47
+ )
48
+ ) {
49
+ console.log(errorMessage.WEAK_PASSWORD_ERROR);
50
+ process.exit(1);
51
+ }
52
+
53
+ //hash the password
54
+ const { hashedPassword, salt } = await hashPassword(
55
+ password,
56
+ SALT_ROUNDS,
57
+ );
58
+ newHashedPassword = hashedPassword;
59
+ newSalt = salt;
60
+
61
+ fieldsString = `${fieldsString ? fieldsString + ', ' : ''} ${
62
+ tableFields.HASHED_PASSWORD
63
+ } = '${newHashedPassword}', ${tableFields.SALT} = '${newSalt}'`;
64
+ }
65
+
66
+ // update the user
67
+ rowService.update({
68
+ tableName: USERS_TABLE,
69
+ lookupField: tableFields.ID,
70
+ fieldsString,
71
+ pks: `${id}`,
72
+ });
73
+
74
+ console.log(successMessage.USER_UPDATE_SUCCESS);
75
+ process.exit(1);
76
+ } catch (error) {
77
+ console.log(error);
78
+ }
79
+ };
80
+
81
+ const registerUser = async (req, res) => {
82
+ /*
83
+ #swagger.tags = ['Auth']
84
+ #swagger.summary = 'Register User'
85
+ #swagger.description = 'Endpoint to signup'
86
+
87
+ #swagger.parameters['username'] = {
88
+ in: 'body',
89
+ required: true,
90
+ type: 'object',
91
+ schema: { $ref: '#/definitions/UserRegistrationRequestBody' }
92
+ }
93
+ */
94
+
95
+ const { username, password } = req.body.fields;
96
+
97
+ try {
98
+ if (!username) {
99
+ return res
100
+ .status(400)
101
+ .send({ message: errorMessage.USERNAME_REQUIRED_ERROR });
102
+ }
103
+
104
+ if (!password) {
105
+ return res
106
+ .status(400)
107
+ .send({ message: errorMessage.PASSWORD_REQUIRED_ERROR });
108
+ }
109
+
110
+ // check if the username is taken
111
+ const users = authService.getUsersByUsername({ username });
112
+
113
+ if (users.length > 0) {
114
+ return res
115
+ .status(409)
116
+ .send({ message: errorMessage.USERNAME_TAKEN_ERROR });
117
+
118
+ /*
119
+ #swagger.responses[409] = {
120
+ description: 'Username taken error',
121
+ schema: {
122
+ $ref: '#/definitions/UsernameTakenErrorResponse'
123
+ }
124
+ }
125
+ */
126
+ }
127
+
128
+ // check if the password is weak
129
+ if (
130
+ [apiConstants.PASSWORD.TOO_WEAK, apiConstants.PASSWORD.WEAK].includes(
131
+ checkPasswordStrength(password),
132
+ )
133
+ ) {
134
+ return res.status(400).send({
135
+ message: errorMessage.WEAK_PASSWORD_ERROR,
136
+ });
137
+
138
+ /*
139
+ #swagger.responses[400] = {
140
+ description: 'Weak password error',
141
+ schema: {
142
+ $ref: '#/definitions/WeakPasswordErrorResponse'
143
+ }
144
+ }
145
+ */
146
+ }
147
+
148
+ // hash the password
149
+ const { salt, hashedPassword } = await hashPassword(password, SALT_ROUNDS);
150
+
151
+ // create the user
152
+ const newUser = rowService.save({
153
+ tableName: USERS_TABLE,
154
+ fields: {
155
+ username,
156
+ salt,
157
+ hashed_password: hashedPassword,
158
+ is_superuser: 'false',
159
+ },
160
+ });
161
+
162
+ // find the default role from the DB
163
+ const defaultRole = authService.getDefaultRole();
164
+
165
+ if (defaultRole.length <= 0) {
166
+ return res.status(500).send({
167
+ message: errorMessage.DEFAULT_ROLE_NOT_CREATED_ERROR,
168
+ });
169
+ /*
170
+ #swagger.responses[500] = {
171
+ description: 'Server error',
172
+ schema: {
173
+ $ref: '#/definitions/DefaultRoleNotCreatedErrorResponse'
174
+ }
175
+ }
176
+ */
177
+ }
178
+
179
+ // create a role for the user
180
+ rowService.save({
181
+ tableName: USERS_ROLES_TABLE,
182
+ fields: { user_id: newUser.lastInsertRowid, role_id: defaultRole[0].id },
183
+ });
184
+
185
+ res.status(201).send({ message: successMessage.ROW_INSERTED });
186
+
187
+ /*
188
+ #swagger.responses[201] = {
189
+ description: 'Row inserted',
190
+ schema: {
191
+ $ref: '#/definitions/InsertRowSuccessResponse'
192
+ }
193
+ }
194
+ */
195
+ } catch (error) {
196
+ console.log(error);
197
+ res.status(500).send({ message: errorMessage.SERVER_ERROR });
198
+ }
199
+ };
200
+
201
+ const changePassword = async (req, res) => {
202
+ /*
203
+ #swagger.tags = ['Auth']
204
+ #swagger.summary = 'Change Password'
205
+ #swagger.description = 'Endpoint to change a password'
206
+
207
+ #swagger.parameters['body'] = {
208
+ in: 'body',
209
+ required: true,
210
+ type: 'object',
211
+ schema: {
212
+ $ref: '#/definitions/ChangePasswordRequestBody'
213
+ }
214
+ }
215
+ */
216
+
217
+ const userInfo = req.user;
218
+ const { currentPassword, newPassword } = req.body.fields;
219
+
220
+ try {
221
+ // get the user from the Db
222
+ const users = authService.getUsersById({ userId: userInfo.userId });
223
+
224
+ if (users.length <= 0) {
225
+ return res
226
+ .status(401)
227
+ .send({ message: errorMessage.USER_NOT_FOUND_ERROR });
228
+ }
229
+
230
+ const user = users[0];
231
+
232
+ // check if the users current password is valid
233
+ const isMatch = await comparePasswords(
234
+ currentPassword,
235
+ user.hashed_password,
236
+ );
237
+
238
+ if (!isMatch) {
239
+ return res
240
+ .status(401)
241
+ .send({ message: errorMessage.INVALID_CURRENT_PASSWORD_ERROR });
242
+ /*
243
+ #swagger.responses[401] = {
244
+ description: 'User not found error',
245
+ schema: {
246
+ $ref: '#/definitions/InvalidPasswordErrorResponse'
247
+ }
248
+ }
249
+ */
250
+ }
251
+
252
+ // check if the new password is strong
253
+ if (
254
+ [apiConstants.PASSWORD.TOO_WEAK, apiConstants.PASSWORD.WEAK].includes(
255
+ checkPasswordStrength(newPassword),
256
+ )
257
+ ) {
258
+ return res.status(400).send({
259
+ message: errorMessage.WEAK_PASSWORD_ERROR,
260
+ });
261
+
262
+ /*
263
+ #swagger.responses[400] = {
264
+ description: 'Weak password error',
265
+ schema: {
266
+ $ref: '#/definitions/WeakPasswordErrorResponse'
267
+ }
268
+ }
269
+ */
270
+ }
271
+
272
+ // hash the password
273
+ const { salt, hashedPassword } = await hashPassword(
274
+ newPassword,
275
+ SALT_ROUNDS,
276
+ );
277
+
278
+ user.salt = salt;
279
+ user.hashed_password = hashedPassword;
280
+
281
+ // update the user
282
+ rowService.update({
283
+ tableName: USERS_TABLE,
284
+ lookupField: tableFields.ID,
285
+ fieldsString: `${tableFields.HASHED_PASSWORD} = '${hashedPassword}', ${tableFields.SALT} = '${salt}'`,
286
+ pks: `${user.id}`,
287
+ });
288
+
289
+ res.status(200).send({
290
+ message: successMessage.PASSWORD_UPDATE_SUCCESS,
291
+ data: { id: user.id, username: user.username },
292
+ });
293
+
294
+ /*
295
+ #swagger.responses[200] = {
296
+ description: 'Weak password error',
297
+ schema: {
298
+ $ref: '#/definitions/ChangePasswordSuccessResponse'
299
+ }
300
+ }
301
+ */
302
+ } catch (error) {
303
+ res.status(500).send({ message: errorMessage.SERVER_ERROR });
304
+ }
305
+ };
306
+
307
+ const createInitialUser = async () => {
308
+ // extract some fields from the environment variables or from the CLI
309
+ const { initialUserUsername: username, initialUserPassword: password } =
310
+ config;
311
+
312
+ try {
313
+ // check if there are users in the DB
314
+ const users = authService.getAllUsers();
315
+
316
+ if (users.length <= 0) {
317
+ // check if initial users username is passed from the env or CLI
318
+ if (!username) {
319
+ console.error(errorMessage.INITIAL_USER_USERNAME_NOT_PASSED_ERROR);
320
+ process.exit(1);
321
+ }
322
+
323
+ // check if initial users password is passed from the env or CLI
324
+ if (!password) {
325
+ console.error(errorMessage.INITIAL_USER_PASSWORD_NOT_PASSED_ERROR);
326
+ process.exit(1);
327
+ }
328
+
329
+ // check if the usernmae is taken
330
+ const users = authService.getUsersByUsername({ username });
331
+
332
+ if (users.length > 0) {
333
+ console.error(errorMessage.USERNAME_TAKEN_ERROR);
334
+ process.exit(1);
335
+ }
336
+
337
+ // check if the password is strong
338
+ if (
339
+ [apiConstants.PASSWORD.TOO_WEAK, apiConstants.PASSWORD.WEAK].includes(
340
+ checkPasswordStrength(password),
341
+ )
342
+ ) {
343
+ console.error(errorMessage.WEAK_PASSWORD_ERROR);
344
+ process.exit(1);
345
+ }
346
+
347
+ // hash the password
348
+ const { hashedPassword, salt } = await hashPassword(
349
+ password,
350
+ SALT_ROUNDS,
351
+ );
352
+
353
+ // create the initial user
354
+ const { lastInsertRowid: userId } = rowService.save({
355
+ tableName: USERS_TABLE,
356
+ fields: {
357
+ username,
358
+ hashed_password: hashedPassword,
359
+ salt,
360
+ is_superuser: 'false',
361
+ },
362
+ });
363
+
364
+ // get the default role from the DB
365
+ const roles = authService.getDefaultRole();
366
+
367
+ if (roles.length <= 0) {
368
+ console.log(errorMessage.DEFAULT_ROLE_NOT_CREATED_ERROR);
369
+ process.exit(1);
370
+ }
371
+
372
+ const defaultRoleId = roles[0].id;
373
+
374
+ // create a _users_role for the initial user
375
+ rowService.save({
376
+ tableName: USERS_ROLES_TABLE,
377
+ fields: { user_id: userId, role_id: defaultRoleId },
378
+ });
379
+
380
+ console.log(successMessage.INITIAL_USER_CREATED_SUCCESS);
381
+ } else {
382
+ console.log(infoMessage.INITIAL_USER_ALREADY_CREATED);
383
+ }
384
+ } catch (error) {
385
+ console.log(error);
386
+ }
387
+ };
388
+
389
+ module.exports = {
390
+ updateSuperuser,
391
+ registerUser,
392
+ changePassword,
393
+ createInitialUser,
394
+ };