soul-cli 0.6.1 → 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 +48 -55
  39. package/src/controllers/rows.test.js +146 -40
  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 +23 -10
  63. package/src/utils/index.js +78 -0
  64. /package/{src/services/.gitkeep → docs/extensions/api-examples.js} +0 -0
@@ -0,0 +1,122 @@
1
+ ## Rows
2
+
3
+ ### 1. Rows realtime changes
4
+
5
+ To subscribe to realtime changes (Insert, Update and Delete) in rows of a certain table,
6
+ use `tables/<table-name>` endpoint.
7
+
8
+ ```bash
9
+ wscat -c ws://localhost:8000/ws/tables/Employee
10
+ ```
11
+
12
+ It should respond with the following message:
13
+
14
+ ```json
15
+ {
16
+ "message": "Subscribed to table \"Employee\""
17
+ }
18
+ ```
19
+
20
+ Note that it's ready to receive messages.
21
+
22
+ Then to test it, in a new terminal, insert a new row in the table `Employee`:
23
+
24
+ ```bash
25
+ curl --request POST \
26
+ --url http://localhost:8000/api/tables/Employee/rows \
27
+ --header 'Content-Type: application/json' \
28
+ --data '{
29
+ "fields": {
30
+ "FirstName": "Damien",
31
+ "LastName": "Rice"
32
+ }
33
+ }'
34
+ ```
35
+
36
+ Checkout `wscat` terminal, it should respond with the following message:
37
+
38
+ ```json
39
+ {
40
+ "type": "INSERT",
41
+ "data": {
42
+ "pk": 10,
43
+ "FirstName": "Damien",
44
+ "LastName": "Rice"
45
+ }
46
+ }
47
+ ```
48
+
49
+ Then to test update changes, let's change the `FirstName` of the row with `pk` 10:
50
+
51
+ ```bash
52
+ curl --request PUT \
53
+ --url http://localhost:8000/api/tables/Employee/rows/10 \
54
+ --header 'Content-Type: application/json' \
55
+ --data '{
56
+ "fields": {
57
+ "FirstName": "Glen"
58
+ }
59
+ }'
60
+ ```
61
+
62
+ Checkout `wscat` terminal, it should respond with the following message:
63
+
64
+ ```json
65
+ {
66
+ "type": "UPDATE",
67
+ "_lookup_field": "EmployeeId",
68
+ "data": {
69
+ "pks": ["10"],
70
+ "FirstName": "Glen"
71
+ }
72
+ }
73
+ ```
74
+
75
+ While we're testing update changes, let's see how it works in bulk update mode:
76
+
77
+ ```bash
78
+ curl --request PUT \
79
+ --url http://localhost:8000/api/tables/Employee/rows/8,9,10 \
80
+ --header 'Content-Type: application/json' \
81
+ --data '{
82
+ "fields": {
83
+ "FirstName": "David"
84
+ }
85
+ }'
86
+ ```
87
+
88
+ Note comma-separated `lookup-values` in the URL. (8,9,10)
89
+
90
+ Checkout `wscat` terminal, it should respond with the following message:
91
+
92
+ ```json
93
+ {
94
+ "type": "UPDATE",
95
+ "_lookup_field": "EmployeeId",
96
+ "data": {
97
+ "pks": ["8", "9", "10"],
98
+ "FirstName": "David"
99
+ }
100
+ }
101
+ ```
102
+
103
+ Then to test delete changes, let's delete the row with `pk` 10:
104
+
105
+ ```bash
106
+ curl --request DELETE \
107
+ --url http://localhost:8000/api/tables/Employee/rows/10
108
+ ```
109
+
110
+ Checkout `wscat` terminal, it should respond with the following message:
111
+
112
+ ```json
113
+ {
114
+ "type": "DELETE",
115
+ "_lookup_field": "EmployeeId",
116
+ "data": {
117
+ "pks": ["10"]
118
+ }
119
+ }
120
+ ```
121
+
122
+ That's it for realtime changes.
@@ -0,0 +1,42 @@
1
+ # Websocket Examples
2
+
3
+ Soul realtime right now only support `rows` changes.
4
+
5
+ ## Setup Environment
6
+
7
+ To follow the below examples we need to download a sample database, install Soul CLI and also a websocket client to test.
8
+ (Please note that you can use any websocket client you want, e.g. Postman, Insomnia, etc.)
9
+
10
+ ### Download Sample Database
11
+
12
+ ```bash
13
+ wget https://raw.githubusercontent.com/lerocha/chinook-database/master/ChinookDatabase/DataSources/Chinook_Sqlite.sqlite # Download sample sqlite database
14
+ ```
15
+
16
+ ### Install Websocket client
17
+
18
+ ```bash
19
+ npm i -g wscat # Install websocket client
20
+ ```
21
+
22
+ ### Using Soul CLI
23
+ ```bash
24
+ npm install -g soul-cli
25
+ soul -d ./Chinook_Sqlite.sqlite -p 8000
26
+ ```
27
+
28
+ <details>
29
+ <summary>Or Using Local Development</summary>
30
+
31
+ ```bash
32
+ git clone https://github.com/thevahidal/soul # Clone project
33
+ npm install # Install dependencies
34
+ npm link # might need `sudo`
35
+ soul -d ./Chinook_Sqlite.sqlite -p 8000
36
+ ```
37
+ </details>
38
+
39
+
40
+ ## Namespaces
41
+
42
+ 1. [/ws/tables](/docs/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.6.1",
3
+ "version": "0.7.0",
4
4
  "description": "A SQLite REST and Realtime server",
5
5
  "main": "src/server.js",
6
6
  "bin": {
@@ -11,7 +11,10 @@
11
11
  "dev": "npm run swagger-autogen && cross-env NO_CLI=true nodemon src/server.js",
12
12
  "cli": "nodemon src/server.js --database foobar.db",
13
13
  "swagger-autogen": "cross-env NO_CLI=true node src/swagger/index.js",
14
- "test": "cross-env NODE_ENV=test NO_CLI=true DB=test.db CORE_PORT=8001 jest --testTimeout=10000"
14
+ "test": "cross-env CI=true NODE_ENV=test NO_CLI=true DB=test.db CORE_PORT=8001 jest --testTimeout=10000",
15
+ "prepare": "husky install",
16
+ "lint": "eslint . --fix --max-warnings=0",
17
+ "format": "prettier . --write"
15
18
  },
16
19
  "repository": {
17
20
  "type": "git",
@@ -24,14 +27,18 @@
24
27
  },
25
28
  "homepage": "https://github.com/thevahidal/soul#readme",
26
29
  "dependencies": {
30
+ "bcrypt": "^5.1.1",
27
31
  "better-sqlite3": "^8.1.0",
28
32
  "body-parser": "^1.20.2",
33
+ "check-password-strength": "^2.0.7",
34
+ "cookie-parser": "^1.4.6",
29
35
  "cors": "^2.8.5",
30
36
  "dotenv": "^16.0.3",
31
37
  "express": "^4.18.2",
32
38
  "express-rate-limit": "^6.7.0",
33
39
  "express-winston": "^4.2.0",
34
40
  "joi": "^17.8.3",
41
+ "jsonwebtoken": "^9.0.2",
35
42
  "soul-studio": "^0.0.1",
36
43
  "swagger-ui-express": "^4.6.1",
37
44
  "winston": "^3.8.2",
@@ -40,8 +47,12 @@
40
47
  },
41
48
  "devDependencies": {
42
49
  "cross-env": "^7.0.3",
50
+ "eslint": "^8.54.0",
51
+ "eslint-config-prettier": "^9.0.0",
52
+ "husky": "^8.0.3",
43
53
  "jest": "^29.4.3",
44
54
  "nodemon": "^2.0.20",
55
+ "prettier": "3.1.0",
45
56
  "supertest": "^6.3.3",
46
57
  "swagger-autogen": "^2.23.1"
47
58
  },
@@ -52,5 +63,9 @@
52
63
  ],
