Merge base branch + Fix merge conflict + Fix typo + Modify createInitialUser controller function

This commit is contained in:
AbegaM
2024-03-08 18:38:08 +03:00
16 changed files with 106 additions and 107 deletions

View File

@@ -18,3 +18,7 @@ INITIAL_USER_PASSWORD=<your_password>
DB=foobar.db
START_WITH_STUDIO=false
TOKEN_SECRET=ABCD23DCAA
ACCESS_TOKEN_EXPIRATION_TIME=10H
REFRESH_TOKEN_EXPIRATION_TIME=2D

View File

@@ -63,7 +63,11 @@ To run Soul in auth mode, allowing login and signup features with authorization
Run the Soul command with the necessary parameters:
```
<<<<<<< HEAD
soul --d foobar.db -a -ats <your_jwt_access_token_secret_value> -atet=4H -rts <your_jwt_refresh_token_secret_value> -rtet=3D -iuu=john -iup=<your_password>
=======
soul --d foobar.db -a -ts <your_jwt_secret_value> -atet=4H -rtet=3D
>>>>>>> authorization_feature
```
Note: When configuring your JWT Secret, it is recommended to use a long string value for enhanced security. It is advisable to use a secret that is at least 10 characters in length.
@@ -71,12 +75,17 @@ Note: When configuring your JWT Secret, it is recommended to use a long string v
In this example:
The `-a` flag instructs Soul to run in auth mode.
The `-ats` flag allows you to pass a JWT secret value for the `access token` generation and verification. Replace <your_jwt_access_token_secret_value> with your desired secret value.
The `-ts` flag allows you to pass a JWT secret value for the `access and refresh tokens` generation and verification. Replace <your_jwt\_\_secret_value> with your desired secret value.
The `-atet` flag sets the JWT expiration time for the access token. In this case, it is set to four hours (4H), meaning the token will expire after 4 hours.
<<<<<<< HEAD
The `-rts` flag allows you to pass a JWT secret value for the `refresh token` generation and verification. Replace <your_jwt_refresh_token_secret_value> with your desired secret value.
The `-rtet` flag sets the JWT expiration time for the refresh token. In this case, it is set to three days (3D), meaning the token will expire after 3 days.
The `-iuu` flag is used to pass a username for the initial user
The `-iup` flag is used to pass a password for the initial user
=======
Teh `-rtet` flag sets the JWT expiration time for the refresh token. In this case, it is set to three days (3D), meaning the token will expire after 3 days.
> > > > > > > authorization_feature
Here are some example values for the `-atet` and `rtet` flags
@@ -84,7 +93,7 @@ Here are some example values for the `-atet` and `rtet` flags
- 5H: Represents a duration of 5 hours.
- 1D: Represents a duration of 1 day.
NOTE: It is crucial to securely store a copy of the `Access token secret` and `Refresh token secret` values used in Soul. Once you pass this values, make sure to keep a backup because you will need it every time you restart Soul. Losing this secret values can result in a situation where all of your users are blocked from accessing Soul.
NOTE: It is crucial to securely store a copy of the `-ts`(`Token Secret`) value used in Soul. Once you pass this values, make sure to keep a backup because you will need it every time you restart Soul. Losing this secret values can result in a situation where all of your users are blocked from accessing Soul.
### 3. Updating Super Users

View File

