soul-cli 0.7.1 → 0.7.3

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.
@@ -0,0 +1,128 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our
6
+ community a harassment-free experience for everyone, regardless of age, body
7
+ size, visible or invisible disability, ethnicity, sex characteristics, gender
8
+ identity and expression, level of experience, education, socio-economic status,
9
+ nationality, personal appearance, race, religion, or sexual identity
10
+ and orientation.
11
+
12
+ We pledge to act and interact in ways that contribute to an open, welcoming,
13
+ diverse, inclusive, and healthy community.
14
+
15
+ ## Our Standards
16
+
17
+ Examples of behavior that contributes to a positive environment for our
18
+ community include:
19
+
20
+ * Demonstrating empathy and kindness toward other people
21
+ * Being respectful of differing opinions, viewpoints, and experiences
22
+ * Giving and gracefully accepting constructive feedback
23
+ * Accepting responsibility and apologizing to those affected by our mistakes,
24
+ and learning from the experience
25
+ * Focusing on what is best not just for us as individuals, but for the
26
+ overall community
27
+
28
+ Examples of unacceptable behavior include:
29
+
30
+ * The use of sexualized language or imagery, and sexual attention or
31
+ advances of any kind
32
+ * Trolling, insulting or derogatory comments, and personal or political attacks
33
+ * Public or private harassment
34
+ * Publishing others' private information, such as a physical or email
35
+ address, without their explicit permission
36
+ * Other conduct which could reasonably be considered inappropriate in a
37
+ professional setting
38
+
39
+ ## Enforcement Responsibilities
40
+
41
+ Community leaders are responsible for clarifying and enforcing our standards of
42
+ acceptable behavior and will take appropriate and fair corrective action in
43
+ response to any behavior that they deem inappropriate, threatening, offensive,
44
+ or harmful.
45
+
46
+ Community leaders have the right and responsibility to remove, edit, or reject
47
+ comments, commits, code, wiki edits, issues, and other contributions that are
48
+ not aligned to this Code of Conduct, and will communicate reasons for moderation
49
+ decisions when appropriate.
50
+
51
+ ## Scope
52
+
53
+ This Code of Conduct applies within all community spaces, and also applies when
54
+ an individual is officially representing the community in public spaces.
55
+ Examples of representing our community include using an official e-mail address,
56
+ posting via an official social media account, or acting as an appointed
57
+ representative at an online or offline event.
58
+
59
+ ## Enforcement
60
+
61
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
62
+ reported to the community leaders responsible for enforcement at
63
+ thevahidal@gmail.com.
64
+ All complaints will be reviewed and investigated promptly and fairly.
65
+
66
+ All community leaders are obligated to respect the privacy and security of the
67
+ reporter of any incident.
68
+
69
+ ## Enforcement Guidelines
70
+
71
+ Community leaders will follow these Community Impact Guidelines in determining
72
+ the consequences for any action they deem in violation of this Code of Conduct:
73
+
74
+ ### 1. Correction
75
+
76
+ **Community Impact**: Use of inappropriate language or other behavior deemed
77
+ unprofessional or unwelcome in the community.
78
+
79
+ **Consequence**: A private, written warning from community leaders, providing
80
+ clarity around the nature of the violation and an explanation of why the
81
+ behavior was inappropriate. A public apology may be requested.
82
+
83
+ ### 2. Warning
84
+
85
+ **Community Impact**: A violation through a single incident or series
86
+ of actions.
87
+
88
+ **Consequence**: A warning with consequences for continued behavior. No
89
+ interaction with the people involved, including unsolicited interaction with
90
+ those enforcing the Code of Conduct, for a specified period of time. This
91
+ includes avoiding interactions in community spaces as well as external channels
92
+ like social media. Violating these terms may lead to a temporary or
93
+ permanent ban.
94
+
95
+ ### 3. Temporary Ban
96
+
97
+ **Community Impact**: A serious violation of community standards, including
98
+ sustained inappropriate behavior.
99
+
100
+ **Consequence**: A temporary ban from any sort of interaction or public
101
+ communication with the community for a specified period of time. No public or
102
+ private interaction with the people involved, including unsolicited interaction
103
+ with those enforcing the Code of Conduct, is allowed during this period.
104
+ Violating these terms may lead to a permanent ban.
105
+
106
+ ### 4. Permanent Ban
107
+
108
+ **Community Impact**: Demonstrating a pattern of violation of community
109
+ standards, including sustained inappropriate behavior, harassment of an
110
+ individual, or aggression toward or disparagement of classes of individuals.
111
+
112
+ **Consequence**: A permanent ban from any sort of public interaction within
113
+ the community.
114
+
115
+ ## Attribution
116
+
117
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118
+ version 2.0, available at
119
+ https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
120
+
121
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct
122
+ enforcement ladder](https://github.com/mozilla/diversity).
123
+
124
+ [homepage]: https://www.contributor-covenant.org
125
+
126
+ For answers to common questions about this code of conduct, see the FAQ at
127
+ https://www.contributor-covenant.org/faq. Translations are available at
128
+ https://www.contributor-covenant.org/translations.
package/CONTRIBUTING.md CHANGED
@@ -15,78 +15,3 @@ Please note we have a code of conduct, please follow it in all your interactions
15
15
  Pull Request would represent. The versioning scheme we use is [SemVer](http://semver.org/).
16
16
  4. You may merge the Pull Request in once you have the sign-off of two other developers, or if you
17
17
  do not have permission to do that, you may request the second reviewer to merge it for you.
18
-
19
- ## Code of Conduct
20
-
21
- ### Our Pledge
22
-
23
- In the interest of fostering an open and welcoming environment, we as
24
- contributors and maintainers pledge to making participation in our project and
25
- our community a harassment-free experience for everyone, regardless of age, body
26
- size, disability, ethnicity, gender identity and expression, level of experience,
27
- nationality, personal appearance, race, religion, or sexual identity and
28
- orientation.
29
-
30
- ### Our Standards
31
-
32
- Examples of behavior that contributes to creating a positive environment
33
- include:
34
-
35
- * Using welcoming and inclusive language
36
- * Being respectful of differing viewpoints and experiences
37
- * Gracefully accepting constructive criticism
38
- * Focusing on what is best for the community
39
- * Showing empathy towards other community members
40
-
41
- Examples of unacceptable behavior by participants include:
42
-
43
- * The use of sexualized language or imagery and unwelcome sexual attention or
44
- advances
45
- * Trolling, insulting/derogatory comments, and personal or political attacks
46
- * Public or private harassment
47
- * Publishing others' private information, such as a physical or electronic
48
- address, without explicit permission
49
- * Other conduct which could reasonably be considered inappropriate in a
50
- professional setting
51
-
52
- ### Our Responsibilities
53
-
54
- Project maintainers are responsible for clarifying the standards of acceptable
55
- behavior and are expected to take appropriate and fair corrective action in
56
- response to any instances of unacceptable behavior.
57
-
58
- Project maintainers have the right and responsibility to remove, edit, or
59
- reject comments, commits, code, wiki edits, issues, and other contributions
60
- that are not aligned to this Code of Conduct, or to ban temporarily or
61
- permanently any contributor for other behaviors that they deem inappropriate,
62
- threatening, offensive, or harmful.
63
-
64
- ### Scope
65
-
66
- This Code of Conduct applies both within project spaces and in public spaces
67
- when an individual is representing the project or its community. Examples of
68
- representing a project or community include using an official project e-mail
69
- address, posting via an official social media account, or acting as an appointed
70
- representative at an online or offline event. Representation of a project may be
71
- further defined and clarified by project maintainers.
72
-
73
- ### Enforcement
74
-
75
- Instances of abusive, harassing, or otherwise unacceptable behavior may be
76
- reported by contacting the project team at [INSERT EMAIL ADDRESS]. All
77
- complaints will be reviewed and investigated and will result in a response that
78
- is deemed necessary and appropriate to the circumstances. The project team is
79
- obligated to maintain confidentiality with regard to the reporter of an incident.
80
- Further details of specific enforcement policies may be posted separately.
81
-
82
- Project maintainers who do not follow or enforce the Code of Conduct in good
83
- faith may face temporary or permanent repercussions as determined by other
84
- members of the project's leadership.
85
-
86
- ### Attribution
87
-
88
- This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
89
- available at [http://contributor-covenant.org/version/1/4][version]
90
-
91
- [homepage]: http://contributor-covenant.org
92
- [version]: http://contributor-covenant.org/version/1/4/
@@ -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
  ```
@@ -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.1",
3
+ "version": "0.7.3",
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
  );
@@ -2,4 +2,5 @@ module.exports = {
2
2
  SALT_ROUNDS: 10,
3
3
  ACCESS_TOKEN_SUBJECT: 'accessToken',
4
4
  REFRESH_TOKEN_SUBJECT: 'refreshToken',
5
+ REVOKED_REFRESH_TOKENS_REMOVAL_TIME_RANGE: 3 * 24 * 60 * 60 * 1000, // 3 days * 24 hours * 60 minutes * 60 seconds * 1000 milliseconds =
5
6
  };
@@ -5,6 +5,7 @@ module.exports = {
5
5
  PASSWORD_UPDATE_SUCCESS: 'Password updated successfully',
6
6
  USER_UPDATE_SUCCESS: 'User updated successfully',
7
7
  INITIAL_USER_CREATED_SUCCESS: 'Initial user created successfully',
8
+ LOGOUT_MESSAGE: 'Logout successful',
8
9
  },
9
10
 
10
11
  errorMessage: {
@@ -2,12 +2,15 @@ const USERS_TABLE = '_users';
2
2
  const ROLES_TABLE = '_roles';
3
3
  const USERS_ROLES_TABLE = '_users_roles';
4
4
  const ROLES_PERMISSIONS_TABLE = '_roles_permissions';
5
+ const REVOKED_REFRESH_TOKENS_TABLE = '_revoked_refresh_tokens';
5
6
 
6
7
  module.exports = {
8
+ // db table names
7
9
  USERS_TABLE,
8
10
  ROLES_TABLE,
9
11
  USERS_ROLES_TABLE,
10
12
  ROLES_PERMISSIONS_TABLE,
13
+ REVOKED_REFRESH_TOKENS_TABLE,
11
14
 
12
15
  reservedTableNames: [
13
16
  USERS_TABLE,
@@ -43,5 +46,9 @@ module.exports = {
43
46
 
44
47
  // _users_roles fields
45
48
  USER_ID: 'user_id',
49
+
50
+ //_revoked_refresh_tokens
51
+ REFRESH_TOKEN: 'refresh_token',
52
+ EXPIRES_AT: 'expires_at',
46
53
  },
47
54
  };
@@ -7,6 +7,7 @@ const {
7
7
  ROLES_TABLE,
8
8
  USERS_ROLES_TABLE,
9
9
  ROLES_PERMISSIONS_TABLE,
10
+ REVOKED_REFRESH_TOKENS_TABLE,
10
11
  constraints,
11
12
  tableFields,
12
13
  } = dbConstants;
@@ -21,6 +22,9 @@ const createDefaultTables = async () => {
21
22
  ROLES_PERMISSIONS_TABLE,
22
23
  );
23
24
  const usersRolesTable = tableService.checkTableExists(USERS_ROLES_TABLE);
25
+ const revokedRefreshTokensTable = tableService.checkTableExists(
26
+ REVOKED_REFRESH_TOKENS_TABLE,
27
+ );
24
28
 
25
29
  // create _users table
26
30
  if (!usersTable) {
@@ -76,10 +80,10 @@ const createDefaultTables = async () => {
76
80
  permissions.push({
77
81
  role_id: roleId,
78
82
  table_name: table.name,
79
- create: 'false',
80
- read: 'true',
81
- update: 'false',
82
- delete: 'false',
83
+ create: 0,
84
+ read: 1,
85
+ update: 0,
86
+ delete: 0,
83
87
  });
84
88
  }
85
89
 
@@ -89,6 +93,14 @@ const createDefaultTables = async () => {
89
93
  fields: permissions,
90
94
  });
91
95
  }
96
+
97
+ // create _revoked_refresh_tokens table
98
+ if (!revokedRefreshTokensTable) {
99
+ tableService.createTable(
100
+ REVOKED_REFRESH_TOKENS_TABLE,
101
+ schema.revokedRefreshTokensSchema,
102
+ );
103
+ }
92
104
  };
93
105
 
94
106
  module.exports = {
@@ -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
@@ -125,11 +123,19 @@ const refreshAccessToken = async (req, res) => {
125
123
  #swagger.summary = 'Refresh Access Token'
126
124
  #swagger.description = 'Endpoint to refresh access and refresh tokens'
127
125
  */
126
+ const refreshTokenFromCookies = req.cookies.refreshToken;
128
127
 
129
128
  try {
129
+ // check if the refresh token is revoked
130
+ if (isRefreshTokenRevoked({ refreshToken: refreshTokenFromCookies })) {
131
+ return res
132
+ .status(403)
133
+ .send({ message: errorMessage.INVALID_REFRESH_TOKEN_ERROR });
134
+ }
135
+
130
136
  // extract the payload from the token and verify it
131
137
  const payload = await decodeToken(
132
- req.cookies.refreshToken,
138
+ refreshTokenFromCookies,
133
139
  config.tokenSecret,
134
140
  );
135
141
 
@@ -151,7 +157,7 @@ const refreshAccessToken = async (req, res) => {
151
157
  */
152
158
  }
153
159
 
154
- let permissions, roleIds;
160
+ let roleIds;
155
161
  const user = users[0];
156
162
 
157
163
  // if the user is not a superuser get the role and its permission from the DB
@@ -161,7 +167,6 @@ const refreshAccessToken = async (req, res) => {
161
167
  res,
162
168
  });
163
169
 
164
- permissions = roleData.permissions;
165
170
  roleIds = roleData.roleIds;
166
171
  }
167
172
 
@@ -170,7 +175,6 @@ const refreshAccessToken = async (req, res) => {
170
175
  userId: user.id,
171
176
  isSuperuser: user.is_superuser,
172
177
  roleIds,
173
- permissions,
174
178
  };
175
179
 
176
180
  // generate an access token
@@ -221,6 +225,52 @@ const refreshAccessToken = async (req, res) => {
221
225
  }
222
226
  };
223
227
 
228
+ const removeTokens = async (req, res) => {
229
+ /*
230
+ #swagger.tags = ['Auth']
231
+ #swagger.summary = 'Remove Tokens'
232
+ #swagger.description = 'Endpoint to remove access and refresh tokens'
233
+ */
234
+
235
+ const refreshToken = req.cookies.refreshToken;
236
+
237
+ try {
238
+ // decode the token
239
+ const payload = await decodeToken(refreshToken, config.tokenSecret);
240
+
241
+ // store the refresh token in the _revoked_refresh_tokens table
242
+ authService.saveRevokedRefreshToken({
243
+ refreshToken,
244
+ expiresAt: payload.exp,
245
+ });
246
+
247
+ // remove the token from the cookie
248
+ res.clearCookie(authConstants.ACCESS_TOKEN_SUBJECT);
249
+ res.clearCookie(authConstants.REFRESH_TOKEN_SUBJECT);
250
+
251
+ res
252
+ .status(200)
253
+ .send({ message: responseMessages.successMessage.LOGOUT_MESSAGE });
254
+
255
+ /*
256
+ #swagger.responses[200] = {
257
+ description: 'Tokens Removed',
258
+ schema: {
259
+ $ref: '#/definitions/RemoveTokensResponse'
260
+ }
261
+ }
262
+ */
263
+ } catch (error) {
264
+ res.status(500).send({ message: errorMessage.SERVER_ERROR });
265
+ }
266
+ };
267
+
268
+ const removeRevokedRefreshTokens = () => {
269
+ authService.deleteRevokedRefreshTokens({
270
+ lookupField: `WHERE expires_at < CURRENT_TIMESTAMP`,
271
+ });
272
+ };
273
+
224
274
  const getUsersRoleAndPermission = ({ userId, res }) => {
225
275
  const userRoles = authService.getUserRoleByUserId({ userId });
226
276
 
@@ -237,7 +287,14 @@ const getUsersRoleAndPermission = ({ userId, res }) => {
237
287
  return { userRoles, roleIds, permissions };
238
288
  };
239
289
 
290
+ const isRefreshTokenRevoked = ({ refreshToken }) => {
291
+ const tokens = authService.getRevokedRefreshToken({ refreshToken });
292
+ return tokens.length > 0;
293
+ };
294
+
240
295
  module.exports = {
241
296
  obtainAccessToken,
242
297
  refreshAccessToken,
298
+ removeTokens,
299
+ removeRevokedRefreshTokens,
243
300
  };
@@ -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/db/schema.js CHANGED
@@ -115,4 +115,22 @@ module.exports = {
115
115
  foreignKey: { table: ROLES_TABLE, column: tableFields.ID },
116
116
  },
117
117
  ],
118
+
119
+ revokedRefreshTokensSchema: [
120
+ {
121
+ name: tableFields.REFRESH_TOKEN,
122
+ type: 'TEXT',
123
+ primaryKey: false,
124
+ notNull: true,
125
+ unique: false,
126
+ },
127
+
128
+ {
129
+ name: tableFields.EXPIRES_AT,
130
+ type: 'NUMERIC',
131
+ primaryKey: false,
132
+ notNull: true,
133
+ unique: false,
134
+ },
135
+ ],
118
136
  };
package/src/index.js CHANGED
@@ -22,9 +22,11 @@ const { setupExtensions } = require('./extensions');
22
22
  const {
23
23
  createDefaultTables,
24
24
  createInitialUser,
25
+ removeRevokedRefreshTokens,
25
26
  } = require('./controllers/auth');
26
27
 
27
28
  const { runCLICommands } = require('./commands');
29
+ const { authConstants } = require('./constants');
28
30
 
29
31
  const app = express();
30
32
  app.get('/health', (req, res) => {
@@ -93,6 +95,12 @@ if (config.auth) {
93
95
  );
94
96
  }
95
97
 
98
+ // remove revoked refresh tokens every X days
99
+ setInterval(
100
+ removeRevokedRefreshTokens,
101
+ authConstants.REVOKED_REFRESH_TOKENS_REMOVAL_TIME_RANGE,
102
+ );
103
+
96
104
  // If the user has passed custom CLI commands run the command and exit to avoid running the server
97
105
  runCLICommands();
98
106
 
@@ -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
  };
@@ -26,4 +26,10 @@ router.put(
26
26
  controllers.changePassword,
27
27
  );
28
28
 
29
+ router.get(
30
+ '/logout',
31
+ validator(schema.removeAccessTokens),
32
+ controllers.removeTokens,
33
+ );
34
+
29
35
  module.exports = router;
@@ -59,9 +59,41 @@ 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
+
82
+ const removeAccessTokens = Joi.object({
83
+ query: Joi.object().required(),
84
+ params: Joi.object({}).required(),
85
+ body: Joi.object({}).required(),
86
+ cookies: Joi.object({
87
+ refreshToken: Joi.string().required(),
88
+ accessToken: Joi.string().required(),
89
+ }).required(),
90
+ });
91
+
62
92
  module.exports = {
63
93
  obtainAccessToken,
64
94
  refreshAccessToken,
65
95
  changePassword,
66
96
  registerUser,
97
+ updateRolePermissions,
98
+ removeAccessTokens,
67
99
  };
@@ -8,10 +8,11 @@ const {
8
8
  ROLES_TABLE,
9
9
  USERS_ROLES_TABLE,
10
10
  ROLES_PERMISSIONS_TABLE,
11
+ REVOKED_REFRESH_TOKENS_TABLE,
11
12
  tableFields,
12
13
  } = dbConstants;
13
14
 
14
- module.exports = () => {
15
+ module.exports = (db) => {
15
16
  return {
16
17
  getUsersByUsername({ username }) {
17
18
  const users = rowService.get({
@@ -43,6 +44,7 @@ module.exports = () => {
43
44
  return users;
44
45
  },
45
46
 
47
+ // TODO: bypass pagination by providing query param for number of rows
46
48
  getPermissionByRoleIds({ roleIds }) {
47
49
  const permissions = rowService.get({
48
50
  tableName: ROLES_PERMISSIONS_TABLE,
@@ -50,6 +52,7 @@ module.exports = () => {
50
52
  () => '?',
51
53
  )})`,
52
54
  whereStringValues: [...roleIds],
55
+ limit: 10000,
53
56
  });
54
57
 
55
58
  return permissions;
@@ -74,5 +77,34 @@ module.exports = () => {
74
77
 
75
78
  return defaultRole;
76
79
  },
80
+
81
+ saveRevokedRefreshToken({ refreshToken, expiresAt }) {
82
+ const { lastInsertRowid } = rowService.save({
83
+ tableName: REVOKED_REFRESH_TOKENS_TABLE,
84
+ fields: {
85
+ refresh_token: refreshToken,
86
+ expires_at: expiresAt,
87
+ },
88
+ });
89
+
90
+ return { id: lastInsertRowid };
91
+ },
92
+
93
+ getRevokedRefreshToken({ refreshToken }) {
94
+ const token = rowService.get({
95
+ tableName: REVOKED_REFRESH_TOKENS_TABLE,
96
+ whereString: `WHERE ${tableFields.REFRESH_TOKEN}=?`,
97
+ whereStringValues: [refreshToken],
98
+ });
99
+
100
+ return token;
101
+ },
102
+
103
+ deleteRevokedRefreshTokens({ lookupField }) {
104
+ const query = `DELETE FROM ${REVOKED_REFRESH_TOKENS_TABLE} ${lookupField}`;
105
+ const statement = db.prepare(query);
106
+ const result = statement.run();
107
+ return result;
108
+ },
77
109
  };
