mirror of
https://github.com/bigcapitalhq/bigcapital.git
synced 2026-02-21 23:30:32 +00:00
feat: fix issues in invite user.
feat: fix update last login at after login.
This commit is contained in:
@@ -1,4 +1,5 @@
|
|||||||
import { matchedData } from "express-validator";
|
import { Response, Request } from 'express';
|
||||||
|
import { matchedData, validationResult } from "express-validator";
|
||||||
import { mapKeys, camelCase, omit } from "lodash";
|
import { mapKeys, camelCase, omit } from "lodash";
|
||||||
|
|
||||||
export default class BaseController {
|
export default class BaseController {
|
||||||
@@ -11,4 +12,16 @@ export default class BaseController {
|
|||||||
});
|
});
|
||||||
return mapKeys(data, (v, k) => camelCase(k));
|
return mapKeys(data, (v, k) => camelCase(k));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
validationResult(req: Request, res: Response, next: NextFunction) {
|
||||||
|
const validationErrors = validationResult(req);
|
||||||
|
|
||||||
|
if (!validationErrors.isEmpty()) {
|
||||||
|
return res.boom.badData(null, {
|
||||||
|
code: 'validation_error',
|
||||||
|
...validationErrors,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
next();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -4,50 +4,61 @@ import {
|
|||||||
check,
|
check,
|
||||||
body,
|
body,
|
||||||
param,
|
param,
|
||||||
matchedData,
|
|
||||||
} from 'express-validator';
|
} from 'express-validator';
|
||||||
import asyncMiddleware from '@/http/middleware/asyncMiddleware';
|
import asyncMiddleware from '@/http/middleware/asyncMiddleware';
|
||||||
import jwtAuth from '@/http/middleware/jwtAuth';
|
|
||||||
import TenancyMiddleware from '@/http/middleware/TenancyMiddleware';
|
|
||||||
import InviteUserService from '@/services/InviteUsers';
|
import InviteUserService from '@/services/InviteUsers';
|
||||||
import { ServiceErrors, ServiceError } from '@/exceptions';
|
import { ServiceErrors, ServiceError } from '@/exceptions';
|
||||||
|
import BaseController from './BaseController';
|
||||||
|
|
||||||
@Service()
|
@Service()
|
||||||
export default class InviteUsersController {
|
export default class InviteUsersController extends BaseController {
|
||||||
@Inject()
|
@Inject()
|
||||||
inviteUsersService: InviteUserService;
|
inviteUsersService: InviteUserService;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Router constructor.
|
* Routes that require authentication.
|
||||||
*/
|
*/
|
||||||
router() {
|
authRouter() {
|
||||||
const router = Router();
|
const router = Router();
|
||||||
|
|
||||||
router.use('/send', jwtAuth);
|
|
||||||
router.use('/send', TenancyMiddleware);
|
|
||||||
|
|
||||||
router.post('/send', [
|
router.post('/send', [
|
||||||
body('email').exists().trim().escape(),
|
body('email').exists().trim().escape(),
|
||||||
],
|
],
|
||||||
asyncMiddleware(this.sendInvite),
|
asyncMiddleware(this.sendInvite.bind(this)),
|
||||||
);
|
);
|
||||||
|
return router;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Routes that non-required authentication.
|
||||||
|
*/
|
||||||
|
nonAuthRouter() {
|
||||||
|
const router = Router();
|
||||||
|
|
||||||
router.post('/accept/:token', [
|
router.post('/accept/:token', [
|
||||||
|
...this.inviteUserDTO,
|
||||||
|
],
|
||||||
|
asyncMiddleware(this.accept.bind(this)));
|
||||||
|
|
||||||
|
router.get('/invited/:token', [
|
||||||
|
param('token').exists().trim().escape(),
|
||||||
|
],
|
||||||
|
asyncMiddleware(this.invited.bind(this)));
|
||||||
|
|
||||||
|
return router;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Invite DTO schema validation.
|
||||||
|
*/
|
||||||
|
get inviteUserDTO() {
|
||||||
|
return [
|
||||||
check('first_name').exists().trim().escape(),
|
check('first_name').exists().trim().escape(),
|
||||||
check('last_name').exists().trim().escape(),
|
check('last_name').exists().trim().escape(),
|
||||||
check('phone_number').exists().trim().escape(),
|
check('phone_number').exists().trim().escape(),
|
||||||
check('password').exists().trim().escape(),
|
check('password').exists().trim().escape(),
|
||||||
param('token').exists().trim().escape(),
|
param('token').exists().trim().escape(),
|
||||||
],
|
];
|
||||||
asyncMiddleware(this.accept)
|
|
||||||
);
|
|
||||||
|
|
||||||
router.get('/invited/:token', [
|
|
||||||
param('token').exists().trim().escape(),
|
|
||||||
],
|
|
||||||
asyncMiddleware(this.invited)
|
|
||||||
);
|
|
||||||
return router;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -63,6 +74,11 @@ export default class InviteUsersController {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
await this.inviteUsersService.sendInvite(tenantId, email, user);
|
await this.inviteUsersService.sendInvite(tenantId, email, user);
|
||||||
|
return res.status(200).send({
|
||||||
|
type: 'success',
|
||||||
|
code: 'INVITE.SENT.SUCCESSFULLY',
|
||||||
|
message: 'The invite has been sent to the given email.',
|
||||||
|
})
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.log(error);
|
console.log(error);
|
||||||
if (error instanceof ServiceError) {
|
if (error instanceof ServiceError) {
|
||||||
@@ -84,7 +100,7 @@ export default class InviteUsersController {
|
|||||||
* @param {NextFunction} next -
|
* @param {NextFunction} next -
|
||||||
*/
|
*/
|
||||||
async accept(req: Request, res: Response, next: Function) {
|
async accept(req: Request, res: Response, next: Function) {
|
||||||
const inviteUserInput: IInviteUserInput = matchedData(req, {
|
const inviteUserInput: IInviteUserInput = this.matchedBodyData(req, {
|
||||||
locations: ['body'],
|
locations: ['body'],
|
||||||
includeOptionals: true,
|
includeOptionals: true,
|
||||||
});
|
});
|
||||||
@@ -92,20 +108,24 @@ export default class InviteUsersController {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
await this.inviteUsersService.acceptInvite(token, inviteUserInput);
|
await this.inviteUsersService.acceptInvite(token, inviteUserInput);
|
||||||
return res.status(200).send();
|
return res.status(200).send({
|
||||||
|
type: 'success',
|
||||||
|
code: 'USER.INVITE.ACCEPTED',
|
||||||
|
message: 'User invite has been accepted successfully.',
|
||||||
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|
||||||
if (error instanceof ServiceErrors) {
|
if (error instanceof ServiceError) {
|
||||||
const errorReasons = [];
|
|
||||||
|
|
||||||
if (error.hasType('email_exists')) {
|
if (error.errorType === 'phone_number_exists') {
|
||||||
errorReasons.push({ type: 'EMAIL.EXISTS' });
|
return res.status(400).send({
|
||||||
|
errors: [{ type: 'PHONE_NUMBER.EXISTS' }],
|
||||||
|
});
|
||||||
}
|
}
|
||||||
if (error.hasType('phone_number_exists')) {
|
if (error.errorType === 'invite_token_invalid') {
|
||||||
errorReasons.push({ type: 'PHONE_NUMBER.EXISTS' });
|
return res.status(400).send({
|
||||||
}
|
errors: [{ type: 'INVITE.TOKEN.INVALID' }],
|
||||||
if (errorReasons.length > 0) {
|
});
|
||||||
return res.status(400).send({ errors: errorReasons });
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
next(error);
|
next(error);
|
||||||
@@ -122,9 +142,13 @@ export default class InviteUsersController {
|
|||||||
const { token } = req.params;
|
const { token } = req.params;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await this.inviteUsersService.checkInvite(token);
|
const { inviteToken, orgName } = await this.inviteUsersService.checkInvite(token);
|
||||||
|
|
||||||
return res.status(200).send();
|
return res.status(200).send({
|
||||||
|
inviteToken: inviteToken.token,
|
||||||
|
email: inviteToken.email,
|
||||||
|
organizationName: orgName?.value,
|
||||||
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|
||||||
if (error instanceof ServiceError) {
|
if (error instanceof ServiceError) {
|
||||||
|
|||||||
@@ -44,7 +44,9 @@ export default class OrganizationController {
|
|||||||
await this.organizationService.build(buildOTD.organizationId);
|
await this.organizationService.build(buildOTD.organizationId);
|
||||||
|
|
||||||
return res.status(200).send({
|
return res.status(200).send({
|
||||||
type: 'ORGANIZATION.DATABASE.INITIALIZED',
|
type: 'success',
|
||||||
|
code: 'ORGANIZATION.DATABASE.INITIALIZED',
|
||||||
|
message: 'The organization database has been initialized.'
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (error instanceof ServiceError) {
|
if (error instanceof ServiceError) {
|
||||||
|
|||||||
@@ -1,6 +1,4 @@
|
|||||||
import 'reflect-metadata';
|
|
||||||
import { Router, Request, Response } from 'express';
|
import { Router, Request, Response } from 'express';
|
||||||
import i18n from 'i18n';
|
|
||||||
|
|
||||||
export default class Ping {
|
export default class Ping {
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -101,8 +101,9 @@ export default class PaymentViaVoucherController extends PaymentMethodController
|
|||||||
.subscriptionViaVoucher(tenant.id, planSlug, voucherCode);
|
.subscriptionViaVoucher(tenant.id, planSlug, voucherCode);
|
||||||
|
|
||||||
return res.status(200).send({
|
return res.status(200).send({
|
||||||
type: 'PAYMENT.SUCCESSFULLY.MADE',
|
type: 'success',
|
||||||
code: 100,
|
code: 'PAYMENT.SUCCESSFULLY.MADE',
|
||||||
|
message: 'Payment via voucher has been made successfully.',
|
||||||
});
|
});
|
||||||
} catch (exception) {
|
} catch (exception) {
|
||||||
const errorReasons = [];
|
const errorReasons = [];
|
||||||
|
|||||||
@@ -165,6 +165,7 @@ export default class VouchersController extends BaseController {
|
|||||||
);
|
);
|
||||||
return res.status(200).send({
|
return res.status(200).send({
|
||||||
code: 100,
|
code: 100,
|
||||||
|
type: 'VOUCHERES.GENERATED.SUCCESSFULLY',
|
||||||
message: 'The vouchers have been generated successfully.'
|
message: 'The vouchers have been generated successfully.'
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|||||||
@@ -1,249 +0,0 @@
|
|||||||
import express from 'express';
|
|
||||||
import {
|
|
||||||
check,
|
|
||||||
query,
|
|
||||||
param,
|
|
||||||
validationResult,
|
|
||||||
} from 'express-validator';
|
|
||||||
import asyncMiddleware from '@/http/middleware/asyncMiddleware';
|
|
||||||
import SystemUser from '@/system/models/SystemUser';
|
|
||||||
|
|
||||||
export default {
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Router constructor.
|
|
||||||
*/
|
|
||||||
router() {
|
|
||||||
const router = express.Router();
|
|
||||||
|
|
||||||
router.put('/:id/inactive',
|
|
||||||
this.inactiveUser.validation,
|
|
||||||
asyncMiddleware(this.inactiveUser.handler));
|
|
||||||
|
|
||||||
router.put('/:id/active',
|
|
||||||
this.activeUser.validation,
|
|
||||||
asyncMiddleware(this.activeUser.handler));
|
|
||||||
|
|
||||||
router.post('/:id',
|
|
||||||
this.editUser.validation,
|
|
||||||
asyncMiddleware(this.editUser.handler));
|
|
||||||
|
|
||||||
router.get('/',
|
|
||||||
this.listUsers.validation,
|
|
||||||
asyncMiddleware(this.listUsers.handler));
|
|
||||||
|
|
||||||
router.get('/:id',
|
|
||||||
this.getUser.validation,
|
|
||||||
asyncMiddleware(this.getUser.handler));
|
|
||||||
|
|
||||||
router.delete('/:id',
|
|
||||||
this.deleteUser.validation,
|
|
||||||
asyncMiddleware(this.deleteUser.handler));
|
|
||||||
|
|
||||||
return router;
|
|
||||||
},
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Edit details of the given user.
|
|
||||||
*/
|
|
||||||
editUser: {
|
|
||||||
validation: [
|
|
||||||
param('id').exists().isNumeric().toInt(),
|
|
||||||
check('first_name').exists(),
|
|
||||||
check('last_name').exists(),
|
|
||||||
check('email').exists().isEmail(),
|
|
||||||
check('phone_number').optional().isMobilePhone(),
|
|
||||||
],
|
|
||||||
async handler(req, res) {
|
|
||||||
const { id } = req.params;
|
|
||||||
const validationErrors = validationResult(req);
|
|
||||||
|
|
||||||
if (!validationErrors.isEmpty()) {
|
|
||||||
return res.boom.badData(null, {
|
|
||||||
code: 'validation_error', ...validationErrors,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
const { TenantUser } = req.models;
|
|
||||||
const { user } = req;
|
|
||||||
const form = { ...req.body };
|
|
||||||
|
|
||||||
const foundUsers = await TenantUser.query()
|
|
||||||
.whereNot('id', id)
|
|
||||||
.andWhere((q) => {
|
|
||||||
q.where('email', form.email);
|
|
||||||
q.orWhere('phone_number', form.phone_number);
|
|
||||||
});
|
|
||||||
|
|
||||||
const foundUserEmail = foundUsers.find((u) => u.email === form.email);
|
|
||||||
const foundUserPhone = foundUsers.find((u) => u.phoneNumber === form.phone_number);
|
|
||||||
|
|
||||||
const errorReasons = [];
|
|
||||||
|
|
||||||
if (foundUserEmail) {
|
|
||||||
errorReasons.push({ type: 'EMAIL_ALREADY_EXIST', code: 100 });
|
|
||||||
}
|
|
||||||
if (foundUserPhone) {
|
|
||||||
errorReasons.push({ type: 'PHONE_NUMBER_ALREADY_EXIST', code: 120 });
|
|
||||||
}
|
|
||||||
if (errorReasons.length > 0) {
|
|
||||||
return res.boom.badRequest(null, { errors: errorReasons });
|
|
||||||
}
|
|
||||||
const userForm = {
|
|
||||||
first_name: form.first_name,
|
|
||||||
last_name: form.last_name,
|
|
||||||
email: form.email,
|
|
||||||
phone_number: form.phone_number,
|
|
||||||
};
|
|
||||||
const updateTenantUser = TenantUser.query()
|
|
||||||
.where('id', id).update({ ...userForm });
|
|
||||||
|
|
||||||
const updateSystemUser = SystemUser.query()
|
|
||||||
.where('id', user.id).update({ ...userForm });
|
|
||||||
|
|
||||||
await Promise.all([
|
|
||||||
updateTenantUser, updateSystemUser,
|
|
||||||
]);
|
|
||||||
return res.status(200).send();
|
|
||||||
},
|
|
||||||
},
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Soft deleting the given user.
|
|
||||||
*/
|
|
||||||
deleteUser: {
|
|
||||||
validation: [
|
|
||||||
param('id').exists().isNumeric().toInt(),
|
|
||||||
],
|
|
||||||
async handler(req, res) {
|
|
||||||
const { id } = req.params;
|
|
||||||
const { TenantUser } = req.models;
|
|
||||||
const user = await TenantUser.query().where('id', id).first();
|
|
||||||
|
|
||||||
if (!user) {
|
|
||||||
return res.boom.notFound(null, {
|
|
||||||
errors: [{ type: 'USER_NOT_FOUND', code: 100 }],
|
|
||||||
});
|
|
||||||
}
|
|
||||||
const tenantUserDel = TenantUser.query().where('id', id).delete();
|
|
||||||
const systemUserDel = SystemUser.query().where('id', id).delete();
|
|
||||||
|
|
||||||
await Promise.all([
|
|
||||||
tenantUserDel,
|
|
||||||
systemUserDel,
|
|
||||||
]);
|
|
||||||
return res.status(200).send();
|
|
||||||
},
|
|
||||||
},
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Retrieve user details of the given user id.
|
|
||||||
*/
|
|
||||||
getUser: {
|
|
||||||
validation: [
|
|
||||||
param('id').exists().isNumeric().toInt(),
|
|
||||||
],
|
|
||||||
async handler(req, res) {
|
|
||||||
const { id } = req.params;
|
|
||||||
const { TenantUser } = req.models;
|
|
||||||
const user = await TenantUser.query().where('id', id).first();
|
|
||||||
|
|
||||||
if (!user) {
|
|
||||||
return res.boom.notFound();
|
|
||||||
}
|
|
||||||
return res.status(200).send({ user });
|
|
||||||
},
|
|
||||||
},
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Retrieve the list of users.
|
|
||||||
*/
|
|
||||||
listUsers: {
|
|
||||||
validation: [
|
|
||||||
query('page_size').optional().isNumeric().toInt(),
|
|
||||||
query('page').optional().isNumeric().toInt(),
|
|
||||||
],
|
|
||||||
async handler(req, res) {
|
|
||||||
const filter = {
|
|
||||||
page_size: 10,
|
|
||||||
page: 1,
|
|
||||||
...req.query,
|
|
||||||
};
|
|
||||||
const { TenantUser } = req.models;
|
|
||||||
const users = await TenantUser.query()
|
|
||||||
.page(filter.page - 1, filter.page_size);
|
|
||||||
|
|
||||||
return res.status(200).send({ users });
|
|
||||||
},
|
|
||||||
},
|
|
||||||
|
|
||||||
inactiveUser: {
|
|
||||||
validation: [
|
|
||||||
param('id').exists().isNumeric().toInt(),
|
|
||||||
],
|
|
||||||
async handler(req, res) {
|
|
||||||
const validationErrors = validationResult(req);
|
|
||||||
|
|
||||||
if (!validationErrors.isEmpty()) {
|
|
||||||
return res.boom.badData(null, {
|
|
||||||
code: 'validation_error', ...validationErrors,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
const { id } = req.params;
|
|
||||||
const { user } = req;
|
|
||||||
const { TenantUser } = req.models;
|
|
||||||
const tenantUser = TenantUser.query().where('id', id).first();
|
|
||||||
|
|
||||||
if (!tenantUser) {
|
|
||||||
return res.boom.notFound(null, {
|
|
||||||
errors: [{ type: 'USER.NOT.FOUND', code: 100 }],
|
|
||||||
});
|
|
||||||
}
|
|
||||||
const updateTenantUser = TenantUser.query()
|
|
||||||
.where('id', id).update({ active: false });
|
|
||||||
|
|
||||||
const updateSystemUser = SystemUser.query()
|
|
||||||
.where('id', user.id).update({ active: false });
|
|
||||||
|
|
||||||
await Promise.all([
|
|
||||||
updateTenantUser, updateSystemUser,
|
|
||||||
]);
|
|
||||||
|
|
||||||
return res.status(200).send({ id: tenantUser.id });
|
|
||||||
},
|
|
||||||
},
|
|
||||||
|
|
||||||
activeUser: {
|
|
||||||
validation: [
|
|
||||||
param('id').exists().isNumeric().toInt(),
|
|
||||||
],
|
|
||||||
async handler(req, res) {
|
|
||||||
const validationErrors = validationResult(req);
|
|
||||||
|
|
||||||
if (!validationErrors.isEmpty()) {
|
|
||||||
return res.boom.badData(null, {
|
|
||||||
code: 'validation_error', ...validationErrors,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
const { id } = req.params;
|
|
||||||
const { user } = req;
|
|
||||||
const { TenantUser } = req.models;
|
|
||||||
const tenantUser = TenantUser.query().where('id', id).first();
|
|
||||||
|
|
||||||
if (!tenantUser) {
|
|
||||||
return res.boom.notFound(null, {
|
|
||||||
errors: [{ type: 'USER.NOT.FOUND', code: 100 }],
|
|
||||||
});
|
|
||||||
}
|
|
||||||
const updateTenantUser = TenantUser.query()
|
|
||||||
.where('id', id).update({ active: true });
|
|
||||||
|
|
||||||
const updateSystemUser = SystemUser.query()
|
|
||||||
.where('id', user.id).update({ active: true });
|
|
||||||
|
|
||||||
await Promise.all([
|
|
||||||
updateTenantUser, updateSystemUser,
|
|
||||||
]);
|
|
||||||
return res.status(200).send({ id: tenantUser.id });
|
|
||||||
},
|
|
||||||
},
|
|
||||||
};
|
|
||||||
251
server/src/http/controllers/Users.ts
Normal file
251
server/src/http/controllers/Users.ts
Normal file
@@ -0,0 +1,251 @@
|
|||||||
|
import { Router, Request, Response, NextFunction } from 'express';
|
||||||
|
import { Service, Inject } from 'typedi';
|
||||||
|
import {
|
||||||
|
check,
|
||||||
|
query,
|
||||||
|
param,
|
||||||
|
} from 'express-validator';
|
||||||
|
import asyncMiddleware from '@/http/middleware/asyncMiddleware';
|
||||||
|
import BaseController from '@/http/controllers/BaseController';
|
||||||
|
import UsersService from '@/services/Users/UsersService';
|
||||||
|
import { ServiceError, ServiceErrors } from '@/exceptions';
|
||||||
|
import { ISystemUserDTO } from '@/interfaces';
|
||||||
|
|
||||||
|
@Service()
|
||||||
|
export default class UsersController extends BaseController{
|
||||||
|
@Inject()
|
||||||
|
usersService: UsersService;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Router constructor.
|
||||||
|
*/
|
||||||
|
router() {
|
||||||
|
const router = Router();
|
||||||
|
|
||||||
|
router.put('/:id/inactivate', [
|
||||||
|
...this.specificUserSchema,
|
||||||
|
],
|
||||||
|
this.validationResult,
|
||||||
|
asyncMiddleware(this.inactivateUser.bind(this))
|
||||||
|
);
|
||||||
|
router.put('/:id/activate', [
|
||||||
|
...this.specificUserSchema
|
||||||
|
],
|
||||||
|
this.validationResult,
|
||||||
|
asyncMiddleware(this.activateUser.bind(this))
|
||||||
|
);
|
||||||
|
router.post('/:id', [
|
||||||
|
...this.userDTOSchema,
|
||||||
|
...this.specificUserSchema,
|
||||||
|
],
|
||||||
|
this.validationResult,
|
||||||
|
asyncMiddleware(this.editUser.bind(this))
|
||||||
|
);
|
||||||
|
router.get('/',
|
||||||
|
this.listUsersSchema,
|
||||||
|
this.validationResult,
|
||||||
|
asyncMiddleware(this.listUsers.bind(this))
|
||||||
|
);
|
||||||
|
router.get('/:id', [
|
||||||
|
...this.specificUserSchema,
|
||||||
|
],
|
||||||
|
this.validationResult,
|
||||||
|
asyncMiddleware(this.getUser.bind(this))
|
||||||
|
);
|
||||||
|
router.delete('/:id', [
|
||||||
|
...this.specificUserSchema
|
||||||
|
],
|
||||||
|
this.validationResult,
|
||||||
|
asyncMiddleware(this.deleteUser.bind(this))
|
||||||
|
);
|
||||||
|
return router;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* User DTO Schema.
|
||||||
|
*/
|
||||||
|
get userDTOSchema() {
|
||||||
|
return [
|
||||||
|
check('first_name').exists(),
|
||||||
|
check('last_name').exists(),
|
||||||
|
check('email').exists().isEmail(),
|
||||||
|
check('phone_number').optional().isMobilePhone(),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
get specificUserSchema() {
|
||||||
|
return [
|
||||||
|
param('id').exists().isNumeric().toInt(),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
get listUsersSchema() {
|
||||||
|
return [
|
||||||
|
query('page_size').optional().isNumeric().toInt(),
|
||||||
|
query('page').optional().isNumeric().toInt(),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Edit details of the given user.
|
||||||
|
* @param {Request} req
|
||||||
|
* @param {Response} res
|
||||||
|
* @return {Response|void}
|
||||||
|
*/
|
||||||
|
async editUser(req: Request, res: Response, next: NextFunction) {
|
||||||
|
const userDTO: ISystemUserDTO = this.matchedBodyData(req);
|
||||||
|
const { tenantId } = req;
|
||||||
|
const { id: userId } = req.params;
|
||||||
|
|
||||||
|
try {
|
||||||
|
await this.usersService.editUser(tenantId, userId, userDTO);
|
||||||
|
return res.status(200).send({ id: userId });
|
||||||
|
} catch (error) {
|
||||||
|
console.log(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 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Soft deleting the given user.
|
||||||
|
* @param {Request} req
|
||||||
|
* @param {Response} res
|
||||||
|
* @return {Response|void}
|
||||||
|
*/
|
||||||
|
async deleteUser(req: Request, res: Response, next: Function) {
|
||||||
|
const { id } = req.params;
|
||||||
|
const { tenantId } = req;
|
||||||
|
|
||||||
|
try {
|
||||||
|
await this.usersService.deleteUser(tenantId, id);
|
||||||
|
return res.status(200).send({ id });
|
||||||
|
} 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();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieve user details of the given user id.
|
||||||
|
* @param {Request} req
|
||||||
|
* @param {Response} res
|
||||||
|
* @return {Response|void}
|
||||||
|
*/
|
||||||
|
async getUser(req: Request, res: Response, next: NextFunction) {
|
||||||
|
const { id: userId } = req.params;
|
||||||
|
const { tenantId } = req;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const user = await this.usersService.getUser(tenantId, userId);
|
||||||
|
return res.status(200).send({ user });
|
||||||
|
} 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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieve the list of users.
|
||||||
|
* @param {Request} req
|
||||||
|
* @param {Response} res
|
||||||
|
* @return {Response|void}
|
||||||
|
*/
|
||||||
|
async listUsers(req: Request, res: Response, next: NextFunction) {
|
||||||
|
const { tenantId } = req;
|
||||||
|
try {
|
||||||
|
const users = await this.usersService.getList(tenantId);
|
||||||
|
|
||||||
|
return res.status(200).send({ users });
|
||||||
|
} catch (error) {
|
||||||
|
next();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Activate the given user.
|
||||||
|
* @param {Request} req
|
||||||
|
* @param {Response} res
|
||||||
|
* @param {NextFunction} next
|
||||||
|
*/
|
||||||
|
async activateUser(req: Request, res: Response, next: NextFunction) {
|
||||||
|
const { tenantId } = req;
|
||||||
|
const { id: userId } = req.params;
|
||||||
|
|
||||||
|
try {
|
||||||
|
await this.usersService.activateUser(tenantId, userId);
|
||||||
|
return res.status(200).send({ id: userId });
|
||||||
|
} catch(error) {
|
||||||
|
console.log(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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Inactivate the given user.
|
||||||
|
* @param {Request} req
|
||||||
|
* @param {Response} res
|
||||||
|
* @return {Response|void}
|
||||||
|
*/
|
||||||
|
async inactivateUser(req: Request, res: Response, next: NextFunction) {
|
||||||
|
const { tenantId, user } = req;
|
||||||
|
const { id: userId } = req.params;
|
||||||
|
|
||||||
|
try {
|
||||||
|
await this.usersService.inactivateUser(tenantId, userId);
|
||||||
|
return res.status(200).send({ id: userId });
|
||||||
|
} 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 }],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -43,7 +43,7 @@ export default () => {
|
|||||||
app.use(I18nMiddleware);
|
app.use(I18nMiddleware);
|
||||||
|
|
||||||
app.use('/auth', Container.get(Authentication).router());
|
app.use('/auth', Container.get(Authentication).router());
|
||||||
app.use('/invite', Container.get(InviteUsers).router());
|
app.use('/invite', Container.get(InviteUsers).nonAuthRouter());
|
||||||
app.use('/organization', Container.get(Organization).router());
|
app.use('/organization', Container.get(Organization).router());
|
||||||
app.use('/vouchers', Container.get(VouchersController).router());
|
app.use('/vouchers', Container.get(VouchersController).router());
|
||||||
app.use('/subscription', Container.get(Subscription).router());
|
app.use('/subscription', Container.get(Subscription).router());
|
||||||
@@ -59,7 +59,8 @@ export default () => {
|
|||||||
dashboard.use(EnsureTenantIsInitialized);
|
dashboard.use(EnsureTenantIsInitialized);
|
||||||
dashboard.use(SettingsMiddleware);
|
dashboard.use(SettingsMiddleware);
|
||||||
|
|
||||||
dashboard.use('/users', Users.router());
|
dashboard.use('/users', Container.get(Users).router());
|
||||||
|
dashboard.use('/invite', Container.get(InviteUsers).authRouter());
|
||||||
dashboard.use('/currencies', Currencies.router());
|
dashboard.use('/currencies', Currencies.router());
|
||||||
dashboard.use('/accounts', Accounts.router());
|
dashboard.use('/accounts', Accounts.router());
|
||||||
dashboard.use('/account_types', AccountTypes.router());
|
dashboard.use('/account_types', AccountTypes.router());
|
||||||
|
|||||||
@@ -39,6 +39,7 @@ export default async (req, res, next) => {
|
|||||||
req.knex = tenantKnex;
|
req.knex = tenantKnex;
|
||||||
req.organizationId = organizationId;
|
req.organizationId = organizationId;
|
||||||
req.tenant = tenant;
|
req.tenant = tenant;
|
||||||
|
req.tenantId = tenant.id;
|
||||||
req.models = models;
|
req.models = models;
|
||||||
|
|
||||||
const tenantContainer = Container.of(`tenant-${tenant.id}`);
|
const tenantContainer = Container.of(`tenant-${tenant.id}`);
|
||||||
|
|||||||
@@ -36,8 +36,6 @@ export default ({ app }) => {
|
|||||||
|
|
||||||
// catch 404 and forward to error handler
|
// catch 404 and forward to error handler
|
||||||
app.use((req, res, next) => {
|
app.use((req, res, next) => {
|
||||||
const err = new Error('Not Found');
|
return res.boom.notFound();
|
||||||
err['status'] = 404;
|
|
||||||
next(err);
|
|
||||||
})
|
})
|
||||||
};
|
};
|
||||||
@@ -2,6 +2,7 @@ import { Service, Inject, Container } from "typedi";
|
|||||||
import JWT from 'jsonwebtoken';
|
import JWT from 'jsonwebtoken';
|
||||||
import uniqid from 'uniqid';
|
import uniqid from 'uniqid';
|
||||||
import { omit } from 'lodash';
|
import { omit } from 'lodash';
|
||||||
|
import moment from "moment";
|
||||||
import {
|
import {
|
||||||
EventDispatcher,
|
EventDispatcher,
|
||||||
EventDispatcherInterface,
|
EventDispatcherInterface,
|
||||||
@@ -76,6 +77,11 @@ export default class AuthenticationService {
|
|||||||
this.logger.info('[login] generating JWT token.');
|
this.logger.info('[login] generating JWT token.');
|
||||||
const token = this.generateToken(user);
|
const token = this.generateToken(user);
|
||||||
|
|
||||||
|
this.logger.info('[login] updating user last login at.');
|
||||||
|
await SystemUser.query()
|
||||||
|
.where('id', user.id)
|
||||||
|
.patch({ last_login_at: moment().toMySqlDateTime() });
|
||||||
|
|
||||||
this.logger.info('[login] Logging success.', { user, token });
|
this.logger.info('[login] Logging success.', { user, token });
|
||||||
|
|
||||||
// Triggers `onLogin` event.
|
// Triggers `onLogin` event.
|
||||||
|
|||||||
@@ -1,11 +1,13 @@
|
|||||||
import { Service, Inject } from "typedi";
|
import { Service, Inject } from "typedi";
|
||||||
import uniqid from 'uniqid';
|
import uniqid from 'uniqid';
|
||||||
|
import moment from 'moment';
|
||||||
import {
|
import {
|
||||||
EventDispatcher,
|
EventDispatcher,
|
||||||
EventDispatcherInterface,
|
EventDispatcherInterface,
|
||||||
} from '@/decorators/eventDispatcher';
|
} from '@/decorators/eventDispatcher';
|
||||||
import { ServiceError, ServiceErrors } from "@/exceptions";
|
import { ServiceError, ServiceErrors } from "@/exceptions";
|
||||||
import { SystemUser, Invite } from "@/system/models";
|
import { SystemUser, Invite, Tenant } from "@/system/models";
|
||||||
|
import { Option } from '@/models';
|
||||||
import { hashPassword } from '@/utils';
|
import { hashPassword } from '@/utils';
|
||||||
import TenancyService from '@/services/Tenancy/TenancyService';
|
import TenancyService from '@/services/Tenancy/TenancyService';
|
||||||
import TenantsManager from "@/system/TenantsManager";
|
import TenantsManager from "@/system/TenantsManager";
|
||||||
@@ -42,28 +44,28 @@ export default class InviteUserService {
|
|||||||
*/
|
*/
|
||||||
async acceptInvite(token: string, inviteUserInput: IInviteUserInput): Promise<void> {
|
async acceptInvite(token: string, inviteUserInput: IInviteUserInput): Promise<void> {
|
||||||
const inviteToken = await this.getInviteOrThrowError(token);
|
const inviteToken = await this.getInviteOrThrowError(token);
|
||||||
await this.validateUserEmailAndPhone(inviteUserInput);
|
await this.validateUserPhoneNumber(inviteUserInput);
|
||||||
|
|
||||||
this.logger.info('[aceept_invite] trying to hash the user password.');
|
this.logger.info('[aceept_invite] trying to hash the user password.');
|
||||||
const hashedPassword = await hashPassword(inviteUserInput.password);
|
const hashedPassword = await hashPassword(inviteUserInput.password);
|
||||||
|
|
||||||
const user = SystemUser.query()
|
console.log(inviteToken);
|
||||||
.where('email', inviteUserInput.email)
|
|
||||||
|
this.logger.info('[accept_invite] trying to update user details.');
|
||||||
|
const updateUserOper = SystemUser.query()
|
||||||
|
.where('email', inviteToken.email)
|
||||||
.patch({
|
.patch({
|
||||||
...inviteUserInput,
|
...inviteUserInput,
|
||||||
active: 1,
|
active: 1,
|
||||||
email: inviteToken.email,
|
invite_accepted_at: moment().format('YYYY-MM-DD'),
|
||||||
invite_accepted_at: moment().format('YYYY/MM/DD'),
|
|
||||||
password: hashedPassword,
|
password: hashedPassword,
|
||||||
tenant_id: inviteToken.tenantId,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
|
this.logger.info('[accept_invite] trying to delete the given token.');
|
||||||
const deleteInviteTokenOper = Invite.query().where('token', inviteToken.token).delete();
|
const deleteInviteTokenOper = Invite.query().where('token', inviteToken.token).delete();
|
||||||
|
|
||||||
await Promise.all([
|
// Await all async operations.
|
||||||
insertUserOper,
|
const [user] = await Promise.all([updateUserOper, deleteInviteTokenOper]);
|
||||||
deleteInviteTokenOper,
|
|
||||||
]);
|
|
||||||
|
|
||||||
// Triggers `onUserAcceptInvite` event.
|
// Triggers `onUserAcceptInvite` event.
|
||||||
this.eventDispatcher.dispatch(events.inviteUser.acceptInvite, {
|
this.eventDispatcher.dispatch(events.inviteUser.acceptInvite, {
|
||||||
@@ -80,20 +82,27 @@ export default class InviteUserService {
|
|||||||
* @return {Promise<IInvite>}
|
* @return {Promise<IInvite>}
|
||||||
*/
|
*/
|
||||||
public async sendInvite(tenantId: number, email: string, authorizedUser: ISystemUser): Promise<IInvite> {
|
public async sendInvite(tenantId: number, email: string, authorizedUser: ISystemUser): Promise<IInvite> {
|
||||||
const { Option } = this.tenancy.models(tenantId);
|
|
||||||
await this.throwErrorIfUserEmailExists(email);
|
await this.throwErrorIfUserEmailExists(email);
|
||||||
|
|
||||||
|
this.logger.info('[send_invite] trying to store invite token.');
|
||||||
const invite = await Invite.query().insert({
|
const invite = await Invite.query().insert({
|
||||||
email,
|
email,
|
||||||
tenant_id: authorizedUser.tenantId,
|
tenant_id: authorizedUser.tenantId,
|
||||||
token: uniqid(),
|
token: uniqid(),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
this.logger.info('[send_invite] trying to store user with email and tenant.');
|
||||||
|
const user = await SystemUser.query().insert({
|
||||||
|
email,
|
||||||
|
tenant_id: authorizedUser.tenantId,
|
||||||
|
active: 1,
|
||||||
|
})
|
||||||
|
|
||||||
// Triggers `onUserSendInvite` event.
|
// Triggers `onUserSendInvite` event.
|
||||||
this.eventDispatcher.dispatch(events.inviteUser.sendInvite, {
|
this.eventDispatcher.dispatch(events.inviteUser.sendInvite, {
|
||||||
invite,
|
invite,
|
||||||
});
|
});
|
||||||
return { invite };
|
return { invite, user };
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -101,7 +110,7 @@ export default class InviteUserService {
|
|||||||
* @param {string} token - the given token string.
|
* @param {string} token - the given token string.
|
||||||
* @throws {ServiceError}
|
* @throws {ServiceError}
|
||||||
*/
|
*/
|
||||||
public async checkInvite(token: string) {
|
public async checkInvite(token: string): Promise<{ inviteToken: string, orgName: object}> {
|
||||||
const inviteToken = await this.getInviteOrThrowError(token)
|
const inviteToken = await this.getInviteOrThrowError(token)
|
||||||
|
|
||||||
// Find the tenant that associated to the given token.
|
// Find the tenant that associated to the given token.
|
||||||
@@ -109,16 +118,20 @@ export default class InviteUserService {
|
|||||||
|
|
||||||
const tenantDb = this.tenantsManager.knexInstance(tenant.organizationId);
|
const tenantDb = this.tenantsManager.knexInstance(tenant.organizationId);
|
||||||
|
|
||||||
const organizationOptions = await Option.bindKnex(tenantDb).query()
|
const orgName = await Option.bindKnex(tenantDb).query()
|
||||||
.where('key', 'organization_name');
|
.findOne('key', 'organization_name')
|
||||||
|
|
||||||
// Triggers `onUserCheckInvite` event.
|
// Triggers `onUserCheckInvite` event.
|
||||||
this.eventDispatcher.dispatch(events.inviteUser.checkInvite, {
|
this.eventDispatcher.dispatch(events.inviteUser.checkInvite, {
|
||||||
inviteToken, organizationOptions,
|
inviteToken, orgName,
|
||||||
});
|
});
|
||||||
return { inviteToken, organizationOptions };
|
return { inviteToken, orgName };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Throws error in case the given user email not exists on the storage.
|
||||||
|
* @param {string} email
|
||||||
|
*/
|
||||||
private async throwErrorIfUserEmailExists(email: string) {
|
private async throwErrorIfUserEmailExists(email: string) {
|
||||||
const foundUser = await SystemUser.query().findOne('email', email);
|
const foundUser = await SystemUser.query().findOne('email', email);
|
||||||
|
|
||||||
@@ -131,6 +144,7 @@ export default class InviteUserService {
|
|||||||
* Retrieve invite model from the given token or throw error.
|
* Retrieve invite model from the given token or throw error.
|
||||||
* @param {string} token - Then given token string.
|
* @param {string} token - Then given token string.
|
||||||
* @throws {ServiceError}
|
* @throws {ServiceError}
|
||||||
|
* @returns {Invite}
|
||||||
*/
|
*/
|
||||||
private async getInviteOrThrowError(token: string) {
|
private async getInviteOrThrowError(token: string) {
|
||||||
const inviteToken = await Invite.query().findOne('token', token);
|
const inviteToken = await Invite.query().findOne('token', token);
|
||||||
@@ -139,34 +153,22 @@ export default class InviteUserService {
|
|||||||
this.logger.info('[aceept_invite] the invite token is invalid.');
|
this.logger.info('[aceept_invite] the invite token is invalid.');
|
||||||
throw new ServiceError('invite_token_invalid');
|
throw new ServiceError('invite_token_invalid');
|
||||||
}
|
}
|
||||||
|
return inviteToken;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Validate the given user email and phone number uniquine.
|
* Validate the given user email and phone number uniquine.
|
||||||
* @param {IInviteUserInput} inviteUserInput
|
* @param {IInviteUserInput} inviteUserInput
|
||||||
*/
|
*/
|
||||||
private async validateUserEmailAndPhone(inviteUserInput: IInviteUserInput) {
|
private async validateUserPhoneNumber(inviteUserInput: IInviteUserInput) {
|
||||||
const foundUser = await SystemUser.query()
|
const foundUser = await SystemUser.query()
|
||||||
.onBuild(query => {
|
.onBuild(query => {
|
||||||
query.where('email', inviteUserInput.email);
|
query.where('phone_number', inviteUserInput.phoneNumber);
|
||||||
|
query.first();
|
||||||
if (inviteUserInput.phoneNumber) {
|
|
||||||
query.where('phone_number', inviteUserInput.phoneNumber);
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
const serviceErrors: ServiceError[] = [];
|
|
||||||
|
|
||||||
if (foundUser && foundUser.email === inviteUserInput.email) {
|
if (foundUser) {
|
||||||
this.logger.info('[send_user_invite] the given email exists.');
|
throw new ServiceError('phone_number_exists');
|
||||||
serviceErrors.push(new ServiceError('email_exists'));
|
|
||||||
}
|
|
||||||
if (foundUser && foundUser.phoneNumber === inviteUserInput.phoneNumber) {
|
|
||||||
this.logger.info('[send_user_invite] the given phone number exists.');
|
|
||||||
serviceErrors.push(new ServiceError('phone_number_exists'));
|
|
||||||
}
|
|
||||||
if (serviceErrors.length > 0) {
|
|
||||||
throw new ServiceErrors(serviceErrors);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
147
server/src/services/Users/UsersService.ts
Normal file
147
server/src/services/Users/UsersService.ts
Normal file
@@ -0,0 +1,147 @@
|
|||||||
|
import { Inject, Service } from "typedi";
|
||||||
|
import TenancyService from '@/services/Tenancy/TenancyService';
|
||||||
|
import { SystemUser } from "@/system/models";
|
||||||
|
import { ServiceError, ServiceErrors } from "@/exceptions";
|
||||||
|
import { ISystemUser, ISystemUserDTO } from "@/interfaces";
|
||||||
|
import { ISystemUser } from "src/interfaces";
|
||||||
|
|
||||||
|
@Service()
|
||||||
|
export default class UsersService {
|
||||||
|
@Inject()
|
||||||
|
tenancy: TenancyService;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a new user.
|
||||||
|
* @param {number} tenantId
|
||||||
|
* @param {number} userId
|
||||||
|
* @param {IUserDTO} userDTO
|
||||||
|
* @return {Promise<ISystemUser>}
|
||||||
|
*/
|
||||||
|
async editUser(tenantId: number, userId: number, userDTO: ISystemUserDTO): Promise<ISystemUser> {
|
||||||
|
const foundUsers = await SystemUser.query()
|
||||||
|
.whereNot('id', userId)
|
||||||
|
.andWhere((q) => {
|
||||||
|
q.where('email', userDTO.email);
|
||||||
|
q.orWhere('phone_number', userDTO.phoneNumber);
|
||||||
|
})
|
||||||
|
.where('tenant_id', tenantId);
|
||||||
|
|
||||||
|
const sameUserEmail = foundUsers
|
||||||
|
.some((u: ISystemUser) => u.email === userDTO.email);
|
||||||
|
|
||||||
|
const samePhoneNumber = foundUsers
|
||||||
|
.some((u: ISystemUser) => u.phoneNumber === userDTO.phone_number);
|
||||||
|
|
||||||
|
const serviceErrors: ServiceError[] = [];
|
||||||
|
|
||||||
|
if (sameUserEmail) {
|
||||||
|
serviceErrors.push(new ServiceError('email_already_exists'));
|
||||||
|
}
|
||||||
|
if (samePhoneNumber) {
|
||||||
|
serviceErrors.push(new ServiceError('phone_number_already_exist'));
|
||||||
|
}
|
||||||
|
if (serviceErrors.length > 0) {
|
||||||
|
throw new ServiceErrors(serviceErrors);
|
||||||
|
}
|
||||||
|
const updateSystemUser = await SystemUser.query()
|
||||||
|
.where('id', userId)
|
||||||
|
.update({
|
||||||
|
...userDTO,
|
||||||
|
});
|
||||||
|
return updateSystemUser;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Validate user existance throw error in case user was not found.,
|
||||||
|
* @param {number} tenantId -
|
||||||
|
* @param {number} userId -
|
||||||
|
* @returns {ISystemUser}
|
||||||
|
*/
|
||||||
|
async getUserOrThrowError(tenantId: number, userId: number): void {
|
||||||
|
const user = await SystemUser.query().findOne({
|
||||||
|
id: userId, tenant_id: tenantId,
|
||||||
|
});
|
||||||
|
if (!user) {
|
||||||
|
throw new ServiceError('user_not_found');
|
||||||
|
}
|
||||||
|
return user;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Deletes the given user id.
|
||||||
|
* @param {number} tenantId
|
||||||
|
* @param {number} userId
|
||||||
|
*/
|
||||||
|
async deleteUser(tenantId: number, userId: number): Promise<void> {
|
||||||
|
await this.getUserOrThrowError(tenantId, userId);
|
||||||
|
await SystemUser.query().where('id', userId).delete();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Activate the given user id.
|
||||||
|
* @param {number} tenantId
|
||||||
|
* @param {number} userId
|
||||||
|
*/
|
||||||
|
async activateUser(tenantId: number, userId: number): Promise<void> {
|
||||||
|
const user = await this.getUserOrThrowError(tenantId, userId);
|
||||||
|
this.throwErrorIfUserActive(user);
|
||||||
|
|
||||||
|
await SystemUser.query().findById(userId).update({ active: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Inactivate the given user id.
|
||||||
|
* @param {number} tenantId
|
||||||
|
* @param {number} userId
|
||||||
|
* @return {Promise<void>}
|
||||||
|
*/
|
||||||
|
async inactivateUser(tenantId: number, userId: number): Promise<void> {
|
||||||
|
const user = await this.getUserOrThrowError(tenantId, userId);
|
||||||
|
this.throwErrorIfUserInactive(user);
|
||||||
|
|
||||||
|
await SystemUser.query().findById(userId).update({ active: false });
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieve users list based on the given filter.
|
||||||
|
* @param {number} tenantId
|
||||||
|
* @param {object} filter
|
||||||
|
*/
|
||||||
|
async getList(tenantId: number) {
|
||||||
|
const users = await SystemUser.query()
|
||||||
|
.where('tenant_id', tenantId);
|
||||||
|
|
||||||
|
return users;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieve the given user details.
|
||||||
|
* @param {number} tenantId - Tenant id.
|
||||||
|
* @param {number} userId - User id.
|
||||||
|
*/
|
||||||
|
async getUser(tenantId: number, userId: number) {
|
||||||
|
return this.getUserOrThrowError(tenantId, userId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Throws service error in case the user was already active.
|
||||||
|
* @param {ISystemUser} user
|
||||||
|
* @throws {ServiceError}
|
||||||
|
*/
|
||||||
|
throwErrorIfUserActive(user: ISystemUser) {
|
||||||
|
if (user.active) {
|
||||||
|
throw new ServiceError('user_already_active');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Throws service error in case the user was already inactive.
|
||||||
|
* @param {ISystemUser} user
|
||||||
|
* @throws {ServiceError}
|
||||||
|
*/
|
||||||
|
throwErrorIfUserInactive(user: ISystemUser) {
|
||||||
|
if (!user.active) {
|
||||||
|
throw new ServiceError('user_already_inactive');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -13,6 +13,7 @@ exports.up = function (knex) {
|
|||||||
|
|
||||||
table.integer('tenant_id').unsigned();
|
table.integer('tenant_id').unsigned();
|
||||||
|
|
||||||
|
table.date('invite_accepted_at');
|
||||||
table.date('last_login_at');
|
table.date('last_login_at');
|
||||||
table.timestamps();
|
table.timestamps();
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import Voucher from './Subscriptions/Voucher';
|
|||||||
import Tenant from './Tenant';
|
import Tenant from './Tenant';
|
||||||
import SystemUser from './SystemUser';
|
import SystemUser from './SystemUser';
|
||||||
import PasswordReset from './PasswordReset';
|
import PasswordReset from './PasswordReset';
|
||||||
|
import Invite from './Invite';
|
||||||
|
|
||||||
export {
|
export {
|
||||||
Plan,
|
Plan,
|
||||||
@@ -15,4 +16,5 @@ export {
|
|||||||
Tenant,
|
Tenant,
|
||||||
SystemUser,
|
SystemUser,
|
||||||
PasswordReset,
|
PasswordReset,
|
||||||
|
Invite,
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user