@@ -53,9 +53,9 @@ if (process.env.NO_CLI !== 'true') {
default: false,
demandOption: false,
})
.options('ats', {
alias: 'accesstokensecret',
describe: 'JWT secret for access token',
.options('ts', {
alias: 'tokensecret',
describe: 'JWT secret for the access and refresh tokens',
type: 'string',
default: null,
demandOption: false,
@@ -67,13 +67,6 @@ if (process.env.NO_CLI !== 'true') {
default: '5H',
demandOption: false,
})
.options('rts', {
alias: 'refreshtokensecret',
describe: 'JWT secret for refresh token',
type: 'string',
default: null,
demandOption: false,
})
.options('rtet', {
alias: 'refreshtokenexpirationtime',
describe: 'JWT expiration time for refresh token',

View File

@@ -33,9 +33,8 @@ const envVarsSchema = Joi.object()
INITIAL_USER_USERNAME: Joi.string(),
INITIAL_USER_PASSWORD: Joi.string(),
ACCESS_TOKEN_SECRET: Joi.string().default(null),
TOKEN_SECRET: Joi.string().default(null),
ACCESS_TOKEN_EXPIRATION_TIME: Joi.string().default('5H'),
REFRESH_TOKEN_SECRET: Joi.string().default(null),
REFRESH_TOKEN_EXPIRATION_TIME: Joi.string().default('3D'),
})
.unknown();
@@ -68,18 +67,14 @@ if (argv['rate-limit-enabled']) {
env.RATE_LIMIT_ENABLED = argv['rate-limit-enabled'];
}
if (argv.accesstokensecret) {
env.ACCESS_TOKEN_SECRET = argv.accesstokensecret;
if (argv.tokensecret) {
env.TOKEN_SECRET = argv.tokensecret;
}
if (argv.accesstokenexpirationtime) {
env.ACCESS_TOKEN_EXPIRATION_TIME = argv.accesstokenexpirationtime;
}
if (argv.refreshtokensecret) {
env.REFRESH_TOKEN_SECRET = argv.refreshtokensecret;
}
if (argv.refreshtokenexpirationtime) {
env.REFRESH_TOKEN_EXPIRATION_TIME = argv.refreshtokenexpirationtime;
}
@@ -119,10 +114,9 @@ module.exports = {
},
auth: argv.auth || envVars.AUTH,
accessTokenSecret: argv.accesstokensecret || envVars.ACCESS_TOKEN_SECRET,
tokenSecret: argv.tokensecret || envVars.TOKEN_SECRET,
accessTokenExpirationTime:
argv.accesstokenexpirationtime || envVars.ACCESS_TOKEN_EXPIRATION_TIME,
refreshTokenSecret: argv.refreshtokensecret || envVars.REFRESH_TOKEN_SECRET,
refreshTokenExpirationTime:
argv.refreshtokenexpirationtime || envVars.REFRESH_TOKEN_EXPIRATION_TIME,

View File

@@ -1,3 +1,9 @@
module.exports = {
defaultRoutes: ['_users', '_roles', '_roles_permissions', '_users_roles'],
DEFAULT_PAGE_LIMIT: 10,
DEFAULT_PAGE_INDEX: 0,
PASSWORD: {
TOO_WEAK: 'Too weak',
WEAK: 'Weak',
},
};

View File

@@ -1,6 +1,4 @@
const { tableService } = require('../services');
const { rowService } = require('../services');
const { dbTables, constantRoles } = require('../constants');
const { tableService, rowService } = require('../services');
const config = require('../config');
const {
hashPassword,
@@ -11,6 +9,8 @@ const {
toBoolean,
} = require('../utils');
const { dbTables, constantRoles, apiConstants } = require('../constants');
const createDefaultTables = async () => {
let roleId;
@@ -101,28 +101,31 @@ const updateSuperuser = async (fields) => {
try {
// find the user by using the id field
let user = rowService.get({
const users = rowService.get({
tableName: '_users',
whereString: 'WHERE id=?',
whereStringValues: [id],
});
// abort if the id is invalid
if (user.length === 0) {
if (users.length === 0) {
console.log('The user id you passed does not exist in the database');
process.exit(1);
}
user = user[0];
// check if the is_superuser field is passed
if (is_superuser !== undefined) {
fieldsString = `is_superuser = '${is_superuser}', `;
fieldsString = `is_superuser = '${is_superuser}'`;
}
// if the password is sent from the CLI, update it
if (password) {
if (password.length < 8) {
// check if the password is weak
if (
[apiConstants.PASSWORD.TOO_WEAK, apiConstants.PASSWORD.WEAK].includes(
checkPasswordStrength(password),
)
) {
console.log('Your password should be at least 8 charachters long');
process.exit(1);
}
@@ -131,7 +134,10 @@ const updateSuperuser = async (fields) => {
const { hashedPassword, salt } = await hashPassword(password, 10);
newHashedPassword = hashedPassword;
newSalt = salt;
fieldsString += `hashed_password = '${newHashedPassword}', salt = '${newSalt}'`;
fieldsString = `${
fieldsString ? fieldsString + ', ' : ''
}hashed_password = '${newHashedPassword}', salt = '${newSalt}'`;
}
// update the user
@@ -175,7 +181,11 @@ const registerUser = async (req, res) => {
}
// check if the password is weak
if (['Too weak', 'Weak'].includes(checkPasswordStrength(password))) {
if (
[apiConstants.PASSWORD.TOO_WEAK, apiConstants.PASSWORD.WEAK].includes(
checkPasswordStrength(password),
)
) {
return res.status(400).send({
message: 'This password is weak, please use another password',
});
@@ -199,7 +209,7 @@ const registerUser = async (req, res) => {
let defaultRole = rowService.get({
tableName: '_roles',
whereString: 'WHERE name=?',
whereStringValues: ['default'],
whereStringValues: [constantRoles.DEFAULT_ROLE],
});
if (defaultRole.length <= 0) {
@@ -276,14 +286,14 @@ const obtainAccessToken = async (req, res) => {
// generate an access token
const accessToken = await generateToken(
{ subject: 'accessToken', ...payload },
config.accessTokenSecret,
config.tokenSecret,
config.accessTokenExpirationTime,
);
// generate a refresh token
const refreshToken = await generateToken(
{ subject: 'refreshToken', ...payload },
config.refreshTokenSecret,
config.tokenSecret,
config.refreshTokenExpirationTime,
);
@@ -307,7 +317,7 @@ const refreshAccessToken = async (req, res) => {
// extract the payload from the token and verify it
const payload = await decodeToken(
req.cookies.refreshToken,
config.refreshTokenSecret,
config.tokenSecret,
);
// find the user
@@ -355,14 +365,14 @@ const refreshAccessToken = async (req, res) => {
// generate an access token
const accessToken = await generateToken(
{ subject: 'accessToken', ...newPayload },
config.accessTokenSecret,
config.tokenSecret,
config.accessTokenExpirationTime,
);
// generate a refresh token
const refreshToken = await generateToken(
{ subject: 'refreshToken', ...newPayload },
config.refreshTokenSecret,
config.tokenSecret,
config.refreshTokenExpirationTime,
);
@@ -406,7 +416,11 @@ const changePassword = async (req, res) => {
}
// check if the new password is strong
if (['Too weak', 'Weak'].includes(checkPasswordStrength(newPassword))) {
if (
[apiConstants.PASSWORD.TOO_WEAK, apiConstants.PASSWORD.WEAK].includes(
checkPasswordStrength(newPassword),
)
) {
return res.status(400).send({
message: 'This password is weak, please use another password',
});
@@ -442,13 +456,13 @@ const createInitialUser = async () => {
try {
// check if there is a superuser in the DB
const superusers = rowService.get({
const users = rowService.get({
tableName: '_users',
whereString: 'WHERE is_superuser=?',
whereStringValues: ['true'],
whereString: '',
whereStringValues: [],
});
if (superusers.length <= 0) {
if (users.length <= 0) {
// check if initial superuser username is passed from the env or CLI
if (!username) {
console.error(
@@ -465,7 +479,7 @@ const createInitialUser = async () => {
process.exit(1);
}
// checkf if the usernmae is taken
// check if the usernmae is taken
const users = rowService.get({
tableName: '_users',
whereString: 'WHERE username=?',

View File

@@ -1,12 +1,6 @@
const db = require('../db/index');
const { rowService } = require('../services');
// const quotePrimaryKeys = (pks) => {
// const primaryKeys = pks.split(',');
// const quotedPks = primaryKeys.map((id) => `'${id}'`).join(',');
// return quotedPks;
// };
const operators = {
eq: '=',
lt: '<',
@@ -327,13 +321,6 @@ const listTableRows = async (req, res, next) => {
}`
: null;
// res.json({
// data,
// total,
// next: nextPage,
// previous
// });
req.response = {
status: 200,
payload: { data, total, next: nextPage, previous },
@@ -598,10 +585,6 @@ const getRowInTableByPK = async (req, res, next) => {
error: 'not_found',
});
} else {
// res.json({
// data
// });
req.response = { status: 200, payload: { data } };
next();
}

View File

@@ -19,7 +19,7 @@ describe('Rows Endpoints', () => {
it('GET /tables/:name/rows should return a list of all rows', async () => {
const accessToken = await generateToken(
{ username: 'John', isSuperuser: true },
config.accessTokenSecret,
config.tokenSecret,
'1H',
);
@@ -39,7 +39,7 @@ describe('Rows Endpoints', () => {
it('GET /tables/:name/rows?_limit=8&_schema=firstName,lastName&_ordering:-firstName&_page=2: should query the rows by the provided query params', async () => {
const accessToken = await generateToken(
{ username: 'John', isSuperuser: true },
config.accessTokenSecret,
config.tokenSecret,
'1H',
);
@@ -80,7 +80,7 @@ describe('Rows Endpoints', () => {
it('GET /tables/:name/rows: should return a null field', async () => {
const accessToken = await generateToken(
{ username: 'John', isSuperuser: true },
config.accessTokenSecret,
config.tokenSecret,
'1H',
);
@@ -96,7 +96,7 @@ describe('Rows Endpoints', () => {
it('GET /tables/:name/rows: should successfully retrieve users created after 2010-01-01 00:00:00.', async () => {
const accessToken = await generateToken(
{ username: 'John', isSuperuser: true },
config.accessTokenSecret,
config.tokenSecret,
'1H',
);
@@ -121,7 +121,7 @@ describe('Rows Endpoints', () => {
it('GET /tables/:name/rows: should successfully retrieve users created before 2008-01-20 00:00:00.', async () => {
const accessToken = await generateToken(
{ username: 'John', isSuperuser: true },
config.accessTokenSecret,
config.tokenSecret,
'1H',
);
@@ -146,7 +146,7 @@ describe('Rows Endpoints', () => {
it('GET /tables/:name/rows: should successfully retrieve users created at 2013-01-08 00:00:00', async () => {
const accessToken = await generateToken(
{ username: 'John', isSuperuser: true },
config.accessTokenSecret,
config.tokenSecret,
'1H',
);
@@ -171,7 +171,7 @@ describe('Rows Endpoints', () => {
it('GET /tables/:name/rows: should successfully retrieve users created at 2007-01-08 00:00:00', async () => {
const accessToken = await generateToken(
{ username: 'John', isSuperuser: true },
config.accessTokenSecret,
config.tokenSecret,
'1H',
);
@@ -188,7 +188,7 @@ describe('Rows Endpoints', () => {
it('GET /tables/:name/rows: should successfully retrieve users that are not created at 2021-01-08 00:00:00', async () => {
const accessToken = await generateToken(
{ username: 'John', isSuperuser: true },
config.accessTokenSecret,
config.tokenSecret,
'1H',
);
@@ -213,7 +213,7 @@ describe('Rows Endpoints', () => {
it('POST /tables/:name/rows should insert a new row and return the lastInsertRowid', async () => {
const accessToken = await generateToken(
{ username: 'John', isSuperuser: true },
config.accessTokenSecret,
config.tokenSecret,
'1H',
);
@@ -230,7 +230,7 @@ describe('Rows Endpoints', () => {
it('GET /tables/:name/rows/:pks should return a row by its primary key', async () => {
const accessToken = await generateToken(
{ username: 'John', isSuperuser: true },
config.accessTokenSecret,
config.tokenSecret,
'1H',
);
@@ -249,7 +249,7 @@ describe('Rows Endpoints', () => {
it('PUT /tables/:name/rows/:pks should update a row by its primary key and return the number of changes', async () => {
const accessToken = await generateToken(
{ username: 'John', isSuperuser: true },
config.accessTokenSecret,
config.tokenSecret,
'1H',
);
const res = await requestWithSupertest
@@ -263,7 +263,7 @@ describe('Rows Endpoints', () => {
it('DELETE /tables/:name/rows/:pks should delete a row by its primary key and return the number of changes', async () => {
const accessToken = await generateToken(
{ username: 'John', isSuperuser: true },
config.accessTokenSecret,
config.tokenSecret,
'1H',
);
@@ -277,7 +277,7 @@ describe('Rows Endpoints', () => {
it('POST /tables/:name/rows should insert a new row if any of the value of the object being inserted is null', async () => {
const accessToken = await generateToken(
{ username: 'John', isSuperuser: true },
config.accessTokenSecret,
config.tokenSecret,
'1H',
);
const res = await requestWithSupertest
@@ -299,7 +299,7 @@ describe('Rows Endpoints', () => {
it('GET /tables/:name/rows should return values if any of the IDs from the array match the user ID.', async () => {
const accessToken = await generateToken(
{ username: 'John', isSuperuser: true },
config.accessTokenSecret,
config.tokenSecret,
'1H',
);
@@ -315,7 +315,7 @@ describe('Rows Endpoints', () => {
it('GET /tables/:name/rows should return values if the provided ID matches the user ID.', async () => {
const accessToken = await generateToken(
{ username: 'John', isSuperuser: true },
config.accessTokenSecret,
config.tokenSecret,
'1H',
);

View File

@@ -10,7 +10,7 @@ describe('Tables Endpoints', () => {
it('GET /tables should return a list of all tables', async () => {
const accessToken = await generateToken(
{ username: 'John', isSuperuser: true },
config.accessTokenSecret,
config.tokenSecret,
'1H',
);
@@ -28,7 +28,7 @@ describe('Tables Endpoints', () => {
it('POST /tables should create a new table and return generated schema', async () => {
const accessToken = await generateToken(
{ username: 'John', isSuperuser: true },
config.accessTokenSecret,
config.tokenSecret,
'1H',
);
@@ -76,7 +76,7 @@ describe('Tables Endpoints', () => {
it('GET /tables/:name should return schema of the table', async () => {
const accessToken = await generateToken(
{ username: 'John', isSuperuser: true },
config.accessTokenSecret,
config.tokenSecret,
'1H',
);

View File

@@ -8,7 +8,7 @@ const processRequest = async (req, res, next) => {
// If the user sends a request when auth is set to false, throw an error
if (apiConstants.defaultRoutes.includes(resource) && !config.auth) {
return res.status(401).send({
return res.status(403).send({
message: 'You can not access this endpoint while AUTH is set to false',
});
}

View File

@@ -2,7 +2,7 @@ const config = require('../config');
const { decodeToken, toBoolean } = require('../utils/index');
const httpVerbs = require('../constants/httpVerbs');
const isAuthorized = async (req, res, next) => {
const isAuthenticated = async (req, res, next) => {
let payload;
const { name: tableName } = req.params;
const verb = req.method;
@@ -13,7 +13,7 @@ const isAuthorized = async (req, res, next) => {
try {
payload = await decodeToken(
req.cookies.accessToken,
config.accessTokenSecret,
config.tokenSecret,
);
req.user = payload;
} catch (error) {
@@ -67,4 +67,4 @@ const isAuthorized = async (req, res, next) => {
}
};
module.exports = { isAuthorized };
module.exports = { isAuthenticated };

View File

@@ -3,7 +3,7 @@ const express = require('express');
const controllers = require('../controllers/auth');
const { validator } = require('../middlewares/validation');
const schema = require('../schemas/auth');
const { isAuthorized } = require('../middlewares/auth');
const { isAuthenticated } = require('../middlewares/auth');
const router = express.Router();
@@ -20,9 +20,9 @@ router.get(
);
router.put(
'/:userId/change-password',
'/change-password',
validator(schema.changePassword),
isAuthorized,
isAuthenticated,
controllers.changePassword,
);

View File

@@ -4,14 +4,14 @@ const controllers = require('../controllers/rows');
const { broadcast } = require('../middlewares/broadcast');
const { validator } = require('../middlewares/validation');
const { processRequest, processResponse } = require('../middlewares/api');
const { isAuthorized } = require('../middlewares/auth');
const { isAuthenticated } = require('../middlewares/auth');
const schema = require('../schemas/rows');
const router = express.Router();
router.get(
'/:name/rows',
isAuthorized,
isAuthenticated,
validator(schema.listTableRows),
processRequest,
controllers.listTableRows,
@@ -19,7 +19,7 @@ router.get(
);
router.post(
'/:name/rows',
isAuthorized,
isAuthenticated,
validator(schema.insertRowInTable),
processRequest,
controllers.insertRowInTable,
@@ -27,21 +27,21 @@ router.post(
);
router.get(
'/:name/rows/:pks',
isAuthorized,
isAuthenticated,
validator(schema.getRowInTableByPK),
controllers.getRowInTableByPK,
processResponse,
);
router.put(
'/:name/rows/:pks',
isAuthorized,
isAuthenticated,
validator(schema.updateRowInTableByPK),
controllers.updateRowInTableByPK,
broadcast,
);
router.delete(
'/:name/rows/:pks',
isAuthorized,
isAuthenticated,
validator(schema.deleteRowInTableByPK),
controllers.deleteRowInTableByPK,
broadcast,

View File

@@ -3,31 +3,31 @@ const express = require('express');
const controllers = require('../controllers/tables');
const { validator } = require('../middlewares/validation');
const schema = require('../schemas/tables');
const { isAuthorized } = require('../middlewares/auth');
const { isAuthenticated } = require('../middlewares/auth');
const router = express.Router();
router.get(
'/',
isAuthorized,
isAuthenticated,
validator(schema.listTables),
controllers.listTables,
);
router.post(
'/',
isAuthorized,
isAuthenticated,
validator(schema.createTable),
controllers.createTable,
);
router.get(
'/:name',
isAuthorized,
isAuthenticated,
validator(schema.getTableSchema),
controllers.getTableSchema,
);
router.delete(
'/:name',
isAuthorized,
isAuthenticated,
validator(schema.deleteTable),
controllers.deleteTable,
);

View File

@@ -1,3 +1,5 @@
const { apiConstants } = require('../constants');
module.exports = (db) => {
return {
get(data) {
@@ -10,8 +12,8 @@ module.exports = (db) => {
const statement = db.prepare(query);
const result = statement.all(
...data.whereStringValues,
data.limit || 10,
data.page || 0,
data.limit || apiConstants.DEFAULT_PAGE_LIMIT,
data.page || apiConstants.DEFAULT_PAGE_INDEX,
);
return result;

View File

@@ -540,16 +540,10 @@
}
}
},
"/api/auth/{userId}/change-password": {
"/api/auth/change-password": {
"put": {
"description": "",
"parameters": [
{
"name": "userId",
"in": "path",
"required": true,
"type": "string"
},
{
"name": "body",
"in": "body",