78
110
  };
@@ -189,6 +189,10 @@ const doc = {
189
189
  },
190
190
 
191
191
  InvalidPasswordErrorResponse: { message: 'Invalid password' },
192
+
193
+ RemoveTokensResponse: {
194
+ message: 'Logout successful',
195
+ },
192
196
  },
193
197
  };
194
198
 
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "swagger": "2.0",
3
3
  "info": {
4
- "version": "0.7.0",
4
+ "version": "0.7.2",
5
5
  "title": "Soul API",
6
6
  "description": "API Documentation for <b>Soul</b>, a SQLite REST and realtime server. "
7
7
  },
@@ -535,6 +535,17 @@
535
535
  }
536
536
  }
537
537
  }
538
+ },
539
+ "/api/auth/logout": {
540
+ "get": {
541
+ "description": "",
542
+ "parameters": [],
543
+ "responses": {
544
+ "400": {
545
+ "description": "Bad Request"
546
+ }
547
+ }
548
+ }
538
549
  }
539
550
  },
540
551
  "definitions": {
@@ -985,6 +996,15 @@
985
996
  "example": "Invalid password"
986
997
  }
987
998
  }
999
+ },
1000
+ "RemoveTokensResponse": {
1001
+ "type": "object",
1002
+ "properties": {
1003
+ "message": {
1004
+ "type": "string",
1005
+ "example": "Logout successful"
1006
+ }
1007
+ }
988
1008
  }
989
1009
  }
990
1010
  }