feat: fix issues in invite user.

feat: fix update last login at after login.
This commit is contained in:
Ahmed Bouhuolia
2020-09-05 22:18:53 +02:00
parent d35b124178
commit 750377ba86
16 changed files with 535 additions and 336 deletions

View File

@@ -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";
export default class BaseController {
@@ -11,4 +12,16 @@ export default class BaseController {
});
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();
}
}

View File

@@ -4,50 +4,61 @@ import {
check,
body,
param,
matchedData,
} from 'express-validator';
import asyncMiddleware from '@/http/middleware/asyncMiddleware';
import jwtAuth from '@/http/middleware/jwtAuth';
import TenancyMiddleware from '@/http/middleware/TenancyMiddleware';
import InviteUserService from '@/services/InviteUsers';
import { ServiceErrors, ServiceError } from '@/exceptions';
import BaseController from './BaseController';
@Service()
export default class InviteUsersController {
export default class InviteUsersController extends BaseController {
@Inject()
inviteUsersService: InviteUserService;
/**
* Router constructor.
* Routes that require authentication.
*/
router() {
authRouter() {
const router = Router();
router.use('/send', jwtAuth);
router.use('/send', TenancyMiddleware);
router.post('/send', [
body('email').exists().trim().escape(),
],
asyncMiddleware(this.sendInvite),
body('email').exists().trim().escape(),
],
asyncMiddleware(this.sendInvite.bind(this)),
);
return router;
}
/**
* Routes that non-required authentication.
*/
nonAuthRouter() {
const router = Router();
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('last_name').exists().trim().escape(),
check('phone_number').exists().trim().escape(),
check('password').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 {
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) {
console.log(error);
if (error instanceof ServiceError) {
@@ -84,7 +100,7 @@ export default class InviteUsersController {
* @param {NextFunction} next -
*/
async accept(req: Request, res: Response, next: Function) {
const inviteUserInput: IInviteUserInput = matchedData(req, {
const inviteUserInput: IInviteUserInput = this.matchedBodyData(req, {
locations: ['body'],
includeOptionals: true,
});
@@ -92,20 +108,24 @@ export default class InviteUsersController {
try {
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) {
if (error instanceof ServiceErrors) {
const errorReasons = [];
if (error instanceof ServiceError) {
if (error.hasType('email_exists')) {
errorReasons.push({ type: 'EMAIL.EXISTS' });
if (error.errorType === 'phone_number_exists') {
return res.status(400).send({
errors: [{ type: 'PHONE_NUMBER.EXISTS' }],
});
}
if (error.hasType('phone_number_exists')) {
errorReasons.push({ type: 'PHONE_NUMBER.EXISTS' });
}
if (errorReasons.length > 0) {
return res.status(400).send({ errors: errorReasons });
if (error.errorType === 'invite_token_invalid') {
return res.status(400).send({
errors: [{ type: 'INVITE.TOKEN.INVALID' }],
});
}
}
next(error);
@@ -122,9 +142,13 @@ export default class InviteUsersController {
const { token } = req.params;
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) {
if (error instanceof ServiceError) {

View File

@@ -44,7 +44,9 @@ export default class OrganizationController {
await this.organizationService.build(buildOTD.organizationId);
return res.status(200).send({
type: 'ORGANIZATION.DATABASE.INITIALIZED',
type: 'success',
code: 'ORGANIZATION.DATABASE.INITIALIZED',
message: 'The organization database has been initialized.'
});
} catch (error) {
if (error instanceof ServiceError) {

View File

@@ -1,6 +1,4 @@
import 'reflect-metadata';
import { Router, Request, Response } from 'express';
import i18n from 'i18n';
export default class Ping {
/**

View File

@@ -101,8 +101,9 @@ export default class PaymentViaVoucherController extends PaymentMethodController
.subscriptionViaVoucher(tenant.id, planSlug, voucherCode);
return res.status(200).send({
type: 'PAYMENT.SUCCESSFULLY.MADE',
code: 100,
type: 'success',
code: 'PAYMENT.SUCCESSFULLY.MADE',
message: 'Payment via voucher has been made successfully.',
});
} catch (exception) {
const errorReasons = [];

View File

@@ -165,6 +165,7 @@ export default class VouchersController extends BaseController {
);
return res.status(200).send({
code: 100,
type: 'VOUCHERES.GENERATED.SUCCESSFULLY',
message: 'The vouchers have been generated successfully.'
});
} catch (error) {

View File

@@ -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 });
},
},
};

View 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 }],
});
}
}
}
}
};

View File

@@ -43,7 +43,7 @@ export default () => {
app.use(I18nMiddleware);
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('/vouchers', Container.get(VouchersController).router());
app.use('/subscription', Container.get(Subscription).router());
@@ -59,7 +59,8 @@ export default () => {
dashboard.use(EnsureTenantIsInitialized);
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('/accounts', Accounts.router());
dashboard.use('/account_types', AccountTypes.router());

View File

@@ -39,6 +39,7 @@ export default async (req, res, next) => {
req.knex = tenantKnex;
req.organizationId = organizationId;
req.tenant = tenant;
req.tenantId = tenant.id;
req.models = models;
const tenantContainer = Container.of(`tenant-${tenant.id}`);

View File

@@ -36,8 +36,6 @@ export default ({ app }) => {
// catch 404 and forward to error handler
app.use((req, res, next) => {
const err = new Error('Not Found');
err['status'] = 404;
next(err);
return res.boom.notFound();
})
};

View File

@@ -2,6 +2,7 @@ import { Service, Inject, Container } from "typedi";
import JWT from 'jsonwebtoken';
import uniqid from 'uniqid';
import { omit } from 'lodash';
import moment from "moment";
import {
EventDispatcher,
EventDispatcherInterface,
@@ -76,6 +77,11 @@ export default class AuthenticationService {
this.logger.info('[login] generating JWT token.');
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 });
// Triggers `onLogin` event.

View File

@@ -1,11 +1,13 @@
import { Service, Inject } from "typedi";
import uniqid from 'uniqid';
import moment from 'moment';
import {
EventDispatcher,
EventDispatcherInterface,
} from '@/decorators/eventDispatcher';
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 TenancyService from '@/services/Tenancy/TenancyService';
import TenantsManager from "@/system/TenantsManager";
@@ -42,28 +44,28 @@ export default class InviteUserService {
*/
async acceptInvite(token: string, inviteUserInput: IInviteUserInput): Promise<void> {
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.');
const hashedPassword = await hashPassword(inviteUserInput.password);
const user = SystemUser.query()
.where('email', inviteUserInput.email)
console.log(inviteToken);
this.logger.info('[accept_invite] trying to update user details.');
const updateUserOper = SystemUser.query()
.where('email', inviteToken.email)
.patch({
...inviteUserInput,
active: 1,
email: inviteToken.email,
invite_accepted_at: moment().format('YYYY/MM/DD'),
invite_accepted_at: moment().format('YYYY-MM-DD'),
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();
await Promise.all([
insertUserOper,
deleteInviteTokenOper,
]);
// Await all async operations.
const [user] = await Promise.all([updateUserOper, deleteInviteTokenOper]);
// Triggers `onUserAcceptInvite` event.
this.eventDispatcher.dispatch(events.inviteUser.acceptInvite, {
@@ -80,20 +82,27 @@ export default class InviteUserService {
* @return {Promise<IInvite>}
*/
public async sendInvite(tenantId: number, email: string, authorizedUser: ISystemUser): Promise<IInvite> {
const { Option } = this.tenancy.models(tenantId);
await this.throwErrorIfUserEmailExists(email);
this.logger.info('[send_invite] trying to store invite token.');
const invite = await Invite.query().insert({
email,
tenant_id: authorizedUser.tenantId,
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.
this.eventDispatcher.dispatch(events.inviteUser.sendInvite, {
invite,
});
return { invite };
return { invite, user };
}
/**
@@ -101,7 +110,7 @@ export default class InviteUserService {
* @param {string} token - the given token string.
* @throws {ServiceError}
*/
public async checkInvite(token: string) {
public async checkInvite(token: string): Promise<{ inviteToken: string, orgName: object}> {
const inviteToken = await this.getInviteOrThrowError(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 organizationOptions = await Option.bindKnex(tenantDb).query()
.where('key', 'organization_name');
const orgName = await Option.bindKnex(tenantDb).query()
.findOne('key', 'organization_name')
// Triggers `onUserCheckInvite` event.
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) {
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.
* @param {string} token - Then given token string.
* @throws {ServiceError}
* @returns {Invite}
*/
private async getInviteOrThrowError(token: string) {
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.');
throw new ServiceError('invite_token_invalid');
}
return inviteToken;
}
/**
* Validate the given user email and phone number uniquine.
* @param {IInviteUserInput} inviteUserInput
*/
private async validateUserEmailAndPhone(inviteUserInput: IInviteUserInput) {
private async validateUserPhoneNumber(inviteUserInput: IInviteUserInput) {
const foundUser = await SystemUser.query()
.onBuild(query => {
query.where('email', inviteUserInput.email);
if (inviteUserInput.phoneNumber) {
query.where('phone_number', inviteUserInput.phoneNumber);
}
});
const serviceErrors: ServiceError[] = [];
if (foundUser && foundUser.email === inviteUserInput.email) {
this.logger.info('[send_user_invite] the given email 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);
query.where('phone_number', inviteUserInput.phoneNumber);
query.first();
});
if (foundUser) {
throw new ServiceError('phone_number_exists');
}
}
}

View 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');
}
}
}

View File

@@ -13,6 +13,7 @@ exports.up = function (knex) {
table.integer('tenant_id').unsigned();
table.date('invite_accepted_at');
table.date('last_login_at');
table.timestamps();
}).then(() => {

View File

@@ -6,6 +6,7 @@ import Voucher from './Subscriptions/Voucher';
import Tenant from './Tenant';
import SystemUser from './SystemUser';
import PasswordReset from './PasswordReset';
import Invite from './Invite';
export {
Plan,
@@ -15,4 +16,5 @@ export {
Tenant,
SystemUser,
PasswordReset,
Invite,
}