fix: should retrieve user inactive error in login response API.

fix: prevent from delete or inactivate the current authorized user.
This commit is contained in:
Ahmed Bouhuolia
2020-09-20 18:39:14 +02:00
parent e28f8496c6
commit e2c53f4513
11 changed files with 151 additions and 105 deletions

14
.env
View File

@@ -1,14 +0,0 @@
MAIL_HOST=
MAIL_USERNAME=
MAIL_PASSWORD=
MAIL_PORT=
MAIL_SECURE=false
MAIL_FROM_ADDRESS=
MAIL_FROM_NAME=
DB_CLIENT=mysql
DB_HOST=127.0.0.1
DB_USER=root
DB_PASSWORD=root
DB_NAME=ratteb

43
server/.env.example Normal file
View File

@@ -0,0 +1,43 @@
MAIL_HOST=smtp.mailtrap.io
MAIL_USERNAME=842f331d3dc005
MAIL_PASSWORD=172f97b34f1a17
MAIL_PORT=587
MAIL_SECURE=false
MAIL_FROM_ADDRESS=
MAIL_FROM_NAME=
SYSTEM_DB_CLIENT=mysql
SYSTEM_DB_HOST=127.0.0.1
SYSTEM_DB_USER=root
SYSTEM_DB_PASSWORD=root
SYSTEM_DB_NAME=bigcapital_system
SYSTEM_MIGRATIONS_DIR=./src/system/migrations
SYSTEM_SEEDS_DIR=./src/system/seeds
TENANT_DB_CLIENT=mysql
TENANT_DB_NAME_PERFIX=bigcapital_tenant_
TENANT_DB_HOST=127.0.0.1
TENANT_DB_PASSWORD=root
TEANNT_DB_USER=root
TENANT_DB_CHARSET=charset
TENANT_MIGRATIONS_DIR=src/database/migrations
TENANT_SEEDS_DIR=src/database/seeds/core
DB_MANAGER_SUPER_USER=root
DB_MANAGER_SUPER_PASSWORD=root
MONGODB_DATABASE_URL=mongodb://localhost/bigcapital
EASY_SMS_TOKEN=b0JDZW56RnV6aEthb0RGPXVEcUI
JWT_SECRET=b0JDZW56RnV6aEthb0RGPXVEcUI
CONTACT_US_MAIL=support@bigcapital.ly
BASE_URL=https://bigcapital.ly
LICENSES_AUTH_USER=root
LICENSES_AUTH_PASSWORD=root
AGENDASH_AUTH_USER=agendash
AGENDASH_AUTH_PASSWORD=123123

View File

@@ -119,7 +119,7 @@ export default class AuthenticationController extends BaseController{
} }
if (error.errorType === 'user_inactive') { if (error.errorType === 'user_inactive') {
return res.boom.badRequest(null, { return res.boom.badRequest(null, {
errors: [{ type: 'INVALID_DETAILS', code: 200 }], errors: [{ type: 'USER_INACTIVE', code: 200 }],
}); });
} }
} }

View File