53
64
  "globalSetup": "./src/tests/globalSetup.js",
54
65
  "globalTeardown": "./src/tests/globalTeardown.js"
66
+ },
67
+ "lint-staged": {
68
+ "*.js": "eslint --fix",
69
+ "*.{js,css,md,html,json}": "prettier --write"
55
70
  }
56
71
  }
package/src/cli.js CHANGED
@@ -46,11 +46,69 @@ if (process.env.NO_CLI !== 'true') {
46
46
  type: 'string',
47
47
  demandOption: false,
48
48
  })
49
+ .options('a', {
50
+ alias: 'auth',
51
+ describe: 'Enable authentication and authorization',
52
+ type: 'boolean',
53
+ default: false,
54
+ demandOption: false,
55
+ })
56
+ .options('ts', {
57
+ alias: 'tokensecret',
58
+ describe: 'JWT secret for the access and refresh tokens',
59
+ type: 'string',
60
+ default: null,
61
+ demandOption: false,
62
+ })
63
+ .options('atet', {
64
+ alias: 'accesstokenexpirationtime',
65
+ describe: 'JWT expiration time for access token',
66
+ type: 'string',
67
+ default: '5H',
68
+ demandOption: false,
69
+ })
70
+ .options('rtet', {
71
+ alias: 'refreshtokenexpirationtime',
72
+ describe: 'JWT expiration time for refresh token',
73
+ type: 'string',
74
+ default: '3D',
75
+ demandOption: false,
76
+ })
77
+ .options('iuu', {
78
+ alias: 'initialuserusername',
79
+ describe: 'Initial superuser username',
80
+ type: 'string',
81
+ demandOption: false,
82
+ })
83
+ .options('iup', {
84
+ alias: 'initialuserpassword',
85
+ describe: 'Initial superuser password',
86
+ type: 'string',
87
+ demandOption: false,
88
+ })
49
89
  .options('S', {
50
90
  alias: 'studio',
51
91
  describe: 'Start Soul Studio in parallel',
52
92
  type: 'boolean',
53
- demandOption: false
93
+ demandOption: false,
94
+ })
95
+ .command('updatesuperuser', 'Update a superuser', (yargs) => {
96
+ return yargs
97
+ .option('id', {
98
+ describe: 'The ID of the superuser you want to update',
99
+ type: 'number',
100
+ demandOption: true,
101
+ })
102
+ .option('password', {
103
+ describe: 'The new password for the superuser you want to update',
104
+ type: 'string',
105
+ demandOption: false,
106
+ })
107
+ .option('is_superuser', {
108
+ describe: 'The role of the superuser you want to update',
109
+ type: 'boolean',
110
+ demandOption: false,
111
+ });
54
112
  })
