mirror of
https://github.com/bigcapitalhq/bigcapital.git
synced 2026-02-16 21:00:31 +00:00
fix: issue in mail sender.
This commit is contained in:
@@ -1,9 +1,8 @@
|
||||
import fs from 'fs';
|
||||
import { Service, Container } from "typedi";
|
||||
import Mustache from 'mustache';
|
||||
import path from 'path';
|
||||
|
||||
import { Service } from "typedi";
|
||||
import { ISystemUser } from 'interfaces';
|
||||
import config from 'config';
|
||||
import Mail from "lib/Mail";
|
||||
|
||||
@Service()
|
||||
export default class AuthenticationMailMesssages {
|
||||
@@ -13,31 +12,23 @@ export default class AuthenticationMailMesssages {
|
||||
* @param {string} organizationName -
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
sendWelcomeMessage(user: ISystemUser, organizationName: string): Promise<void> {
|
||||
const Mail = Container.get('mail');
|
||||
|
||||
const filePath = path.join(global.__root, 'views/mail/Welcome.html');
|
||||
const template = fs.readFileSync(filePath, 'utf8');
|
||||
const rendered = Mustache.render(template, {
|
||||
email: user.email,
|
||||
firstName: user.firstName,
|
||||
organizationName,
|
||||
});
|
||||
const mailOptions = {
|
||||
to: user.email,
|
||||
from: `${process.env.MAIL_FROM_NAME} ${process.env.MAIL_FROM_ADDRESS}`,
|
||||
subject: 'Welcome to Bigcapital',
|
||||
html: rendered,
|
||||
};
|
||||
return new Promise((resolve, reject) => {
|
||||
Mail.sendMail(mailOptions, (error) => {
|
||||
if (error) {
|
||||
resolve(error);
|
||||
return;
|
||||
}
|
||||
reject();
|
||||
async sendWelcomeMessage(
|
||||
user: ISystemUser,
|
||||
organizationId: string
|
||||
): Promise<void> {
|
||||
|
||||
const mail = new Mail()
|
||||
.setView('mail/Welcome.html')
|
||||
.setSubject('Welcome to Bigcapital')
|
||||
.setTo(user.email)
|
||||
.setData({
|
||||
firstName: user.firstName,
|
||||
organizationId,
|
||||
successPhoneNumber: config.customerSuccess.phoneNumber,
|
||||
successEmail: config.customerSuccess.email,
|
||||
});
|
||||
});
|
||||
|
||||
await mail.send();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -46,31 +37,22 @@ export default class AuthenticationMailMesssages {
|
||||
* @param {string} token - Reset password token.
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
sendResetPasswordMessage(user: ISystemUser, token: string): Promise<void> {
|
||||
const Mail = Container.get('mail');
|
||||
async sendResetPasswordMessage(
|
||||
user: ISystemUser,
|
||||
token: string
|
||||
): Promise<void> {
|
||||
|
||||
const filePath = path.join(global.__root, 'views/mail/ResetPassword.html');
|
||||
const template = fs.readFileSync(filePath, 'utf8');
|
||||
const rendered = Mustache.render(template, {
|
||||
resetPasswordUrl: `${config.baseURL}/reset/${token}`,
|
||||
first_name: user.firstName,
|
||||
last_name: user.lastName,
|
||||
contact_us_email: config.contactUsMail,
|
||||
});
|
||||
const mailOptions = {
|
||||
to: user.email,
|
||||
from: `${process.env.MAIL_FROM_NAME} ${process.env.MAIL_FROM_ADDRESS}`,
|
||||
subject: 'Bigcapital - Password Reset',
|
||||
html: rendered,
|
||||
};
|
||||
return new Promise((resolve, reject) => {
|
||||
Mail.sendMail(mailOptions, (error) => {
|
||||
if (error) {
|
||||
reject(error);
|
||||
return;
|
||||
}
|
||||
resolve();
|
||||
const mail = new Mail()
|
||||
.setSubject('Bigcapital - Password Reset')
|
||||
.setView('mail/ResetPassword.html')
|
||||
.setTo(user.email)
|
||||
.setData({
|
||||
resetPasswordUrl: `${config.baseURL}/reset/${token}`,
|
||||
first_name: user.firstName,
|
||||
last_name: user.lastName,
|
||||
contact_us_email: config.contactUsMail,
|
||||
});
|
||||
});
|
||||
|
||||
await mail.send();
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Service, Inject } from "typedi";
|
||||
import { ISystemUser, ITenant } from "interfaces";
|
||||
import { Service, Inject } from 'typedi';
|
||||
import { ISystemUser, ITenant } from 'interfaces';
|
||||
|
||||
@Service()
|
||||
export default class AuthenticationSMSMessages {
|
||||
@@ -8,12 +8,12 @@ export default class AuthenticationSMSMessages {
|
||||
|
||||
/**
|
||||
* Sends welcome sms message.
|
||||
* @param {ITenant} tenant
|
||||
* @param {ISystemUser} user
|
||||
* @param {ITenant} tenant
|
||||
* @param {ISystemUser} user
|
||||
*/
|
||||
sendWelcomeMessage(tenant: ITenant, user: ISystemUser) {
|
||||
const message: string = `Hi ${user.firstName}, Welcome to Bigcapital, You've joined the new workspace, if you need any help please don't hesitate to contact us.`
|
||||
const message: string = `Hi ${user.firstName}, Welcome to Bigcapital, You've joined the new workspace, if you need any help please don't hesitate to contact us.`;
|
||||
|
||||
return this.smsClient.sendMessage(user.phoneNumber, message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { Service, Inject, Container } from "typedi";
|
||||
import { Service, Inject, Container } from 'typedi';
|
||||
import JWT from 'jsonwebtoken';
|
||||
import uniqid from 'uniqid';
|
||||
import { omit } from 'lodash';
|
||||
import moment from "moment";
|
||||
import moment from 'moment';
|
||||
import {
|
||||
EventDispatcher,
|
||||
EventDispatcherInterface,
|
||||
@@ -46,7 +46,7 @@ export default class AuthenticationService implements IAuthenticationService {
|
||||
/**
|
||||
* Signin and generates JWT token.
|
||||
* @throws {ServiceError}
|
||||
* @param {string} emailOrPhone - Email or phone number.
|
||||
* @param {string} emailOrPhone - Email or phone number.
|
||||
* @param {string} password - Password.
|
||||
* @return {Promise<{user: IUser, token: string}>}
|
||||
*/
|
||||
@@ -54,11 +54,14 @@ export default class AuthenticationService implements IAuthenticationService {
|
||||
emailOrPhone: string,
|
||||
password: string
|
||||
): Promise<{
|
||||
user: ISystemUser,
|
||||
token: string,
|
||||
tenant: ITenant
|
||||
user: ISystemUser;
|
||||
token: string;
|
||||
tenant: ITenant;
|
||||
}> {
|
||||
this.logger.info('[login] Someone trying to login.', { emailOrPhone, password });
|
||||
this.logger.info('[login] Someone trying to login.', {
|
||||
emailOrPhone,
|
||||
password,
|
||||
});
|
||||
|
||||
const { systemUserRepository } = this.sysRepositories;
|
||||
const loginThrottler = Container.get('rateLimiter.login');
|
||||
@@ -72,7 +75,10 @@ export default class AuthenticationService implements IAuthenticationService {
|
||||
throw new ServiceError('invalid_details');
|
||||
}
|
||||
|
||||
this.logger.info('[login] check password validation.', { emailOrPhone, password });
|
||||
this.logger.info('[login] check password validation.', {
|
||||
emailOrPhone,
|
||||
password,
|
||||
});
|
||||
if (!user.verifyPassword(password)) {
|
||||
await loginThrottler.hit(emailOrPhone);
|
||||
|
||||
@@ -87,14 +93,18 @@ export default class AuthenticationService implements IAuthenticationService {
|
||||
this.logger.info('[login] generating JWT token.', { userId: user.id });
|
||||
const token = this.generateToken(user);
|
||||
|
||||
this.logger.info('[login] updating user last login at.', { userId: user.id });
|
||||
this.logger.info('[login] updating user last login at.', {
|
||||
userId: user.id,
|
||||
});
|
||||
await systemUserRepository.patchLastLoginAt(user.id);
|
||||
|
||||
this.logger.info('[login] Logging success.', { user, token });
|
||||
|
||||
// Triggers `onLogin` event.
|
||||
this.eventDispatcher.dispatch(events.auth.login, {
|
||||
emailOrPhone, password, user,
|
||||
emailOrPhone,
|
||||
password,
|
||||
user,
|
||||
});
|
||||
const tenant = await user.$relatedQuery('tenant');
|
||||
|
||||
@@ -111,8 +121,12 @@ export default class AuthenticationService implements IAuthenticationService {
|
||||
*/
|
||||
private async validateEmailAndPhoneUniqiness(registerDTO: IRegisterDTO) {
|
||||
const { systemUserRepository } = this.sysRepositories;
|
||||
const isEmailExists = await systemUserRepository.getByEmail(registerDTO.email);
|
||||
const isPhoneExists = await systemUserRepository.getByPhoneNumber(registerDTO.phoneNumber);
|
||||
const isEmailExists = await systemUserRepository.getByEmail(
|
||||
registerDTO.email
|
||||
);
|
||||
const isPhoneExists = await systemUserRepository.getByPhoneNumber(
|
||||
registerDTO.phoneNumber
|
||||
);
|
||||
|
||||
const errorReasons: ServiceError[] = [];
|
||||
|
||||
@@ -132,7 +146,7 @@ export default class AuthenticationService implements IAuthenticationService {
|
||||
/**
|
||||
* Registers a new tenant with user from user input.
|
||||
* @throws {ServiceErrors}
|
||||
* @param {IUserDTO} user
|
||||
* @param {IUserDTO} user
|
||||
*/
|
||||
public async register(registerDTO: IRegisterDTO): Promise<ISystemUser> {
|
||||
this.logger.info('[register] Someone trying to register.');
|
||||
@@ -141,7 +155,7 @@ export default class AuthenticationService implements IAuthenticationService {
|
||||
this.logger.info('[register] Creating a new tenant organization.');
|
||||
const tenant = await this.newTenantOrganization();
|
||||
|
||||
this.logger.info('[register] Trying hashing the password.')
|
||||
this.logger.info('[register] Trying hashing the password.');
|
||||
const hashedPassword = await hashPassword(registerDTO.password);
|
||||
|
||||
const { systemUserRepository } = this.sysRepositories;
|
||||
@@ -153,7 +167,9 @@ export default class AuthenticationService implements IAuthenticationService {
|
||||
});
|
||||
// Triggers `onRegister` event.
|
||||
this.eventDispatcher.dispatch(events.auth.register, {
|
||||
registerDTO, user: registeredUser
|
||||
registerDTO,
|
||||
tenant,
|
||||
user: registeredUser,
|
||||
});
|
||||
return registeredUser;
|
||||
}
|
||||
@@ -170,14 +186,14 @@ export default class AuthenticationService implements IAuthenticationService {
|
||||
/**
|
||||
* Validate the given email existance on the storage.
|
||||
* @throws {ServiceError}
|
||||
* @param {string} email - email address.
|
||||
* @param {string} email - email address.
|
||||
*/
|
||||
private async validateEmailExistance(email: string): Promise<ISystemUser> {
|
||||
const { systemUserRepository } = this.sysRepositories;
|
||||
const userByEmail = await systemUserRepository.getByEmail(email);
|
||||
|
||||
if (!userByEmail) {
|
||||
this.logger.info('[send_reset_password] The given email not found.');
|
||||
this.logger.info('[send_reset_password] The given email not found.');
|
||||
throw new ServiceError('email_not_found');
|
||||
}
|
||||
return userByEmail;
|
||||
@@ -185,7 +201,7 @@ export default class AuthenticationService implements IAuthenticationService {
|
||||
|
||||
/**
|
||||
* Generates and retrieve password reset token for the given user email.
|
||||
* @param {string} email
|
||||
* @param {string} email
|
||||
* @return {<Promise<IPasswordReset>}
|
||||
*/
|
||||
public async sendResetPassword(email: string): Promise<IPasswordReset> {
|
||||
@@ -193,7 +209,9 @@ export default class AuthenticationService implements IAuthenticationService {
|
||||
const user = await this.validateEmailExistance(email);
|
||||
|
||||
// Delete all stored tokens of reset password that associate to the give email.
|
||||
this.logger.info('[send_reset_password] trying to delete all tokens by email.');
|
||||
this.logger.info(
|
||||
'[send_reset_password] trying to delete all tokens by email.'
|
||||
);
|
||||
this.deletePasswordResetToken(email);
|
||||
|
||||
const token: string = uniqid();
|
||||
@@ -202,8 +220,10 @@ export default class AuthenticationService implements IAuthenticationService {
|
||||
const passwordReset = await PasswordReset.query().insert({ email, token });
|
||||
|
||||
// Triggers `onSendResetPassword` event.
|
||||
this.eventDispatcher.dispatch(events.auth.sendResetPassword, { user, token });
|
||||
|
||||
this.eventDispatcher.dispatch(events.auth.sendResetPassword, {
|
||||
user,
|
||||
token,
|
||||
});
|
||||
return passwordReset;
|
||||
}
|
||||
|
||||
@@ -215,14 +235,20 @@ export default class AuthenticationService implements IAuthenticationService {
|
||||
*/
|
||||
public async resetPassword(token: string, password: string): Promise<void> {
|
||||
const { systemUserRepository } = this.sysRepositories;
|
||||
const tokenModel: IPasswordReset = await PasswordReset.query().findOne('token', token);
|
||||
const tokenModel: IPasswordReset = await PasswordReset.query().findOne(
|
||||
'token',
|
||||
token
|
||||
);
|
||||
|
||||
if (!tokenModel) {
|
||||
this.logger.info('[reset_password] token invalid.');
|
||||
throw new ServiceError('token_invalid');
|
||||
}
|
||||
// Different between tokne creation datetime and current time.
|
||||
if (moment().diff(tokenModel.createdAt, 'seconds') > config.resetPasswordSeconds) {
|
||||
if (
|
||||
moment().diff(tokenModel.createdAt, 'seconds') >
|
||||
config.resetPasswordSeconds
|
||||
) {
|
||||
this.logger.info('[reset_password] token expired.');
|
||||
|
||||
// Deletes the expired token by expired token email.
|
||||
@@ -235,7 +261,7 @@ export default class AuthenticationService implements IAuthenticationService {
|
||||
throw new ServiceError('user_not_found');
|
||||
}
|
||||
const hashedPassword = await hashPassword(password);
|
||||
|
||||
|
||||
this.logger.info('[reset_password] saving a new hashed password.');
|
||||
await systemUserRepository.edit(user.id, { password: hashedPassword });
|
||||
|
||||
@@ -243,13 +269,17 @@ export default class AuthenticationService implements IAuthenticationService {
|
||||
await this.deletePasswordResetToken(tokenModel.email);
|
||||
|
||||
// Triggers `onResetPassword` event.
|
||||
this.eventDispatcher.dispatch(events.auth.resetPassword, { user, token, password });
|
||||
this.eventDispatcher.dispatch(events.auth.resetPassword, {
|
||||
user,
|
||||
token,
|
||||
password,
|
||||
});
|
||||
this.logger.info('[reset_password] reset password success.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes the password reset token by the given email.
|
||||
* @param {string} email
|
||||
* @param {string} email
|
||||
* @returns {Promise}
|
||||
*/
|
||||
private async deletePasswordResetToken(email: string) {
|
||||
@@ -259,7 +289,7 @@ export default class AuthenticationService implements IAuthenticationService {
|
||||
|
||||
/**
|
||||
* Generates JWT token for the given user.
|
||||
* @param {ISystemUser} user
|
||||
* @param {ISystemUser} user
|
||||
* @return {string} token
|
||||
*/
|
||||
generateToken(user: ISystemUser): string {
|
||||
@@ -273,7 +303,7 @@ export default class AuthenticationService implements IAuthenticationService {
|
||||
id: user.id, // We are gonna use this in the middleware 'isAuth'
|
||||
exp: exp.getTime() / 1000,
|
||||
},
|
||||
config.jwtSecret,
|
||||
config.jwtSecret
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,31 +1,29 @@
|
||||
import { IInviteUserInput, ISystemUser } from "interfaces";
|
||||
import Mail from "lib/Mail";
|
||||
import { Service } from "typedi";
|
||||
|
||||
@Service()
|
||||
export default class InviteUsersMailMessages {
|
||||
|
||||
sendInviteMail() {
|
||||
const filePath = path.join(global.__root, 'views/mail/UserInvite.html');
|
||||
const template = fs.readFileSync(filePath, 'utf8');
|
||||
|
||||
const rendered = Mustache.render(template, {
|
||||
acceptUrl: `${req.protocol}://${req.hostname}/invite/accept/${invite.token}`,
|
||||
fullName: `${user.firstName} ${user.lastName}`,
|
||||
firstName: user.firstName,
|
||||
lastName: user.lastName,
|
||||
email: user.email,
|
||||
organizationName: organizationOptions.getMeta('organization_name'),
|
||||
});
|
||||
const mailOptions = {
|
||||
to: user.email,
|
||||
from: `${process.env.MAIL_FROM_NAME} ${process.env.MAIL_FROM_ADDRESS}`,
|
||||
subject: `${user.fullName} has invited you to join a Bigcapital`,
|
||||
html: rendered,
|
||||
};
|
||||
mail.sendMail(mailOptions, (error) => {
|
||||
if (error) {
|
||||
Logger.log('error', 'Failed send user invite mail', { error, form });
|
||||
}
|
||||
Logger.log('info', 'User has been sent invite user email successfuly.', { form });
|
||||
});
|
||||
/**
|
||||
* Sends invite mail to the given email.
|
||||
* @param user
|
||||
* @param invite
|
||||
*/
|
||||
async sendInviteMail(user: ISystemUser, invite) {
|
||||
const mail = new Mail()
|
||||
.setSubject(`${user.fullName} has invited you to join a Bigcapital`)
|
||||
.setView('mail/UserInvite.html')
|
||||
.setData({
|
||||
acceptUrl: `${req.protocol}://${req.hostname}/invite/accept/${invite.token}`,
|
||||
fullName: `${user.firstName} ${user.lastName}`,
|
||||
firstName: user.firstName,
|
||||
lastName: user.lastName,
|
||||
email: user.email,
|
||||
organizationName: organizationOptions.getMeta('organization_name'),
|
||||
});
|
||||
|
||||
await mail.send();
|
||||
Logger.log('info', 'User has been sent invite user email successfuly.');
|
||||
}
|
||||
}
|
||||
@@ -1,21 +1,18 @@
|
||||
import { Service, Inject } from "typedi";
|
||||
import { Service, Inject } from 'typedi';
|
||||
import uniqid from 'uniqid';
|
||||
import moment from 'moment';
|
||||
import {
|
||||
EventDispatcher,
|
||||
EventDispatcherInterface,
|
||||
} from 'decorators/eventDispatcher';
|
||||
import { ServiceError } from "exceptions";
|
||||
import { Invite, Tenant } from "system/models";
|
||||
import { ServiceError } from 'exceptions';
|
||||
import { Invite, Tenant } from 'system/models';
|
||||
import { Option } from 'models';
|
||||
import { hashPassword } from 'utils';
|
||||
import TenancyService from 'services/Tenancy/TenancyService';
|
||||
import InviteUsersMailMessages from "services/InviteUsers/InviteUsersMailMessages";
|
||||
import InviteUsersMailMessages from 'services/InviteUsers/InviteUsersMailMessages';
|
||||
import events from 'subscribers/events';
|
||||
import {
|
||||
ISystemUser,
|
||||
IInviteUserInput,
|
||||
} from 'interfaces';
|
||||
import { ISystemUser, IInviteUserInput } from 'interfaces';
|
||||
|
||||
@Service()
|
||||
export default class InviteUserService {
|
||||
@@ -36,12 +33,15 @@ export default class InviteUserService {
|
||||
|
||||
/**
|
||||
* Accept the received invite.
|
||||
* @param {string} token
|
||||
* @param {IInviteUserInput} inviteUserInput
|
||||
* @param {string} token
|
||||
* @param {IInviteUserInput} inviteUserInput
|
||||
* @throws {ServiceErrors}
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async acceptInvite(token: string, inviteUserInput: IInviteUserInput): Promise<void> {
|
||||
async acceptInvite(
|
||||
token: string,
|
||||
inviteUserInput: IInviteUserInput
|
||||
): Promise<void> {
|
||||
const inviteToken = await this.getInviteOrThrowError(token);
|
||||
await this.validateUserPhoneNumber(inviteUserInput);
|
||||
|
||||
@@ -61,14 +61,20 @@ export default class InviteUserService {
|
||||
});
|
||||
|
||||
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 all async operations.
|
||||
const [updatedUser] = await Promise.all([updateUserOper, deleteInviteTokenOper]);
|
||||
const [updatedUser] = await Promise.all([
|
||||
updateUserOper,
|
||||
deleteInviteTokenOper,
|
||||
]);
|
||||
|
||||
// Triggers `onUserAcceptInvite` event.
|
||||
this.eventDispatcher.dispatch(events.inviteUser.acceptInvite, {
|
||||
inviteToken, user: updatedUser,
|
||||
inviteToken,
|
||||
user: updatedUser,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -77,10 +83,17 @@ export default class InviteUserService {
|
||||
* @param {number} tenantId -
|
||||
* @param {string} email -
|
||||
* @param {IUser} authorizedUser -
|
||||
*
|
||||
*
|
||||
* @return {Promise<IInvite>}
|
||||
*/
|
||||
public async sendInvite(tenantId: number, email: string, authorizedUser: ISystemUser): Promise<{ invite: IInvite, user: ISystemUser }> {
|
||||
public async sendInvite(
|
||||
tenantId: number,
|
||||
email: string,
|
||||
authorizedUser: ISystemUser
|
||||
): Promise<{
|
||||
invite: IInvite,
|
||||
user: ISystemUser
|
||||
}> {
|
||||
await this.throwErrorIfUserEmailExists(email);
|
||||
|
||||
this.logger.info('[send_invite] trying to store invite token.');
|
||||
@@ -90,7 +103,9 @@ export default class InviteUserService {
|
||||
token: uniqid(),
|
||||
});
|
||||
|
||||
this.logger.info('[send_invite] trying to store user with email and tenant.');
|
||||
this.logger.info(
|
||||
'[send_invite] trying to store user with email and tenant.'
|
||||
);
|
||||
const { systemUserRepository } = this.sysRepositories;
|
||||
const user = await systemUserRepository.create({
|
||||
email,
|
||||
@@ -100,39 +115,45 @@ export default class InviteUserService {
|
||||
|
||||
// Triggers `onUserSendInvite` event.
|
||||
this.eventDispatcher.dispatch(events.inviteUser.sendInvite, {
|
||||
invite,
|
||||
invite,
|
||||
});
|
||||
return { invite, user };
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate the given invite token.
|
||||
* @param {string} token - the given token string.
|
||||
* @param {string} token - the given token string.
|
||||
* @throws {ServiceError}
|
||||
*/
|
||||
public async checkInvite(token: string): Promise<{ inviteToken: string, orgName: object}> {
|
||||
const inviteToken = await this.getInviteOrThrowError(token)
|
||||
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.
|
||||
const tenant = await Tenant.query().findOne('id', inviteToken.tenantId);
|
||||
|
||||
const tenantDb = this.tenantsManager.knexInstance(tenant.organizationId);
|
||||
|
||||
const orgName = await Option.bindKnex(tenantDb).query()
|
||||
.findOne('key', 'organization_name')
|
||||
const orgName = await Option.bindKnex(tenantDb)
|
||||
.query()
|
||||
.findOne('key', 'organization_name');
|
||||
|
||||
// Triggers `onUserCheckInvite` event.
|
||||
this.eventDispatcher.dispatch(events.inviteUser.checkInvite, {
|
||||
inviteToken, orgName,
|
||||
inviteToken,
|
||||
orgName,
|
||||
});
|
||||
return { inviteToken, orgName };
|
||||
}
|
||||
|
||||
/**
|
||||
* Throws error in case the given user email not exists on the storage.
|
||||
* @param {string} email
|
||||
* @param {string} email
|
||||
*/
|
||||
private async throwErrorIfUserEmailExists(email: string): Promise<ISystemUser> {
|
||||
private async throwErrorIfUserEmailExists(
|
||||
email: string
|
||||
): Promise<ISystemUser> {
|
||||
const { systemUserRepository } = this.sysRepositories;
|
||||
const foundUser = await systemUserRepository.getByEmail(email);
|
||||
|
||||
@@ -160,14 +181,18 @@ export default class InviteUserService {
|
||||
|
||||
/**
|
||||
* Validate the given user email and phone number uniquine.
|
||||
* @param {IInviteUserInput} inviteUserInput
|
||||
* @param {IInviteUserInput} inviteUserInput
|
||||
*/
|
||||
private async validateUserPhoneNumber(inviteUserInput: IInviteUserInput): Promise<ISystemUser> {
|
||||
private async validateUserPhoneNumber(
|
||||
inviteUserInput: IInviteUserInput
|
||||
): Promise<ISystemUser> {
|
||||
const { systemUserRepository } = this.sysRepositories;
|
||||
const foundUser = await systemUserRepository.getByPhoneNumber(inviteUserInput.phoneNumber)
|
||||
|
||||
const foundUser = await systemUserRepository.getByPhoneNumber(
|
||||
inviteUserInput.phoneNumber
|
||||
);
|
||||
|
||||
if (foundUser) {
|
||||
throw new ServiceError('phone_number_exists');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ import events from 'subscribers/events';
|
||||
import {
|
||||
TenantAlreadyInitialized,
|
||||
TenantAlreadySeeded,
|
||||
TenantDatabaseNotBuilt
|
||||
TenantDatabaseNotBuilt,
|
||||
} from 'exceptions';
|
||||
import TenantsManager from 'services/Tenancy/TenantsManager';
|
||||
|
||||
@@ -35,10 +35,10 @@ export default class OrganizationService {
|
||||
|
||||
/**
|
||||
* Builds the database schema and seed data of the given organization id.
|
||||
* @param {srting} organizationId
|
||||
* @param {srting} organizationId
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
public async build(organizationId: string): Promise<void> {
|
||||
public async build(organizationId: string, user: ISystemUser): Promise<void> {
|
||||
const tenant = await this.getTenantByOrgIdOrThrowError(organizationId);
|
||||
this.throwIfTenantInitizalized(tenant);
|
||||
|
||||
@@ -46,15 +46,18 @@ export default class OrganizationService {
|
||||
|
||||
try {
|
||||
if (!tenantHasDB) {
|
||||
this.logger.info('[organization] trying to create tenant database.', { organizationId });
|
||||
this.logger.info('[organization] trying to create tenant database.', {
|
||||
organizationId, userId: user.id,
|
||||
});
|
||||
await this.tenantsManager.createDatabase(tenant);
|
||||
}
|
||||
this.logger.info('[organization] trying to migrate tenant database.', { organizationId });
|
||||
this.logger.info('[organization] trying to migrate tenant database.', {
|
||||
organizationId, userId: user.id,
|
||||
});
|
||||
await this.tenantsManager.migrateTenant(tenant);
|
||||
|
||||
// Throws `onOrganizationBuild` event.
|
||||
this.eventDispatcher.dispatch(events.organization.build, { tenant });
|
||||
|
||||
this.eventDispatcher.dispatch(events.organization.build, { tenant, user });
|
||||
} catch (error) {
|
||||
if (error instanceof TenantAlreadyInitialized) {
|
||||
throw new ServiceError(ERRORS.TENANT_ALREADY_INITIALIZED);
|
||||
@@ -66,7 +69,7 @@ export default class OrganizationService {
|
||||
|
||||
/**
|
||||
* Seeds initial core data to the given organization tenant.
|
||||
* @param {number} organizationId
|
||||
* @param {number} organizationId
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
public async seed(organizationId: string): Promise<void> {
|
||||
@@ -74,12 +77,13 @@ export default class OrganizationService {
|
||||
this.throwIfTenantSeeded(tenant);
|
||||
|
||||
try {
|
||||
this.logger.info('[organization] trying to seed tenant database.', { organizationId });
|
||||
this.logger.info('[organization] trying to seed tenant database.', {
|
||||
organizationId,
|
||||
});
|
||||
await this.tenantsManager.seedTenant(tenant);
|
||||
|
||||
// Throws `onOrganizationBuild` event.
|
||||
this.eventDispatcher.dispatch(events.organization.seeded, { tenant });
|
||||
|
||||
} catch (error) {
|
||||
if (error instanceof TenantAlreadySeeded) {
|
||||
throw new ServiceError(ERRORS.TENANT_ALREADY_SEEDED);
|
||||
@@ -93,11 +97,13 @@ export default class OrganizationService {
|
||||
|
||||
/**
|
||||
* Listing all associated organizations to the given user.
|
||||
* @param {ISystemUser} user -
|
||||
* @param {ISystemUser} user -
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
public async listOrganizations(user: ISystemUser): Promise<ITenant[]> {
|
||||
this.logger.info('[organization] trying to list all organizations.', { user });
|
||||
this.logger.info('[organization] trying to list all organizations.', {
|
||||
user,
|
||||
});
|
||||
|
||||
const { tenantRepository } = this.sysRepositories;
|
||||
const tenant = await tenantRepository.getById(user.tenantId);
|
||||
@@ -107,7 +113,7 @@ export default class OrganizationService {
|
||||
|
||||
/**
|
||||
* Throws error in case the given tenant is undefined.
|
||||
* @param {ITenant} tenant
|
||||
* @param {ITenant} tenant
|
||||
*/
|
||||
private throwIfTenantNotExists(tenant: ITenant) {
|
||||
if (!tenant) {
|
||||
@@ -118,7 +124,7 @@ export default class OrganizationService {
|
||||
|
||||
/**
|
||||
* Throws error in case the given tenant is already initialized.
|
||||
* @param {ITenant} tenant
|
||||
* @param {ITenant} tenant
|
||||
*/
|
||||
private throwIfTenantInitizalized(tenant: ITenant) {
|
||||
if (tenant.initializedAt) {
|
||||
@@ -128,7 +134,7 @@ export default class OrganizationService {
|
||||
|
||||
/**
|
||||
* Throws service if the tenant already seeded.
|
||||
* @param {ITenant} tenant
|
||||
* @param {ITenant} tenant
|
||||
*/
|
||||
private throwIfTenantSeeded(tenant: ITenant) {
|
||||
if (tenant.seededAt) {
|
||||
@@ -137,9 +143,9 @@ export default class OrganizationService {
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve tenant model by the given organization id or throw not found
|
||||
* Retrieve tenant model by the given organization id or throw not found
|
||||
* error if the tenant not exists on the storage.
|
||||
* @param {string} organizationId
|
||||
* @param {string} organizationId
|
||||
* @return {ITenant}
|
||||
*/
|
||||
private async getTenantByOrgIdOrThrowError(organizationId: string) {
|
||||
@@ -149,4 +155,4 @@ export default class OrganizationService {
|
||||
|
||||
return tenant;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import Mustache from 'mustache';
|
||||
import { Container } from 'typedi';
|
||||
|
||||
import Mail from 'lib/Mail';
|
||||
import config from 'config';
|
||||
export default class SubscriptionMailMessages {
|
||||
/**
|
||||
* Send license code to the given mail address.
|
||||
@@ -11,26 +9,18 @@ export default class SubscriptionMailMessages {
|
||||
*/
|
||||
public async sendMailLicense(licenseCode: string, email: string) {
|
||||
const Logger = Container.get('logger');
|
||||
const Mail = Container.get('mail');
|
||||
|
||||
const filePath = path.join(global.__root, 'views/mail/LicenseReceive.html');
|
||||
const template = fs.readFileSync(filePath, 'utf8');
|
||||
const rendered = Mustache.render(template, { licenseCode });
|
||||
|
||||
const mailOptions = {
|
||||
to: email,
|
||||
from: `${process.env.MAIL_FROM_NAME} ${process.env.MAIL_FROM_ADDRESS}`,
|
||||
subject: 'Bigcapital License',
|
||||
html: rendered,
|
||||
};
|
||||
return new Promise((resolve, reject) => {
|
||||
Mail.sendMail(mailOptions, (error) => {
|
||||
if (error) {
|
||||
reject(error);
|
||||
return;
|
||||
}
|
||||
resolve();
|
||||
|
||||
const mail = new Mail()
|
||||
.setView('mail/LicenseReceive.html')
|
||||
.setSubject('Bigcapital - License code')
|
||||
.setTo(email)
|
||||
.setData({
|
||||
licenseCode,
|
||||
successEmail: config.customerSuccess.email,
|
||||
successPhoneNumber: config.customerSuccess.phoneNumber,
|
||||
});
|
||||
});
|
||||
|
||||
await mail.send();
|
||||
Logger.info('[license_mail] sent successfully.');
|
||||
}
|
||||
}
|
||||
@@ -11,7 +11,7 @@ export default class SubscriptionSMSMessages {
|
||||
* @param {string} licenseCode
|
||||
*/
|
||||
public async sendLicenseSMSMessage(phoneNumber: string, licenseCode: string) {
|
||||
const message: string = `Your license card number: ${licenseCode}.`;
|
||||
const message: string = `Your license card number: ${licenseCode}. If you need any help please contact us. Bigcapital.`;
|
||||
return this.smsClient.sendMessage(phoneNumber, message);
|
||||
}
|
||||
}
|
||||
@@ -12,7 +12,8 @@ export default class EasySMSClient implements SMSClientInterface {
|
||||
*/
|
||||
send(to: string, message: string) {
|
||||
const API_KEY = config.easySMSGateway.api_key;
|
||||
const params = `action=send-sms&api_key=${API_KEY}=&to=${to}&sms=${message}&unicode=1`;
|
||||
const parsedTo = to.indexOf('218') === 0 ? to.replace('218', '') : to;
|
||||
const params = `action=send-sms&api_key=${API_KEY}=&to=${parsedTo}&sms=${message}&unicode=1`;
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
axios.get(`https://easysms.devs.ly/sms/api?${params}`)
|
||||
|
||||
@@ -8,7 +8,7 @@ export default class SMSAPI {
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* Sends the message to the target via the client.
|
||||
* @param {string} to
|
||||
* @param {string} message
|
||||
* @param {array} extraParams
|
||||
|
||||
Reference in New Issue
Block a user