@@ -249,32 +249,32 @@ export default class ExpensesController extends BaseController {
if (error instanceof ServiceError) { if (error instanceof ServiceError) {
if (error.errorType === 'expense_not_found') { if (error.errorType === 'expense_not_found') {
return res.boom.badRequest(null, { return res.boom.badRequest(null, {
errors: [{ type: 'EXPENSE_NOT_FOUND' }], errors: [{ type: 'EXPENSE_NOT_FOUND', code: 100 }],
}); });
} }
if (error.errorType === 'total_amount_equals_zero') { if (error.errorType === 'total_amount_equals_zero') {
return res.boom.badRequest(null, { return res.boom.badRequest(null, {
errors: [{ type: 'TOTAL.AMOUNT.EQUALS.ZERO' }], errors: [{ type: 'TOTAL.AMOUNT.EQUALS.ZERO', code: 200 }],
}); });
} }
if (error.errorType === 'payment_account_not_found') { if (error.errorType === 'payment_account_not_found') {
return res.boom.badRequest(null, { return res.boom.badRequest(null, {
errors: [{ type: 'PAYMENT.ACCOUNT.NOT.FOUND', }], errors: [{ type: 'PAYMENT.ACCOUNT.NOT.FOUND', code: 300 }],
}); });
} }
if (error.errorType === 'some_expenses_not_found') { if (error.errorType === 'some_expenses_not_found') {
return res.boom.badRequest(null, { return res.boom.badRequest(null, {
errors: [{ type: 'SOME.EXPENSE.ACCOUNTS.NOT.FOUND', code: 200 }] errors: [{ type: 'SOME.EXPENSE.ACCOUNTS.NOT.FOUND', code: 400 }]
}) })
} }
if (error.errorType === 'payment_account_has_invalid_type') { if (error.errorType === 'payment_account_has_invalid_type') {
return res.boom.badRequest(null, { return res.boom.badRequest(null, {
errors: [{ type: 'PAYMENT.ACCOUNT.HAS.INVALID.TYPE' }], errors: [{ type: 'PAYMENT.ACCOUNT.HAS.INVALID.TYPE', code: 500 }],
}); });
} }
if (error.errorType === 'expenses_account_has_invalid_type') { if (error.errorType === 'expenses_account_has_invalid_type') {
return res.boom.badRequest(null, { return res.boom.badRequest(null, {
errors: [{ type: 'EXPENSES.ACCOUNT.HAS.INVALID.TYPE' }] errors: [{ type: 'EXPENSES.ACCOUNT.HAS.INVALID.TYPE', code: 600 }]
}); });
} }
} }

View File

@@ -26,37 +26,42 @@ export default class UsersController extends BaseController{
...this.specificUserSchema, ...this.specificUserSchema,
], ],
this.validationResult, this.validationResult,
asyncMiddleware(this.inactivateUser.bind(this)) asyncMiddleware(this.inactivateUser.bind(this)),
this.catchServiceErrors,
); );
router.put('/:id/activate', [ router.put('/:id/activate', [
...this.specificUserSchema ...this.specificUserSchema
], ],
this.validationResult, this.validationResult,
asyncMiddleware(this.activateUser.bind(this)) asyncMiddleware(this.activateUser.bind(this)),
this.catchServiceErrors,
); );
router.post('/:id', [ router.post('/:id', [
...this.userDTOSchema, ...this.userDTOSchema,
...this.specificUserSchema, ...this.specificUserSchema,
], ],
this.validationResult, this.validationResult,
asyncMiddleware(this.editUser.bind(this)) asyncMiddleware(this.editUser.bind(this)),
this.catchServiceErrors,
); );
router.get('/', router.get('/',
this.listUsersSchema, this.listUsersSchema,
this.validationResult, this.validationResult,
asyncMiddleware(this.listUsers.bind(this)) asyncMiddleware(this.listUsers.bind(this)),
); );
router.get('/:id', [ router.get('/:id', [
...this.specificUserSchema, ...this.specificUserSchema,
], ],
this.validationResult, this.validationResult,
asyncMiddleware(this.getUser.bind(this)) asyncMiddleware(this.getUser.bind(this)),
this.catchServiceErrors,
); );
router.delete('/:id', [ router.delete('/:id', [
...this.specificUserSchema ...this.specificUserSchema
], ],
this.validationResult, this.validationResult,
asyncMiddleware(this.deleteUser.bind(this)) asyncMiddleware(this.deleteUser.bind(this)),
this.catchServiceErrors,
); );
return router; return router;
} }
@@ -101,19 +106,6 @@ export default class UsersController extends BaseController{
await this.usersService.editUser(tenantId, userId, userDTO); await this.usersService.editUser(tenantId, userId, userDTO);
return res.status(200).send({ id: userId }); return res.status(200).send({ id: userId });
} catch (error) { } catch (error) {
if (error instanceof ServiceErrors) {
const errorReasons = [];
if (error.errorType === 'email_already_exists') {
errorReasons.push({ type: 'EMAIL_ALREADY_EXIST', code: 100 });
}
if (error.errorType === 'phone_number_already_exist') {
errorReasons.push({ type: 'PHONE_NUMBER_ALREADY_EXIST', code: 200 });
}
if (errorReasons.length > 0) {
return res.status(400).send({ errors: errorReasons });
}
}
next(error); next(error);
} }
} }
@@ -128,19 +120,10 @@ export default class UsersController extends BaseController{
const { id } = req.params; const { id } = req.params;
const { tenantId } = req; const { tenantId } = req;
debugger;
try { try {
await this.usersService.deleteUser(tenantId, id); await this.usersService.deleteUser(tenantId, id);
return res.status(200).send({ id }); return res.status(200).send({ id });
} catch (error) { } catch (error) {
if (error instanceof ServiceError) {
if (error.errorType === 'user_not_found') {
return res.boom.notFound(null, {
errors: [{ type: 'USER_NOT_FOUND', code: 100 }],
});
}
}
next(error); next(error);
} }
} }
@@ -159,15 +142,8 @@ export default class UsersController extends BaseController{
const user = await this.usersService.getUser(tenantId, userId); const user = await this.usersService.getUser(tenantId, userId);
return res.status(200).send({ user }); return res.status(200).send({ user });
} catch (error) { } catch (error) {
if (error instanceof ServiceError) {
if (error.errorType === 'user_not_found') {
return res.boom.notFound(null, {
errors: [{ type: 'USER_NOT_FOUND', code: 100 }],
});
}
}
next(error); next(error);
} }
} }
/** /**
@@ -194,25 +170,13 @@ export default class UsersController extends BaseController{
* @param {NextFunction} next * @param {NextFunction} next
*/ */
async activateUser(req: Request, res: Response, next: NextFunction) { async activateUser(req: Request, res: Response, next: NextFunction) {
const { tenantId } = req; const { tenantId, user } = req;
const { id: userId } = req.params; const { id: userId } = req.params;
try { try {
await this.usersService.activateUser(tenantId, userId); await this.usersService.activateUser(tenantId, userId, user);
return res.status(200).send({ id: userId }); return res.status(200).send({ id: userId });
} catch(error) { } catch(error) {
if (error instanceof ServiceError) {
if (error.errorType === 'user_not_found') {
return res.status(404).send({
errors: [{ type: 'USER.NOT.FOUND', code: 100 }],
});
}
if (error.errorType === 'user_already_active') {
return res.status(404).send({
errors: [{ type: 'USER.ALREADY.ACTIVE', code: 200 }],
});
}
}
next(error); next(error);
} }
} }
@@ -228,22 +192,57 @@ export default class UsersController extends BaseController{
const { id: userId } = req.params; const { id: userId } = req.params;
try { try {
await this.usersService.inactivateUser(tenantId, userId); await this.usersService.inactivateUser(tenantId, userId, user);
return res.status(200).send({ id: userId }); return res.status(200).send({ id: userId });
} catch(error) { } catch(error) {
if (error instanceof ServiceError) {
if (error.errorType === 'user_not_found') {
return res.status(404).send({
errors: [{ type: 'USER.NOT.FOUND', code: 100 }],
});
}
if (error.errorType === 'user_already_inactive') {
return res.status(404).send({
errors: [{ type: 'USER.ALREADY.INACTIVE', code: 200 }],
});
}
}
next(error); next(error);
} }
} }
/**
* Catches all users service errors.
* @param {Error} error
* @param {Request} req
* @param {Response} res
* @param {NextFunction} next
*/
catchServiceErrors(error: Error, req: Request, res: Response, next: NextFunction) {
if (error instanceof ServiceErrors) {
const errorReasons = [];
if (error.errorType === 'email_already_exists') {
errorReasons.push({ type: 'EMAIL_ALREADY_EXIST', code: 100 });
}
if (error.errorType === 'phone_number_already_exist') {
errorReasons.push({ type: 'PHONE_NUMBER_ALREADY_EXIST', code: 200 });
}
if (errorReasons.length > 0) {
return res.status(400).send({ errors: errorReasons });
}
}
if (error instanceof ServiceError) {
if (error.errorType === 'user_not_found') {
return res.status(404).send({
errors: [{ type: 'USER.NOT.FOUND', code: 100 }],
});
}
if (error.errorType === 'user_already_active') {
return res.status(404).send({
errors: [{ type: 'USER.ALREADY.ACTIVE', code: 200 }],
});
}
if (error.errorType === 'user_already_inactive') {
return res.status(404).send({
errors: [{ type: 'USER.ALREADY.INACTIVE', code: 200 }],
});
}
if (error.errorType === 'user_same_the_authorized_user') {
return res.boom.badRequest(
'You could not activate/inactivate the same authorized user.',
{ errors: [{ type: 'CANNOT.TOGGLE.ACTIVATE.AUTHORIZED.USER', code: 300 }] },
)
}
}
next(error);
}
}; };