55
113
  .help(true).argv;
56
114
  }
@@ -0,0 +1,22 @@
1
+ const { yargs } = require('./cli');
2
+ const { updateSuperuser } = require('./controllers/auth');
3
+
4
+ const { argv } = yargs;
5
+
6
+ const runCLICommands = () => {
7
+ // if the updatesuperuser command is passed from the CLI execute the updatesuperuser function
8
+ if (argv._.includes('updatesuperuser')) {
9
+ const { id, password, is_superuser } = argv;
10
+
11
+ if (!password && !is_superuser) {
12
+ console.log(
13
+ 'Please provide either the --password or --is_superuser flag when using the updateuser command.',
14
+ );
15
+ process.exit(1);
16
+ } else {
17
+ updateSuperuser({ id, password, is_superuser });
18
+ }
19
+ }
20
+ };
21
+
22
+ module.exports = { runCLICommands };
@@ -2,7 +2,7 @@ const dotenv = require('dotenv');
2
2
  const Joi = require('joi');
3
3
  const path = require('path');
4
4
 
5
- const { yargs, usage, options } = require('../cli');
5
+ const { yargs } = require('../cli');
6
6
 
7
7
  const { argv } = yargs;
8
8
 
@@ -20,6 +20,7 @@ const envVarsSchema = Joi.object()
20
20
  VERBOSE: Joi.string().valid('console', null).default(null),
21
21
 
22
22
  CORS_ORIGIN_WHITELIST: Joi.string().default('*'),
23
+ AUTH: Joi.boolean().default(false),
23
24
 
24
25
  RATE_LIMIT_ENABLED: Joi.boolean().default(false),
25
26
  RATE_LIMIT_WINDOW_MS: Joi.number().positive().default(1000),