View File

@@ -14,11 +14,19 @@ const attachCurrentUser = async (req: Request, res: Response, next: Function) =>
try { try {
Logger.info('[attach_user_middleware] finding system user by id.'); Logger.info('[attach_user_middleware] finding system user by id.');
const user = await systemUserRepository.getById(req.token.id); const user = await systemUserRepository.getById(req.token.id);
console.log(user);
if (!user) { if (!user) {
Logger.info('[attach_user_middleware] the system user not found.'); Logger.info('[attach_user_middleware] the system user not found.');
return res.boom.unauthorized(); return res.boom.unauthorized();
} }
if (!user.active) {
Logger.info('[attach_user_middleware] the system user not found.');
return res.boom.badRequest(
'The authorized user is inactivated.',
{ errors: [{ type: 'USER_INACTIVE', code: 100, }] },
);
}
// Delete password property from user object. // Delete password property from user object.
Reflect.deleteProperty(user, 'password'); Reflect.deleteProperty(user, 'password');
req.user = user; req.user = user;

View File

@@ -31,26 +31,26 @@ export default {
// Accounts // Accounts
'accounts': { 'accounts': {
'name': { name: {
column: 'name', column: 'name',
}, },
'type': { type: {
column: 'account_type_id', column: 'account_type_id',
relation: 'account_types.id', relation: 'account_types.id',
relationColumn: 'account_types.key', relationColumn: 'account_types.key',
}, },
'description': { description: {
column: 'description', column: 'description',
}, },
'code': { code: {
column: 'code', column: 'code',
}, },
'root_type': { root_type: {
column: 'account_type_id', column: 'account_type_id',
relation: 'account_types.id', relation: 'account_types.id',
relationColumn: 'account_types.root_type', relationColumn: 'account_types.root_type',
}, },
'created_at': { created_at: {
column: 'created_at', column: 'created_at',
columnType: 'date', columnType: 'date',
}, },

View File

@@ -59,20 +59,20 @@ export default class AuthenticationService {
this.logger.info('[login] invalid data'); this.logger.info('[login] invalid data');
throw new ServiceError('invalid_details'); throw new ServiceError('invalid_details');
} }
this.logger.info('[login] check password validation.'); this.logger.info('[login] check password validation.', { emailOrPhone, password });
if (!user.verifyPassword(password)) { if (!user.verifyPassword(password)) {
throw new ServiceError('invalid_password'); throw new ServiceError('invalid_password');
} }
if (!user.active) { if (!user.active) {
this.logger.info('[login] user inactive.'); this.logger.info('[login] user inactive.', { userId: user.id });
throw new ServiceError('user_inactive'); throw new ServiceError('user_inactive');
} }
this.logger.info('[login] generating JWT token.'); this.logger.info('[login] generating JWT token.', { userId: user.id });
const token = this.generateToken(user); const token = this.generateToken(user);
this.logger.info('[login] updating user last login at.'); this.logger.info('[login] updating user last login at.', { userId: user.id });
await systemUserRepository.patchLastLoginAt(user.id); await systemUserRepository.patchLastLoginAt(user.id);
this.logger.info('[login] Logging success.', { user, token }); this.logger.info('[login] Logging success.', { user, token });

View File

@@ -53,7 +53,7 @@ export default class UsersService {
* @param {number} userId - * @param {number} userId -
* @returns {ISystemUser} * @returns {ISystemUser}
*/ */
async getUserOrThrowError(tenantId: number, userId: number): void { async getUserOrThrowError(tenantId: number, userId: number): Promise<ISystemUser> {
const { systemUserRepository } = this.repositories; const { systemUserRepository } = this.repositories;
const user = await systemUserRepository.getByIdAndTenant(userId, tenantId); const user = await systemUserRepository.getByIdAndTenant(userId, tenantId);
@@ -72,7 +72,7 @@ export default class UsersService {
async deleteUser(tenantId: number, userId: number): Promise<void> { async deleteUser(tenantId: number, userId: number): Promise<void> {
const { systemUserRepository } = this.repositories; const { systemUserRepository } = this.repositories;
await this.getUserOrThrowError(tenantId, userId); await this.getUserOrThrowError(tenantId, userId);
this.logger.info('[users] trying to delete the given user.', { tenantId, userId }); this.logger.info('[users] trying to delete the given user.', { tenantId, userId });
await systemUserRepository.deleteById(userId); await systemUserRepository.deleteById(userId);
@@ -84,7 +84,8 @@ export default class UsersService {
* @param {number} tenantId * @param {number} tenantId
* @param {number} userId * @param {number} userId
*/ */
async activateUser(tenantId: number, userId: number): Promise<void> { async activateUser(tenantId: number, userId: number, authorizedUser: ISystemUser): Promise<void> {
this.throwErrorIfUserIdSameAuthorizedUser(userId, authorizedUser);
const { systemUserRepository } = this.repositories; const { systemUserRepository } = this.repositories;
const user = await this.getUserOrThrowError(tenantId, userId); const user = await this.getUserOrThrowError(tenantId, userId);
@@ -99,8 +100,10 @@ export default class UsersService {
* @param {number} userId * @param {number} userId
* @return {Promise<void>} * @return {Promise<void>}
*/ */
async inactivateUser(tenantId: number, userId: number): Promise<void> { async inactivateUser(tenantId: number, userId: number, authorizedUser: ISystemUser): Promise<void> {
this.throwErrorIfUserIdSameAuthorizedUser(userId, authorizedUser);
const { systemUserRepository } = this.repositories; const { systemUserRepository } = this.repositories;
const user = await this.getUserOrThrowError(tenantId, userId); const user = await this.getUserOrThrowError(tenantId, userId);
this.throwErrorIfUserInactive(user); this.throwErrorIfUserInactive(user);
@@ -114,6 +117,7 @@ export default class UsersService {
*/ */
async getList(tenantId: number) { async getList(tenantId: number) {
const users = await SystemUser.query() const users = await SystemUser.query()
.whereNotDeleted()
.where('tenant_id', tenantId); .where('tenant_id', tenantId);
return users; return users;
@@ -149,4 +153,15 @@ export default class UsersService {
throw new ServiceError('user_already_inactive'); throw new ServiceError('user_already_inactive');
} }
} }
/**
* Throw service error in case the given user same the authorized user.
* @param {number} userId
* @param {ISystemUser} authorizedUser
*/
throwErrorIfUserIdSameAuthorizedUser(userId: number, authorizedUser: ISystemUser) {
if (userId === authorizedUser.id) {
throw new ServiceError('user_same_the_authorized_user');
}
}
} }

View File

@@ -8,9 +8,8 @@ exports.up = function (knex) {
table.string('phone_number').unique(); table.string('phone_number').unique();
table.string('password'); table.string('password');
table.boolean('active'); table.boolean('active');
table.integer('role_id').unique();
table.string('language'); table.string('language');
table.integer('tenant_id').unsigned(); table.integer('tenant_id').unsigned();
table.date('invite_accepted_at'); table.date('invite_accepted_at');
@@ -18,10 +17,6 @@ exports.up = function (knex) {
table.dateTime('deleted_at'); table.dateTime('deleted_at');
table.timestamps(); table.timestamps();
}).then(() => {
// knex.seed.run({
// specific: 'seed_users.js',
// })
}); });
}; };

View File

@@ -98,7 +98,7 @@ export default class SystemUserRepository extends SystemRepository {
* @param {number} userId * @param {number} userId
*/ */
async deleteById(userId: number) { async deleteById(userId: number) {
const user = this.getById(userId); const user = await this.getById(userId);
await SystemUser.query().where('id', userId).delete(); await SystemUser.query().where('id', userId).delete();
this.flushUserCache(user); this.flushUserCache(user);
} }