@@ -27,7 +28,14 @@ const envVarsSchema = Joi.object()
27
28
 
28
29
  EXTENSIONS: Joi.string().default(null),
29
30
 
30
- START_WITH_STUDIO: Joi.boolean().default(false)
31
+ START_WITH_STUDIO: Joi.boolean().default(false),
32
+
33
+ INITIAL_USER_USERNAME: Joi.string(),
34
+ INITIAL_USER_PASSWORD: Joi.string(),
35
+
36
+ TOKEN_SECRET: Joi.string().default(null),
37
+ ACCESS_TOKEN_EXPIRATION_TIME: Joi.string().default('5H'),
38
+ REFRESH_TOKEN_EXPIRATION_TIME: Joi.string().default('3D'),
31
39
  })
32
40
  .unknown();
33
41
 
@@ -51,10 +59,34 @@ if (argv.cors) {
51
59
  env.CORS_ORIGIN_WHITELIST = argv.cors;
52
60
  }
53
61
 
62
+ if (argv.auth) {
63
+ env.AUTH = argv.auth;
64
+ }
65
+
54
66
  if (argv['rate-limit-enabled']) {
55
67
  env.RATE_LIMIT_ENABLED = argv['rate-limit-enabled'];
56
68
  }
57
69
 
70
+ if (argv.tokensecret) {
71
+ env.TOKEN_SECRET = argv.tokensecret;
72
+ }
73
+
74
+ if (argv.accesstokenexpirationtime) {
75
+ env.ACCESS_TOKEN_EXPIRATION_TIME = argv.accesstokenexpirationtime;
76
+ }
77
+
78
+ if (argv.refreshtokenexpirationtime) {
79
+ env.REFRESH_TOKEN_EXPIRATION_TIME = argv.refreshtokenexpirationtime;
80
+ }
81
+
82
+ if (argv.initialuserusername) {
83
+ env.INITIAL_USER_USERNAME = argv.initialuserusername;
84
+ }
85
+
86
+ if (argv.initialuserpassword) {
87
+ env.INITIAL_USER_PASSWORD = argv.initialuserpassword;
88
+ }
89
+
58
90
  const { value: envVars, error } = envVarsSchema
59
91
  .prefs({ errors: { label: 'key' } })
60
92
  .validate(env);
@@ -80,6 +112,19 @@ module.exports = {
80
112
  origin: argv.cors?.split(',') ||
81
113
  envVars.CORS_ORIGIN_WHITELIST?.split(',') || ['*'],
82
114
  },
115
+
116
+ auth: argv.auth || envVars.AUTH,
117
+ tokenSecret: argv.tokensecret || envVars.TOKEN_SECRET,
118
+ accessTokenExpirationTime:
119
+ argv.accesstokenexpirationtime || envVars.ACCESS_TOKEN_EXPIRATION_TIME,
120
+ refreshTokenExpirationTime:
121
+ argv.refreshtokenexpirationtime || envVars.REFRESH_TOKEN_EXPIRATION_TIME,
122
+
123
+ initialUserUsername:
124
+ argv.initialuserusername || envVars.INITIAL_USER_USERNAME,
125
+ initialUserPassword:
126
+ argv.initialuserpassword || envVars.INITIAL_USER_PASSWORD,
127
+
83
128
  rateLimit: {
84
129
  enabled: argv['rate-limit-enabled'] || envVars.RATE_LIMIT_ENABLED,
85
130
  windowMs: envVars.RATE_LIMIT_WINDOW,
@@ -90,5 +135,5 @@ module.exports = {
90
135
  path: argv.extensions || envVars.EXTENSIONS,
91
136
  },
92
137
 
93
- startWithStudio: argv.studio || envVars.START_WITH_STUDIO
138
+ startWithStudio: argv.studio || envVars.START_WITH_STUDIO,
94
139
  };
@@ -0,0 +1,26 @@
1
+ module.exports = {
2
+ authEndpoints: ['_users', '_roles', '_roles_permissions', '_users_roles'],
3
+ baseTableUrl: '/api/tables',
4
+ universalAccessEndpoints: ['/api/auth/change-password'],
5
+
6
+ DEFAULT_PAGE_LIMIT: 10,
7
+ DEFAULT_PAGE_INDEX: 0,
8
+ PASSWORD: {
9
+ TOO_WEAK: 'Too weak',
10
+ WEAK: 'Weak',
11
+ },
12
+
13
+ httpVerbs: {
14
+ POST: 'POST',
15
+ GET: 'GET',
16
+ PUT: 'PUT',
17
+ DELETE: 'DELETE',
18
+ },
19
+
20
+ httpMethodDefinitions: {
21
+ POST: 'CREATE',
22
+ GET: 'READ',
23
+ PUT: 'UPDATE',
24
+ DELETE: 'DELETE',
25
+ },
26
+ };
@@ -0,0 +1,5 @@
1
+ module.exports = {
2
+ SALT_ROUNDS: 10,
3
+ ACCESS_TOKEN_SUBJECT: 'accessToken',
4
+ REFRESH_TOKEN_SUBJECT: 'refreshToken',
5
+ };
@@ -0,0 +1,13 @@
1
+ const dbConstants = require('./tables');
2
+ const apiConstants = require('./api');
3
+ const constantRoles = require('./roles');
4
+ const responseMessages = require('./messages');
5
+ const authConstants = require('./auth');
6
+
7
+ module.exports = {
8
+ dbConstants,
9
+ apiConstants,
10
+ constantRoles,
11
+ responseMessages,
12
+ authConstants,
13
+ };
@@ -0,0 +1,41 @@
1
+ module.exports = {
2
+ successMessage: {
3
+ SUCCESS: 'Success',
4
+ ROW_INSERTED: 'Row Inserted',
5
+ PASSWORD_UPDATE_SUCCESS: 'Password updated successfully',
6
+ USER_UPDATE_SUCCESS: 'User updated successfully',
7
+ INITIAL_USER_CREATED_SUCCESS: 'Initial user created successfully',
8
+ },
9
+
10
+ errorMessage: {
11
+ USERNAME_TAKEN_ERROR: 'This username is taken',
12
+ WEAK_PASSWORD_ERROR: 'This password is weak, please use another password',
13
+ DEFAULT_ROLE_NOT_CREATED_ERROR:
14
+ 'Please restart soul so a default role can be created',
15
+ INVALID_USERNAME_PASSWORD_ERROR: 'Invalid username or password',
16
+ INVALID_REFRESH_TOKEN_ERROR: 'Invalid refresh token',
17
+ INVALID_ACCESS_TOKEN_ERROR: 'Invalid access token',
18
+ USER_NOT_FOUND_ERROR: 'User not found',
19
+ INVALID_CURRENT_PASSWORD_ERROR: 'Invalid current password',
20
+ NOT_AUTHORIZED_ERROR: 'Not authorized',
21
+ PERMISSION_NOT_DEFINED_ERROR: 'Permission not defined for this role',
22
+ ROLE_NOT_FOUND_ERROR: 'Role not found for this user',
23
+ AUTH_SET_TO_FALSE_ERROR:
24
+ 'You can not access this endpoint while AUTH is set to false',
25
+ RESERVED_TABLE_NAME_ERROR:
26
+ 'The table name is reserved. Please choose a different name for the table.',
27
+ SERVER_ERROR: 'Server error',
28
+
29
+ INITIAL_USER_USERNAME_NOT_PASSED_ERROR:
30
+ 'Error: You should pass the initial users username either from the CLI with the --iuu or from the environment variable using the INITIAL_USER_USERNAME flag',
31
+ INITIAL_USER_PASSWORD_NOT_PASSED_ERROR:
32
+ 'Error: You should pass the initial users password either from the CLI with the --iup or from the environment variable using the INITIAL_USER_PASSWORD flag',
33
+
34
+ USERNAME_REQUIRED_ERROR: 'username is required',
35
+ PASSWORD_REQUIRED_ERROR: 'password is required',
36
+ },
37
+
38
+ infoMessage: {
39
+ INITIAL_USER_ALREADY_CREATED: 'Initial user is already created',
40
+ },
41
+ };
@@ -0,0 +1,3 @@
1
+ module.exports = {
2
+ DEFAULT_ROLE: 'default',
3
+ };
@@ -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
+ };