Compare commits
86 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
aec09f178b | ||
|
|
ffe51bae07 | ||
|
|
68231d5edb | ||
|
|
e1ea5c402c | ||
|
|
34b2c2c8b4 | ||
|
|
5d96fe6aa0 | ||
|
|
d2b5084b42 | ||
|
|
81fb0734d5 | ||
|
|
3639ce44e5 | ||
|
|
a7c00d60d5 | ||
|
|
932750b62d | ||
|
|
c90ffed67f | ||
|
|
e92c4486aa | ||
|
|
aaceea5338 | ||
|
|
4d54d180bc | ||
|
|
8fdd98e34d | ||
|
|
d53c5ee5e6 | ||
|
|
4082e4e2b8 | ||
|
|
0c689459cb | ||
|
|
40ef02f215 | ||
|
|
d369f0bb17 | ||
|
|
425d0293cc | ||
|
|
b621650975 | ||
|
|
40948160fe | ||
|
|
aa6b9dd295 | ||
|
|
05c2232b97 | ||
|
|
8f6325d529 | ||
|
|
0aa681043d | ||
|
|
40bddfdfeb | ||
|
|
d6e2f01d70 | ||
|
|
2344d3d34d | ||
|
|
883c5dcb41 | ||
|
|
be10b8934d | ||
|
|
ce38c71fa7 | ||
|
|
1162fbc7c3 | ||
|
|
18b9e25f2b | ||
|
|
dd26bdc482 | ||
|
|
ad3c9ebfe9 | ||
|
|
36611652da | ||
|
|
06c7ee71b4 | ||
|
|
54d3188666 | ||
|
|
3ceb9adda2 | ||
|
|
1249415054 | ||
|
|
4d44ce4c7f | ||
|
|
6c96c371c5 | ||
|
|
6c61a69f10 | ||
|
|
981b65349d | ||
|
|
a7d29a31c8 | ||
|
|
c1d92b74f0 | ||
|
|
6f0f47f38a | ||
|
|
83510cfa70 | ||
|
|
903dc0522a | ||
|
|
eecbcacb90 | ||
|
|
cfbe4cfea0 | ||
|
|
8f039b77e7 | ||
|
|
672a1bbb82 | ||
|
|
b2f3585047 | ||
|
|
e6434ea2d1 | ||
|
|
a21d6a37e4 | ||
|
|
e9fdffa9d9 | ||
|
|
6bd30abddb | ||
|
|
920c8ea95c | ||
|
|
8de3717587 | ||
|
|
cc863f774a | ||
|
|
bcd08284b4 | ||
|
|
8e8161f207 | ||
|
|
7b4b50cf4b | ||
|
|
bca3e51fdf | ||
|
|
6faa378577 | ||
|
|
012b13ad4a | ||
|
|
ad8770f12c | ||
|
|
c6cdbe11e6 | ||
|
|
308980604a | ||
|
|
32148a3207 | ||
|
|
fe270b3703 | ||
|
|
950b5407c3 | ||
|
|
e4a647376c | ||
|
|
85b24c7a4f | ||
|
|
4a22576d88 | ||
|
|
d1ab64e9bd | ||
|
|
110fdbaa4e | ||
|
|
961ff74880 | ||
|
|
da20b7c837 | ||
|
|
a5c190e094 | ||
|
|
7177276b12 | ||
|
|
65bb3a1cb8 |
12
.env.example
@@ -8,9 +8,10 @@ MAIL_FROM_NAME=
|
||||
MAIL_FROM_ADDRESS=
|
||||
|
||||
# Database
|
||||
DB_USER=
|
||||
DB_HOST=
|
||||
DB_USER=
|
||||
DB_PASSWORD=
|
||||
DB_ROOT_PASSWORD=
|
||||
DB_CHARSET=
|
||||
|
||||
# System database
|
||||
@@ -29,6 +30,15 @@ JWT_SECRET=b0JDZW56RnV6aEthb0RGPXVEcUI
|
||||
BASE_URL=https://bigcapital.ly
|
||||
CONTACT_US_MAIL=support@bigcapital.ly
|
||||
|
||||
# App proxy
|
||||
PUBLIC_PROXY_PORT=80
|
||||
PUBLIC_PROXY_SSL_PORT=443
|
||||
|
||||
# Agendash
|
||||
AGENDASH_AUTH_USER=agendash
|
||||
AGENDASH_AUTH_PASSWORD=123123
|
||||
|
||||
# Sign-up restrictions
|
||||
SIGNUP_DISABLED=true
|
||||
SIGNUP_ALLOWED_DOMAINS=
|
||||
SIGNUP_ALLOWED_EMAILS=
|
||||
68
.github/workflows/e2e.yml
vendored
Normal file
@@ -0,0 +1,68 @@
|
||||
name: E2E
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
- develop
|
||||
paths:
|
||||
- '**.ts'
|
||||
- '**.tsx'
|
||||
- '**/tsconfig.json'
|
||||
- 'yarn.lock'
|
||||
- '.github/workflows/e2e.yml'
|
||||
pull_request:
|
||||
paths:
|
||||
- '**.ts'
|
||||
- '**.tsx'
|
||||
- '**/tsconfig.json'
|
||||
- 'yarn.lock'
|
||||
- '.github/workflows/e2e.yml'
|
||||
|
||||
defaults:
|
||||
run:
|
||||
shell: 'bash'
|
||||
|
||||
jobs:
|
||||
test_setup:
|
||||
name: Test setup
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
preview_url: ${{ steps.waitForVercelPreviewDeployment.outputs.url }}
|
||||
steps:
|
||||
- name: Wait for Vercel preview deployment to be ready
|
||||
uses: patrickedqvist/wait-for-vercel-preview@v1.3.1
|
||||
id: waitForVercelPreviewDeployment
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
max_timeout: 3000
|
||||
|
||||
test_e2e:
|
||||
runs-on: ubuntu-latest
|
||||
needs: test_setup
|
||||
name: Playwright tests
|
||||
timeout-minutes: 15
|
||||
environment: ${{ vars.ENVIRONMENT_STAGE }}
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/setup-node@v2
|
||||
with:
|
||||
node-version: 14 # Need for npm >=7.7
|
||||
cache: 'npm'
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm install
|
||||
|
||||
- name: Install Playwright with deps
|
||||
run: npx playwright install --with-deps
|
||||
|
||||
- name: Run tests
|
||||
run: npm run test:e2e
|
||||
env:
|
||||
PLAYWRIGHT_TEST_BASE_URL: ${{ needs.test_setup.outputs.preview_url }}
|
||||
|
||||
- uses: actions/upload-artifact@v2
|
||||
if: always()
|
||||
with:
|
||||
name: playwright-report
|
||||
path: test-results/
|
||||
retention-days: 30
|
||||
3
.gitignore
vendored
@@ -1,3 +1,4 @@
|
||||
node_modules/
|
||||
data
|
||||
.env
|
||||
.env
|
||||
test-results/
|
||||
44
CHANGELOG.md
@@ -2,6 +2,50 @@
|
||||
|
||||
All notable changes to Bigcapital server-side will be in this file.
|
||||
|
||||
## [0.9.1] - 28-05-2023
|
||||
|
||||
`@bigcapital/server`
|
||||
- fix: deleting ledger entries of manual journal.
|
||||
- fix: base currency should be enabled.
|
||||
- fix: delete invoice transaction issue.
|
||||
|
||||
`@bigcapital/webapp`
|
||||
- fix: general, accoutant and items preferences.
|
||||
- fix: auto-increment sale invoices, estiamtes, credit notes, payments and manual journals.
|
||||
- refactor: the setup organization form to use binded Formik components.
|
||||
|
||||
## [0.9.0] - 06-05-2023
|
||||
|
||||
`@bigcapital/server`
|
||||
|
||||
- [Sign-up restrictions](https://docs.bigcapital.ly/docs/deployment/signup_restriction) for self-hosting instances to disable signup or control the allowed email addresses and domains that can sign-up.
|
||||
|
||||
## [0.8.3] - 06-04-2023
|
||||
|
||||
`@bigcaptial/monorepo`
|
||||
|
||||
- Switch to AGPL license to protect application's networks. by @abouolia
|
||||
|
||||
`@bigcapital/webapp`
|
||||
|
||||
### Added
|
||||
|
||||
- Improve the style of authentication pages. by @abouolia
|
||||
- Remove the phone number field from the authentication pages. by @abouolia
|
||||
- Remove the phone number field from the users management. by @abouolia
|
||||
- Add all countries options to the setup page. by @abouolia
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fix intent type of reset password success toast.
|
||||
|
||||
`@bigcapital/server`
|
||||
|
||||
### Added
|
||||
|
||||
- Remove the phone number field from the authentication service. by @abouolia
|
||||
- Remove the phone number field from the users service. by @abouolia
|
||||
|
||||
## [0.8.1] - 26-03-2023
|
||||
|
||||
`@bigcaptial/monorepo`
|
||||
|
||||
132
CONTRIBUTING.md
Normal file
@@ -0,0 +1,132 @@
|
||||
# Contributing Guidelines
|
||||
|
||||
Thank you for considering contributing to our project! We appreciate your interest and welcome any contributions you may have.
|
||||
|
||||
Please read through this document before submitting any issues or pull requests to ensure we have all the necessary information to effectively respond to your bug report or contribution.
|
||||
|
||||
## Sections
|
||||
|
||||
- [General Instructions](#general-instructions)
|
||||
- [Contribute to Backend](#contribute-to-backend)
|
||||
- [Contribute to Frontend](#contribute-to-frontend)
|
||||
- [Other Ways to Contribute](#other-ways-to-contribute)
|
||||
|
||||
## General Instructions
|
||||
|
||||
## For Pull Request(s)
|
||||
|
||||
Contributions via pull requests are much appreciated. Once the approach is agreed upon ✅, make your changes and open a Pull Request(s). Before sending us a pull request, please ensure that,
|
||||
|
||||
- Fork the repo on GitHub, clone it on your machine.
|
||||
- Create a branch with your changes.
|
||||
- You are working against the latest source on the `develop` branch.
|
||||
- Modify the source; please focus only on the specific change.
|
||||
- Ensure local tests pass.
|
||||
- Commit to your fork using clear commit messages.
|
||||
- Send us a pull request.
|
||||
- Pay attention to any automated CI failures reported in the pull request.
|
||||
- Stay involved in the conversation
|
||||
|
||||
⚠️ Please note: If you want to work on an issue, please ask the maintainers to assign the issue to you before starting work on it. This would help us understand who is working on an issue and prevent duplicate work. 🙏🏻
|
||||
|
||||
---
|
||||
|
||||
## Contribute to Backend
|
||||
|
||||
- Clone the `bigcapital` repository and `cd` into `bigcapital` directory.
|
||||
- Install all npm dependencies of the monorepo, you don't have to change directory to the `backend` package. just hit these command on root directory and it will install dependencies of all packages.
|
||||
|
||||
```
|
||||
npm install
|
||||
npm run bootstrap
|
||||
```
|
||||
|
||||
- Run all required docker containers in the development, we already configured all containers under `docker-compose.yml`.
|
||||
|
||||
```
|
||||
docker-compose up -d
|
||||
```
|
||||
|
||||
Wait some seconds, and hit `docker-compose ps` and you should see the same result below.
|
||||
|
||||
```
|
||||
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
|
||||
d974edfab9df bigcapital-mysql "docker-entrypoint.s…" 7 seconds ago Up 1 second 0.0.0.0:3306->3306/tcp, 33060/tcp bigcapital-mysql-1
|
||||
cefa73fe2881 bigcapital-redis "docker-entrypoint.s…" 7 seconds ago Up 1 second 6379/tcp bigcapital-redis-1
|
||||
1ea059198cb4 bigcapital-mongo "docker-entrypoint.s…" 7 seconds ago Up 1 second 0.0.0.0:27017->27017/tcp bigcapital-mongo-1
|
||||
```
|
||||
|
||||
- There're some CLI commands we should run before running the server like databaase migration, so we need to build the `server` app first.
|
||||
|
||||
```
|
||||
npm run build:server
|
||||
```
|
||||
|
||||
- Run the database migration for system database.
|
||||
|
||||
```
|
||||
node packages/server/build/commands.js system:migrate:latest
|
||||
```
|
||||
|
||||
And you should get something like that.
|
||||
|
||||
```
|
||||
Batch 1 run: 6 migrations
|
||||
```
|
||||
|
||||
- Next, start the webapp application.
|
||||
|
||||
```
|
||||
npm run dev:server
|
||||
```
|
||||
|
||||
**[`^top^`](#)**
|
||||
|
||||
----
|
||||
|
||||
## Contribute to Frontend
|
||||
|
||||
- Clone the `bigcapital` repository and cd into `bigcapital` directory.
|
||||
|
||||
```
|
||||
git clone https://github.com/bigcapital/bigcapital.git && cd bigcaptial
|
||||
```
|
||||
|
||||
- Install all npm dependencies of the monorepo, you don't have to change directory to the `frontend` package. just hit that command and will install all packages across all application.
|
||||
|
||||
```
|
||||
npm install
|
||||
npm run bootstrap
|
||||
```
|
||||
|
||||
- Next, start the webapp application.
|
||||
|
||||
```
|
||||
npm run dev:webapp
|
||||
```
|
||||
|
||||
**[`^top^`](#)**
|
||||
|
||||
---
|
||||
|
||||
## Code Review
|
||||
|
||||
We welcome constructive criticism and feedback on code submitted by contributors. All feedback should be constructive and respectful, and should focus on the code rather than the contributor. Code review may include suggestions for improvement or changes to the code.
|
||||
|
||||
---
|
||||
|
||||
## Other Ways to Contribute
|
||||
|
||||
There are many other ways to get involved with the community and to participate in this project:
|
||||
|
||||
- Use the product, submitting GitHub issues when a problem is found.
|
||||
- Help code review pull requests and participate in issue threads.
|
||||
- Submit a new feature request as an issue.
|
||||
- Help answer questions on forums such as Bigcapital Community Discord Channel.
|
||||
- Tell others about the project on Twitter, your blog, etc.
|
||||
|
||||
**[`^top^`](#)**
|
||||
|
||||
Again, Feel free to ping us on [`#contributing`](https://discord.com/invite/c8nPBJafeb) on our Discord community if you need any help on this :)
|
||||
|
||||
Thank You!
|
||||
@@ -26,6 +26,6 @@ Bigcapital is a smart and open-source accounting and inventory software, Bigcapi
|
||||
- [Bug Tracker](https://github.com/bigcapitalhq/bigcapital/issues) - Notify us new bugs.
|
||||
- [Source Code](https://github.com/bigcapitalhq/bigcapital) - Github repo.
|
||||
|
||||
# Changlog
|
||||
# Changelog
|
||||
|
||||
Please see [Releases](https://github.com/bigcapitalhq/bigcapital/releases) for more information what has changed recently.
|
||||
|
||||
@@ -15,14 +15,14 @@ services:
|
||||
- ./data/logs/nginx/:/var/log/nginx
|
||||
- ./docker/certbot/certs/:/var/certs
|
||||
ports:
|
||||
- "80:80"
|
||||
- "443:443"
|
||||
- "${PUBLIC_PROXY_PORT:-80}:80"
|
||||
- "${PUBLIC_PROXY_SSL_PORT:-443}:443"
|
||||
tty: true
|
||||
depends_on:
|
||||
- server
|
||||
- webapp
|
||||
|
||||
webapp:
|
||||
webapp:
|
||||
container_name: bigcapital-webapp
|
||||
image: ghcr.io/bigcapitalhq/webapp:latest
|
||||
|
||||
@@ -40,7 +40,7 @@ services:
|
||||
environment:
|
||||
# Mail
|
||||
- MAIL_HOST=${MAIL_HOST}
|
||||
- MAIL_USERNAME=${MAIL_USERNAM}
|
||||
- MAIL_USERNAME=${MAIL_USERNAME}
|
||||
- MAIL_PASSWORD=${MAIL_PASSWORD}
|
||||
- MAIL_PORT=${MAIL_PORT}
|
||||
- MAIL_SECURE=${MAIL_SECURE}
|
||||
@@ -72,29 +72,36 @@ services:
|
||||
- AGENDASH_AUTH_USER=${AGENDASH_AUTH_USER}
|
||||
- AGENDASH_AUTH_PASSWORD=${AGENDASH_AUTH_PASSWORD}
|
||||
|
||||
# Sign-up restrictions
|
||||
- SIGNUP_DISABLED=${SIGNUP_DISABLED}
|
||||
- SIGNUP_ALLOWED_DOMAINS=${SIGNUP_ALLOWED_DOMAINS}
|
||||
- SIGNUP_ALLOWED_EMAILS=${SIGNUP_ALLOWED_EMAILS}
|
||||
|
||||
database_migration:
|
||||
container_name: bigcapital-database-migration
|
||||
build:
|
||||
context: ./
|
||||
dockerfile: docker/migration/Dockerfile
|
||||
args:
|
||||
- DB_HOST=mysql
|
||||
- DB_USER=${DB_USER}
|
||||
- DB_PASSWORD=${DB_PASSWORD}
|
||||
- DB_CHARSET=${DB_CHARSET}
|
||||
- SYSTEM_DB_NAME=${SYSTEM_DB_NAME}
|
||||
environment:
|
||||
- DB_HOST=mysql
|
||||
- DB_USER=${DB_USER}
|
||||
- DB_PASSWORD=${DB_PASSWORD}
|
||||
- DB_CHARSET=${DB_CHARSET}
|
||||
- SYSTEM_DB_NAME=${SYSTEM_DB_NAME}
|
||||
depends_on:
|
||||
- mysql
|
||||
|
||||
mysql:
|
||||
container_name: bigcapital-mysql
|
||||
build:
|
||||
context: ./docker/mysql
|
||||
args:
|
||||
- MYSQL_DATABASE=${SYSTEM_DB_NAME}
|
||||
- MYSQL_USER=${DB_NAME}
|
||||
- MYSQL_PASSWORD=${DB_PASSWORD}
|
||||
- MYSQL_ROOT_PASSWORD=${DB_PASSWORD}
|
||||
context: ./docker/mariadb
|
||||
environment:
|
||||
- MYSQL_DATABASE=${SYSTEM_DB_NAME}
|
||||
- MYSQL_USER=${DB_USER}
|
||||
- MYSQL_PASSWORD=${DB_PASSWORD}
|
||||
- MYSQL_ROOT_PASSWORD=${DB_ROOT_PASSWORD}
|
||||
volumes:
|
||||
- ./data/mysql/:/var/lib/mysql
|
||||
- mysql:/var/lib/mysql
|
||||
expose:
|
||||
- '3306'
|
||||
|
||||
@@ -104,7 +111,7 @@ services:
|
||||
expose:
|
||||
- '27017'
|
||||
volumes:
|
||||
- ./data/mongo/:/var/lib/mongodb
|
||||
- mongo:/var/lib/mongodb
|
||||
|
||||
redis:
|
||||
container_name: bigcapital-redis
|
||||
@@ -113,4 +120,18 @@ services:
|
||||
expose:
|
||||
- "6379"
|
||||
volumes:
|
||||
- ./data/redis:/data
|
||||
- redis:/data
|
||||
|
||||
# Volumes
|
||||
volumes:
|
||||
mysql:
|
||||
name: bigcapital_prod_mysql
|
||||
driver: local
|
||||
|
||||
mongo:
|
||||
name: bigcapital_prod_mongo
|
||||
driver: local
|
||||
|
||||
redis:
|
||||
name: bigcapital_prod_redis
|
||||
driver: local
|
||||
|
||||
@@ -6,16 +6,16 @@
|
||||
version: '3.3'
|
||||
|
||||
services:
|
||||
mysql:
|
||||
mariadb:
|
||||
build:
|
||||
context: ./docker/mysql
|
||||
args:
|
||||
- MYSQL_DATABASE=${SYSTEM_DB_NAME}
|
||||
- MYSQL_USER=${DB_NAME}
|
||||
- MYSQL_PASSWORD=${DB_PASSWORD}
|
||||
- MYSQL_ROOT_PASSWORD=${DB_PASSWORD}
|
||||
context: ./docker/mariadb
|
||||
environment:
|
||||
- MYSQL_DATABASE=${SYSTEM_DB_NAME}
|
||||
- MYSQL_USER=${DB_USER}
|
||||
- MYSQL_PASSWORD=${DB_PASSWORD}
|
||||
- MYSQL_ROOT_PASSWORD=${DB_ROOT_PASSWORD}
|
||||
volumes:
|
||||
- ./data/mysql/:/var/lib/mysql
|
||||
- mysql:/var/lib/mysql
|
||||
expose:
|
||||
- '3306'
|
||||
ports:
|
||||
@@ -26,7 +26,7 @@ services:
|
||||
expose:
|
||||
- '27017'
|
||||
volumes:
|
||||
- ./data/mongo/:/var/lib/mongodb
|
||||
- mongo:/var/lib/mongodb
|
||||
ports:
|
||||
- '27017:27017'
|
||||
|
||||
@@ -36,4 +36,18 @@ services:
|
||||
expose:
|
||||
- "6379"
|
||||
volumes:
|
||||
- ./data/redis:/data
|
||||
- redis:/data
|
||||
|
||||
# Volumes
|
||||
volumes:
|
||||
mysql:
|
||||
name: bigcapital_dev_mysql
|
||||
driver: local
|
||||
|
||||
mongo:
|
||||
name: bigcapital_dev_mongo
|
||||
driver: local
|
||||
|
||||
redis:
|
||||
name: bigcapital_dev_redis
|
||||
driver: local
|
||||
26
docker/mariadb/Dockerfile
Normal file
@@ -0,0 +1,26 @@
|
||||
FROM mariadb:10.2
|
||||
|
||||
USER root
|
||||
ADD my.cnf /etc/mysql/conf.d/my.cnf
|
||||
|
||||
ARG MYSQL_DATABASE=default_database
|
||||
ARG MYSQL_USER=default_user
|
||||
ARG MYSQL_PASSWORD=secret
|
||||
ARG MYSQL_ROOT_PASSWORD=root
|
||||
|
||||
ENV MYSQL_DATABASE=$MYSQL_DATABASE
|
||||
ENV MYSQL_USER=$MYSQL_USER
|
||||
ENV MYSQL_PASSWORD=$MYSQL_PASSWORD
|
||||
ENV MYSQL_ROOT_PASSWORD=$MYSQL_ROOT_PASSWORD
|
||||
|
||||
# Copy init sql file with env vars and then the script will substitute the variables.
|
||||
COPY ./init.sql /scripts/init.template.sql
|
||||
COPY ./docker-entrypoint.sh /docker-entrypoint-initdb.d/docker-initialize.sh
|
||||
|
||||
# The scripts in the `docker-entrypoint-initdb.d/` directory are executed as
|
||||
# the mysql user inside the MySQL Docker container.
|
||||
RUN chown -R mysql:root /docker-entrypoint-initdb.d
|
||||
RUN chown -R mysql:root /scripts
|
||||
|
||||
CMD ["mysqld"]
|
||||
EXPOSE 3306
|
||||
18
docker/mariadb/docker-entrypoint.sh
Normal file
@@ -0,0 +1,18 @@
|
||||
#!/bin/bash
|
||||
|
||||
# chmod u+rwx /scripts/init.template.sql
|
||||
cp /scripts/init.template.sql /scripts/init.sql
|
||||
|
||||
# Replace environment variables in SQL files with their values
|
||||
if [ -n "$MYSQL_USER" ]; then
|
||||
sed -i "s/{MYSQL_USER}/$MYSQL_USER/g" /scripts/init.sql
|
||||
fi
|
||||
if [ -n "$MYSQL_PASSWORD" ]; then
|
||||
sed -i "s/{MYSQL_PASSWORD}/$MYSQL_PASSWORD/g" /scripts/init.sql
|
||||
fi
|
||||
if [ -n "$MYSQL_DATABASE" ]; then
|
||||
sed -i "s/{MYSQL_DATABASE}/$MYSQL_DATABASE/g" /scripts/init.sql
|
||||
fi
|
||||
|
||||
# Execute SQL file
|
||||
mysql -u root -p$MYSQL_ROOT_PASSWORD < /scripts/init.sql
|
||||
3
docker/mariadb/init.sql
Normal file
@@ -0,0 +1,3 @@
|
||||
GRANT ALL PRIVILEGES ON *.* TO '{MYSQL_USER}'@'%' IDENTIFIED BY '{MYSQL_PASSWORD}' WITH GRANT OPTION;
|
||||
|
||||
FLUSH PRIVILEGES;
|
||||
@@ -1,18 +0,0 @@
|
||||
FROM mysql:5.7
|
||||
|
||||
ADD my.cnf /etc/mysql/conf.d/my.cnf
|
||||
|
||||
RUN chown -R mysql:root /var/lib/mysql/
|
||||
|
||||
ARG MYSQL_DATABASE=default_database
|
||||
ARG MYSQL_USER=default_user
|
||||
ARG MYSQL_PASSWORD=secret
|
||||
ARG MYSQL_ROOT_PASSWORD=root
|
||||
|
||||
ENV MYSQL_DATABASE=$MYSQL_DATABASE
|
||||
ENV MYSQL_USER=$MYSQL_USER
|
||||
ENV MYSQL_PASSWORD=$MYSQL_PASSWORD
|
||||
ENV MYSQL_ROOT_PASSWORD=$MYSQL_ROOT_PASSWORD
|
||||
|
||||
CMD ["mysqld"]
|
||||
EXPOSE 3306
|
||||
68
e2e/authentication.spec.ts
Normal file
@@ -0,0 +1,68 @@
|
||||
import { test, expect, Page } from '@playwright/test';
|
||||
|
||||
let authPage: Page;
|
||||
|
||||
test.describe('authentication', () => {
|
||||
test.beforeAll(async ({ browser }) => {
|
||||
authPage = await browser.newPage();
|
||||
});
|
||||
|
||||
test.describe('login', () => {
|
||||
test.beforeAll(async () => {
|
||||
await authPage.goto('/auth/login');
|
||||
});
|
||||
test('should show the login page.', async () => {
|
||||
await expect(authPage.locator('body')).toContainText(
|
||||
"Don't have an account? Sign up"
|
||||
);
|
||||
});
|
||||
test('should email and password be required.', async () => {
|
||||
await authPage.getByRole('button', { name: 'Log in' }).click();
|
||||
|
||||
await expect(authPage.locator('form')).toContainText(
|
||||
'Email is a required field'
|
||||
);
|
||||
await expect(authPage.locator('form')).toContainText(
|
||||
'Password is a required field'
|
||||
);
|
||||
});
|
||||
test('should go to the register page when click on sign up link', async () => {
|
||||
await authPage.getByRole('link', { name: 'Sign up' }).click();
|
||||
await expect(authPage.url()).toContain('/auth/register');
|
||||
});
|
||||
});
|
||||
|
||||
test.describe('register', () => {
|
||||
test.beforeAll(async () => {
|
||||
await authPage.goto('/auth/register');
|
||||
});
|
||||
test('should first name, last name, email and password be required.', async () => {
|
||||
await authPage.getByRole('button', { name: 'Register' }).click();
|
||||
|
||||
await expect(authPage.locator('form')).toContainText(
|
||||
'First name is a required field'
|
||||
);
|
||||
await expect(authPage.locator('form')).toContainText(
|
||||
'Last name is a required field'
|
||||
);
|
||||
await expect(authPage.locator('form')).toContainText(
|
||||
'Email is a required field'
|
||||
);
|
||||
await expect(authPage.locator('form')).toContainText(
|
||||
'Password is a required field'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
test.describe('reset password', () => {
|
||||
test.beforeAll(async () => {
|
||||
await authPage.goto('/auth/send_reset_password');
|
||||
});
|
||||
test('should email be required.', async () => {
|
||||
await authPage.getByRole('button', { name: 'Reset Password' }).click();
|
||||
await expect(authPage.locator('form')).toContainText(
|
||||
'Email is a required field'
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
26
package-lock.json
generated
@@ -941,6 +941,23 @@
|
||||
"esquery": "^1.0.1"
|
||||
}
|
||||
},
|
||||
"@playwright/test": {
|
||||
"version": "1.32.3",
|
||||
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.32.3.tgz",
|
||||
"integrity": "sha512-BvWNvK0RfBriindxhLVabi8BRe3X0J9EVjKlcmhxjg4giWBD/xleLcg2dz7Tx0agu28rczjNIPQWznwzDwVsZQ==",
|
||||
"requires": {
|
||||
"@types/node": "*",
|
||||
"fsevents": "2.3.2",
|
||||
"playwright-core": "1.32.3"
|
||||
},
|
||||
"dependencies": {
|
||||
"playwright-core": {
|
||||
"version": "1.32.3",
|
||||
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.32.3.tgz",
|
||||
"integrity": "sha512-SB+cdrnu74ZIn5Ogh/8278ngEh9NEEV0vR4sJFmK04h2iZpybfbqBY0bX6+BLYWVdV12JLLI+JEFtSnYgR+mWg=="
|
||||
}
|
||||
}
|
||||
},
|
||||
"@tootallnate/once": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@tootallnate/once/-/once-2.0.0.tgz",
|
||||
@@ -986,8 +1003,7 @@
|
||||
"@types/node": {
|
||||
"version": "18.14.6",
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-18.14.6.tgz",
|
||||
"integrity": "sha512-93+VvleD3mXwlLI/xASjw0FzKcwzl3OdTCzm1LaRfqgS21gfFtK3zDXM5Op9TeeMsJVOaJ2VRDpT9q4Y3d0AvA==",
|
||||
"dev": true
|
||||
"integrity": "sha512-93+VvleD3mXwlLI/xASjw0FzKcwzl3OdTCzm1LaRfqgS21gfFtK3zDXM5Op9TeeMsJVOaJ2VRDpT9q4Y3d0AvA=="
|
||||
},
|
||||
"@types/normalize-package-data": {
|
||||
"version": "2.4.1",
|
||||
@@ -2304,6 +2320,12 @@
|
||||
"integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==",
|
||||
"dev": true
|
||||
},
|
||||
"fsevents": {
|
||||
"version": "2.3.2",
|
||||
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",
|
||||
"integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",
|
||||
"optional": true
|
||||
},
|
||||
"function-bind": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz",
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
"dev:server": "lerna run dev --scope \"@bigcapital/server\"",
|
||||
"build:server": "lerna run build --scope \"@bigcapital/server\"",
|
||||
"serve:server": "lerna run serve --scope \"@bigcapital/server\"",
|
||||
"test:e2e": "playwright test",
|
||||
"prepare": "husky install"
|
||||
},
|
||||
"workspaces": [
|
||||
@@ -21,7 +22,8 @@
|
||||
"@commitlint/config-lerna-scopes": "^17.4.2",
|
||||
"husky": "^8.0.3",
|
||||
"lerna": "^6.4.1",
|
||||
"@commitlint/cli": "^17.4.2"
|
||||
"@commitlint/cli": "^17.4.2",
|
||||
"@playwright/test": "^1.32.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": "14.x"
|
||||
@@ -30,6 +32,5 @@
|
||||
"hooks": {
|
||||
"commit-msg": "commitlint -E HUSKY_GIT_PARAMS"
|
||||
}
|
||||
},
|
||||
"dependencies": {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,7 +34,11 @@ ARG MAIL_HOST= \
|
||||
BASE_URL= \
|
||||
# Agendash
|
||||
AGENDASH_AUTH_USER=agendash \
|
||||
AGENDASH_AUTH_PASSWORD=123123
|
||||
AGENDASH_AUTH_PASSWORD=123123 \
|
||||
# Sign-up restriction
|
||||
SIGNUP_DISABLED= \
|
||||
SIGNUP_ALLOWED_DOMAINS= \
|
||||
SIGNUP_ALLOWED_EMAILS=
|
||||
|
||||
ENV MAIL_HOST=$MAIL_HOST \
|
||||
MAIL_USERNAME=$MAIL_USERNAME \
|
||||
@@ -68,7 +72,11 @@ ENV MAIL_HOST=$MAIL_HOST \
|
||||
# MongoDB
|
||||
MONGODB_DATABASE_URL=$MONGODB_DATABASE_URL \
|
||||
# Application
|
||||
BASE_URL=$BASE_URL
|
||||
BASE_URL=$BASE_URL \
|
||||
# Sign-up restriction
|
||||
SIGNUP_DISABLED=$SIGNUP_DISABLED \
|
||||
SIGNUP_ALLOWED_DOMAINS=$SIGNUP_ALLOWED_DOMAINS \
|
||||
SIGNUP_ALLOWED_EMAILS=$SIGNUP_ALLOWED_EMAILS
|
||||
|
||||
# Create app directory.
|
||||
WORKDIR /app
|
||||
|
||||
@@ -3,7 +3,12 @@ import { check, param, query } from 'express-validator';
|
||||
import { Service, Inject } from 'typedi';
|
||||
import asyncMiddleware from '@/api/middleware/asyncMiddleware';
|
||||
import BaseController from '@/api/controllers/BaseController';
|
||||
import { AbilitySubject, AccountAction, IAccountDTO } from '@/interfaces';
|
||||
import {
|
||||
AbilitySubject,
|
||||
AccountAction,
|
||||
IAccountDTO,
|
||||
IAccountsStructureType,
|
||||
} from '@/interfaces';
|
||||
import { ServiceError } from '@/exceptions';
|
||||
import DynamicListingService from '@/services/DynamicListing/DynamicListService';
|
||||
import { DATATYPES_LENGTH } from '@/data/DataTypes';
|
||||
@@ -172,6 +177,11 @@ export default class AccountsController extends BaseController {
|
||||
|
||||
query('inactive_mode').optional().isBoolean().toBoolean(),
|
||||
query('search_keyword').optional({ nullable: true }).isString().trim(),
|
||||
|
||||
query('structure')
|
||||
.optional()
|
||||
.isString()
|
||||
.isIn([IAccountsStructureType.Tree, IAccountsStructureType.Flat]),
|
||||
];
|
||||
}
|
||||
|
||||
@@ -341,6 +351,7 @@ export default class AccountsController extends BaseController {
|
||||
sortOrder: 'desc',
|
||||
columnSortBy: 'created_at',
|
||||
inactiveMode: false,
|
||||
structure: IAccountsStructureType.Tree,
|
||||
...this.matchedQueryData(req),
|
||||
};
|
||||
|
||||
|
||||
@@ -1,26 +1,23 @@
|
||||
import { Request, Response, Router } from 'express';
|
||||
import { check, ValidationChain } from 'express-validator';
|
||||
import { Service, Inject } from 'typedi';
|
||||
import countries from 'country-codes-list';
|
||||
import parsePhoneNumber from 'libphonenumber-js';
|
||||
import BaseController from '@/api/controllers/BaseController';
|
||||
import asyncMiddleware from '@/api/middleware/asyncMiddleware';
|
||||
import AuthenticationService from '@/services/Authentication';
|
||||
import { ILoginDTO, ISystemUser, IRegisterDTO } from '@/interfaces';
|
||||
import { ServiceError, ServiceErrors } from '@/exceptions';
|
||||
import { DATATYPES_LENGTH } from '@/data/DataTypes';
|
||||
import LoginThrottlerMiddleware from '@/api/middleware/LoginThrottlerMiddleware';
|
||||
import config from '@/config';
|
||||
import AuthenticationApplication from '@/services/Authentication/AuthApplication';
|
||||
|
||||
@Service()
|
||||
export default class AuthenticationController extends BaseController {
|
||||
@Inject()
|
||||
authService: AuthenticationService;
|
||||
private authApplication: AuthenticationApplication;
|
||||
|
||||
/**
|
||||
* Constructor method.
|
||||
*/
|
||||
router() {
|
||||
public router() {
|
||||
const router = Router();
|
||||
|
||||
router.post(
|
||||
@@ -52,13 +49,15 @@ export default class AuthenticationController extends BaseController {
|
||||
asyncMiddleware(this.resetPassword.bind(this)),
|
||||
this.handlerErrors
|
||||
);
|
||||
router.get('/meta', asyncMiddleware(this.getAuthMeta.bind(this)));
|
||||
return router;
|
||||
}
|
||||
|
||||
/**
|
||||
* Login schema.
|
||||
* Login validation schema.
|
||||
* @returns {ValidationChain[]}
|
||||
*/
|
||||
get loginSchema(): ValidationChain[] {
|
||||
private get loginSchema(): ValidationChain[] {
|
||||
return [
|
||||
check('crediential').exists().isEmail(),
|
||||
check('password').exists().isLength({ min: 5 }),
|
||||
@@ -66,9 +65,10 @@ export default class AuthenticationController extends BaseController {
|
||||
}
|
||||
|
||||
/**
|
||||
* Register schema.
|
||||
* Register validation schema.
|
||||
* @returns {ValidationChain[]}
|
||||
*/
|
||||
get registerSchema(): ValidationChain[] {
|
||||
private get registerSchema(): ValidationChain[] {
|
||||
return [
|
||||
check('first_name')
|
||||
.exists()
|
||||
@@ -89,71 +89,20 @@ export default class AuthenticationController extends BaseController {
|
||||
.trim()
|
||||
.escape()
|
||||
.isLength({ max: DATATYPES_LENGTH.STRING }),
|
||||
check('phone_number')
|
||||
.exists()
|
||||
.isString()
|
||||
.trim()
|
||||
.escape()
|
||||
.custom(this.phoneNumberValidator)
|
||||
.isLength({ max: DATATYPES_LENGTH.STRING }),
|
||||
check('password')
|
||||
.exists()
|
||||
.isString()
|
||||
.trim()
|
||||
.escape()
|
||||
.isLength({ max: DATATYPES_LENGTH.STRING }),
|
||||
check('country')
|
||||
.exists()
|
||||
.isString()
|
||||
.trim()
|
||||
.escape()
|
||||
.custom(this.countryValidator)
|
||||
.isLength({ max: DATATYPES_LENGTH.STRING }),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Country validator.
|
||||
*/
|
||||
countryValidator(value, { req }) {
|
||||
const {
|
||||
countries: { whitelist, blacklist },
|
||||
} = config.registration;
|
||||
const foundCountry = countries.findOne('countryCode', value);
|
||||
|
||||
if (!foundCountry) {
|
||||
throw new Error('The country code is invalid.');
|
||||
}
|
||||
if (
|
||||
// Focus with me! In case whitelist is not empty and the given coutry is not
|
||||
// in whitelist throw the error.
|
||||
//
|
||||
// Or in case the blacklist is not empty and the given country exists
|
||||
// in the blacklist throw the goddamn error.
|
||||
(whitelist.length > 0 && whitelist.indexOf(value) === -1) ||
|
||||
(blacklist.length > 0 && blacklist.indexOf(value) !== -1)
|
||||
) {
|
||||
throw new Error('The country code is not supported yet.');
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Phone number validator.
|
||||
*/
|
||||
phoneNumberValidator(value, { req }) {
|
||||
const phoneNumber = parsePhoneNumber(value, req.body.country);
|
||||
|
||||
if (!phoneNumber || !phoneNumber.isValid()) {
|
||||
throw new Error('Phone number is invalid with the given country code.');
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset password schema.
|
||||
* @returns {ValidationChain[]}
|
||||
*/
|
||||
get resetPasswordSchema(): ValidationChain[] {
|
||||
private get resetPasswordSchema(): ValidationChain[] {
|
||||
return [
|
||||
check('password')
|
||||
.exists()
|
||||
@@ -170,8 +119,9 @@ export default class AuthenticationController extends BaseController {
|
||||
|
||||
/**
|
||||
* Send reset password validation schema.
|
||||
* @returns {ValidationChain[]}
|
||||
*/
|
||||
get sendResetPasswordSchema(): ValidationChain[] {
|
||||
private get sendResetPasswordSchema(): ValidationChain[] {
|
||||
return [check('email').exists().isEmail().trim().escape()];
|
||||
}
|
||||
|
||||
@@ -180,11 +130,11 @@ export default class AuthenticationController extends BaseController {
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async login(req: Request, res: Response, next: Function): Response {
|
||||
private async login(req: Request, res: Response, next: Function): Response {
|
||||
const userDTO: ILoginDTO = this.matchedBodyData(req);
|
||||
|
||||
try {
|
||||
const { token, user, tenant } = await this.authService.signIn(
|
||||
const { token, user, tenant } = await this.authApplication.signIn(
|
||||
userDTO.crediential,
|
||||
userDTO.password
|
||||
);
|
||||
@@ -199,13 +149,11 @@ export default class AuthenticationController extends BaseController {
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async register(req: Request, res: Response, next: Function) {
|
||||
private async register(req: Request, res: Response, next: Function) {
|
||||
const registerDTO: IRegisterDTO = this.matchedBodyData(req);
|
||||
|
||||
try {
|
||||
const registeredUser: ISystemUser = await this.authService.register(
|
||||
registerDTO
|
||||
);
|
||||
await this.authApplication.signUp(registerDTO);
|
||||
|
||||
return res.status(200).send({
|
||||
type: 'success',
|
||||
@@ -222,11 +170,11 @@ export default class AuthenticationController extends BaseController {
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async sendResetPassword(req: Request, res: Response, next: Function) {
|
||||
private async sendResetPassword(req: Request, res: Response, next: Function) {
|
||||
const { email } = this.matchedBodyData(req);
|
||||
|
||||
try {
|
||||
await this.authService.sendResetPassword(email);
|
||||
await this.authApplication.sendResetPassword(email);
|
||||
|
||||
return res.status(200).send({
|
||||
code: 'SEND_RESET_PASSWORD_SUCCESS',
|
||||
@@ -244,12 +192,12 @@ export default class AuthenticationController extends BaseController {
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async resetPassword(req: Request, res: Response, next: Function) {
|
||||
private async resetPassword(req: Request, res: Response, next: Function) {
|
||||
const { token } = req.params;
|
||||
const { password } = req.body;
|
||||
|
||||
try {
|
||||
await this.authService.resetPassword(token, password);
|
||||
await this.authApplication.resetPassword(token, password);
|
||||
|
||||
return res.status(200).send({
|
||||
type: 'RESET_PASSWORD_SUCCESS',
|
||||
@@ -260,10 +208,27 @@ export default class AuthenticationController extends BaseController {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the authentication meta for SPA.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
* @returns {Response|void}
|
||||
*/
|
||||
private async getAuthMeta(req: Request, res: Response, next: Function) {
|
||||
try {
|
||||
const meta = await this.authApplication.getAuthMeta();
|
||||
|
||||
return res.status(200).send({ meta });
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles the service errors.
|
||||
*/
|
||||
handlerErrors(error, req: Request, res: Response, next: Function) {
|
||||
private handlerErrors(error, req: Request, res: Response, next: Function) {
|
||||
if (error instanceof ServiceError) {
|
||||
if (
|
||||
['INVALID_DETAILS', 'invalid_password'].indexOf(error.errorType) !== -1
|
||||
@@ -295,18 +260,34 @@ export default class AuthenticationController extends BaseController {
|
||||
errors: [{ type: 'EMAIL.NOT.REGISTERED', code: 500 }],
|
||||
});
|
||||
}
|
||||
}
|
||||
if (error instanceof ServiceErrors) {
|
||||
const errorReasons = [];
|
||||
|
||||
if (error.hasType('PHONE_NUMBER_EXISTS')) {
|
||||
errorReasons.push({ type: 'PHONE_NUMBER_EXISTS', code: 100 });
|
||||
if (error.errorType === 'EMAIL_EXISTS') {
|
||||
return res.status(400).send({
|
||||
errors: [{ type: 'EMAIL.EXISTS', code: 600 }],
|
||||
});
|
||||
}
|
||||
if (error.hasType('EMAIL_EXISTS')) {
|
||||
errorReasons.push({ type: 'EMAIL.EXISTS', code: 200 });
|
||||
if (error.errorType === 'SIGNUP_RESTRICTED') {
|
||||
return res.status(400).send({
|
||||
errors: [
|
||||
{
|
||||
type: 'SIGNUP_RESTRICTED',
|
||||
message:
|
||||
'Sign-up is restricted no one can sign-up to the system.',
|
||||
code: 700,
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
if (errorReasons.length > 0) {
|
||||
return res.boom.badRequest(null, { errors: errorReasons });
|
||||
if (error.errorType === 'SIGNUP_RESTRICTED_NOT_ALLOWED') {
|
||||
return res.status(400).send({
|
||||
errors: [
|
||||
{
|
||||
type: 'SIGNUP_RESTRICTED_NOT_ALLOWED',
|
||||
message:
|
||||
'Sign-up is restricted the given email address is not allowed to sign-up.',
|
||||
code: 710,
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
}
|
||||
next(error);
|
||||
|
||||
@@ -41,7 +41,7 @@ export default class BalanceSheetStatementController extends BaseFinancialReport
|
||||
get balanceSheetValidationSchema(): ValidationChain[] {
|
||||
return [
|
||||
...this.sheetNumberFormatValidationSchema,
|
||||
query('accounting_method').optional().isIn(['cash', 'accural']),
|
||||
query('accounting_method').optional().isIn(['cash', 'accrual']),
|
||||
|
||||
query('from_date').optional(),
|
||||
query('to_date').optional(),
|
||||
|
||||
@@ -67,6 +67,7 @@ export default class GeneralLedgerReportController extends BaseFinancialReportCo
|
||||
try {
|
||||
const { data, query, meta } =
|
||||
await this.generalLedgetService.generalLedger(tenantId, filter);
|
||||
|
||||
return res.status(200).send({
|
||||
meta: this.transfromToResponse(meta),
|
||||
data: this.transfromToResponse(data),
|
||||
|
||||
@@ -11,10 +11,10 @@ import AcceptInviteUserService from '@/services/InviteUsers/AcceptInviteUser';
|
||||
@Service()
|
||||
export default class InviteUsersController extends BaseController {
|
||||
@Inject()
|
||||
inviteUsersService: InviteTenantUserService;
|
||||
private inviteUsersService: InviteTenantUserService;
|
||||
|
||||
@Inject()
|
||||
acceptInviteService: AcceptInviteUserService;
|
||||
private acceptInviteService: AcceptInviteUserService;
|
||||
|
||||
/**
|
||||
* Routes that require authentication.
|
||||
@@ -68,13 +68,13 @@ export default class InviteUsersController extends BaseController {
|
||||
|
||||
/**
|
||||
* Invite DTO schema validation.
|
||||
* @returns {ValidationChain[]}
|
||||
*/
|
||||
get inviteUserDTO() {
|
||||
private 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(),
|
||||
check('password').exists().trim().escape().isLength({ min: 5 }),
|
||||
param('token').exists().trim().escape(),
|
||||
];
|
||||
}
|
||||
@@ -85,17 +85,14 @@ export default class InviteUsersController extends BaseController {
|
||||
* @param {Response} res - Response object.
|
||||
* @param {NextFunction} next - Next function.
|
||||
*/
|
||||
async sendInvite(req: Request, res: Response, next: Function) {
|
||||
private async sendInvite(req: Request, res: Response, next: Function) {
|
||||
const sendInviteDTO = this.matchedBodyData(req);
|
||||
const { tenantId } = req;
|
||||
const { user } = req;
|
||||
|
||||
try {
|
||||
const { invite } = await this.inviteUsersService.sendInvite(
|
||||
tenantId,
|
||||
sendInviteDTO,
|
||||
user
|
||||
);
|
||||
await this.inviteUsersService.sendInvite(tenantId, sendInviteDTO, user);
|
||||
|
||||
return res.status(200).send({
|
||||
type: 'success',
|
||||
code: 'INVITE.SENT.SUCCESSFULLY',
|
||||
@@ -112,7 +109,7 @@ export default class InviteUsersController extends BaseController {
|
||||
* @param {Response} res - Response object.
|
||||
* @param {NextFunction} next - Next function.
|
||||
*/
|
||||
async resendInvite(req: Request, res: Response, next: NextFunction) {
|
||||
private async resendInvite(req: Request, res: Response, next: NextFunction) {
|
||||
const { tenantId, user } = req;
|
||||
const { userId } = req.params;
|
||||
|
||||
@@ -135,7 +132,7 @@ export default class InviteUsersController extends BaseController {
|
||||
* @param {Response} res -
|
||||
* @param {NextFunction} next -
|
||||
*/
|
||||
async accept(req: Request, res: Response, next: Function) {
|
||||
private async accept(req: Request, res: Response, next: Function) {
|
||||
const inviteUserInput: IInviteUserInput = this.matchedBodyData(req, {
|
||||
locations: ['body'],
|
||||
includeOptionals: true,
|
||||
@@ -161,7 +158,7 @@ export default class InviteUsersController extends BaseController {
|
||||
* @param {Response} res -
|
||||
* @param {NextFunction} next -
|
||||
*/
|
||||
async invited(req: Request, res: Response, next: Function) {
|
||||
private async invited(req: Request, res: Response, next: Function) {
|
||||
const { token } = req.params;
|
||||
|
||||
try {
|
||||
@@ -181,7 +178,12 @@ export default class InviteUsersController extends BaseController {
|
||||
/**
|
||||
* Handles the service error.
|
||||
*/
|
||||
handleServicesError(error, req: Request, res: Response, next: Function) {
|
||||
private handleServicesError(
|
||||
error,
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: Function
|
||||
) {
|
||||
if (error instanceof ServiceError) {
|
||||
if (error.errorType === 'EMAIL_EXISTS') {
|
||||
return res.status(400).send({
|
||||
|
||||
@@ -177,7 +177,7 @@ export default class ItemsController extends BaseController {
|
||||
/**
|
||||
* Validate list query schema.
|
||||
*/
|
||||
get validateListQuerySchema() {
|
||||
private get validateListQuerySchema() {
|
||||
return [
|
||||
query('column_sort_by').optional().trim().escape(),
|
||||
query('sort_order').optional().isIn(['desc', 'asc']),
|
||||
@@ -193,32 +193,20 @@ export default class ItemsController extends BaseController {
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate autocomplete list query schema.
|
||||
*/
|
||||
get autocompleteQuerySchema() {
|
||||
return [
|
||||
query('column_sort_by').optional().trim().escape(),
|
||||
query('sort_order').optional().isIn(['desc', 'asc']),
|
||||
|
||||
query('stringified_filter_roles').optional().isJSON(),
|
||||
query('limit').optional().isNumeric().toInt(),
|
||||
|
||||
query('keyword').optional().isString().trim().escape(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Stores the given item details to the storage.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async newItem(req: Request, res: Response, next: NextFunction) {
|
||||
private async newItem(req: Request, res: Response, next: NextFunction) {
|
||||
const { tenantId } = req;
|
||||
const itemDTO: IItemDTO = this.matchedBodyData(req);
|
||||
|
||||
try {
|
||||
const storedItem = await this.itemsApplication.createItem(tenantId, itemDTO);
|
||||
const storedItem = await this.itemsApplication.createItem(
|
||||
tenantId,
|
||||
itemDTO
|
||||
);
|
||||
|
||||
return res.status(200).send({
|
||||
id: storedItem.id,
|
||||
@@ -234,7 +222,7 @@ export default class ItemsController extends BaseController {
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async editItem(req: Request, res: Response, next: NextFunction) {
|
||||
private async editItem(req: Request, res: Response, next: NextFunction) {
|
||||
const { tenantId } = req;
|
||||
const itemId: number = req.params.id;
|
||||
const item: IItemDTO = this.matchedBodyData(req);
|
||||
@@ -257,7 +245,7 @@ export default class ItemsController extends BaseController {
|
||||
* @param {Response} res
|
||||
* @param {NextFunction} next
|
||||
*/
|
||||
async activateItem(req: Request, res: Response, next: NextFunction) {
|
||||
private async activateItem(req: Request, res: Response, next: NextFunction) {
|
||||
const { tenantId } = req;
|
||||
const itemId: number = req.params.id;
|
||||
|
||||
@@ -279,7 +267,11 @@ export default class ItemsController extends BaseController {
|
||||
* @param {Response} res
|
||||
* @param {NextFunction} next
|
||||
*/
|
||||
async inactivateItem(req: Request, res: Response, next: NextFunction) {
|
||||
private async inactivateItem(
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction
|
||||
) {
|
||||
const { tenantId } = req;
|
||||
const itemId: number = req.params.id;
|
||||
|
||||
@@ -300,7 +292,7 @@ export default class ItemsController extends BaseController {
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async deleteItem(req: Request, res: Response, next: NextFunction) {
|
||||
private async deleteItem(req: Request, res: Response, next: NextFunction) {
|
||||
const itemId: number = req.params.id;
|
||||
const { tenantId } = req;
|
||||
|
||||
@@ -322,7 +314,7 @@ export default class ItemsController extends BaseController {
|
||||
* @param {Response} res
|
||||
* @return {Response}
|
||||
*/
|
||||
async getItem(req: Request, res: Response, next: NextFunction) {
|
||||
private async getItem(req: Request, res: Response, next: NextFunction) {
|
||||
const itemId: number = req.params.id;
|
||||
const { tenantId } = req;
|
||||
|
||||
@@ -342,7 +334,7 @@ export default class ItemsController extends BaseController {
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async getItemsList(req: Request, res: Response, next: NextFunction) {
|
||||
private async getItemsList(req: Request, res: Response, next: NextFunction) {
|
||||
const { tenantId } = req;
|
||||
|
||||
const filter = {
|
||||
|
||||
@@ -8,18 +8,12 @@ import JWTAuth from '@/api/middleware/jwtAuth';
|
||||
import TenancyMiddleware from '@/api/middleware/TenancyMiddleware';
|
||||
import AttachCurrentTenantUser from '@/api/middleware/AttachCurrentTenantUser';
|
||||
import OrganizationService from '@/services/Organization/OrganizationService';
|
||||
import {
|
||||
ACCEPTED_CURRENCIES,
|
||||
MONTHS,
|
||||
ACCEPTED_LOCALES,
|
||||
} from '@/services/Organization/constants';
|
||||
import { MONTHS, ACCEPTED_LOCALES } from '@/services/Organization/constants';
|
||||
import { DATE_FORMATS } from '@/services/Miscellaneous/DateFormats/constants';
|
||||
|
||||
import { ServiceError } from '@/exceptions';
|
||||
import BaseController from '@/api/controllers/BaseController';
|
||||
|
||||
const ACCEPTED_LOCATIONS = ['libya'];
|
||||
|
||||
@Service()
|
||||
export default class OrganizationController extends BaseController {
|
||||
@Inject()
|
||||
@@ -64,9 +58,9 @@ export default class OrganizationController extends BaseController {
|
||||
private get organizationValidationSchema(): ValidationChain[] {
|
||||
return [
|
||||
check('name').exists().trim(),
|
||||
check('industry').optional().isString(),
|
||||
check('location').exists().isString().isIn(ACCEPTED_LOCATIONS),
|
||||
check('base_currency').exists().isIn(ACCEPTED_CURRENCIES),
|
||||
check('industry').optional({ nullable: true }).isString().trim().escape(),
|
||||
check('location').exists().isString().isISO31661Alpha2(),
|
||||
check('base_currency').exists().isISO4217(),
|
||||
check('timezone').exists().isIn(moment.tz.names()),
|
||||
check('fiscal_year').exists().isIn(MONTHS),
|
||||
check('language').exists().isString().isIn(ACCEPTED_LOCALES),
|
||||
|
||||
@@ -47,7 +47,6 @@ export default class UsersController extends BaseController {
|
||||
check('first_name').exists(),
|
||||
check('last_name').exists(),
|
||||
check('email').exists().isEmail(),
|
||||
check('phone_number').optional().isMobilePhone(),
|
||||
check('role_id').exists().isNumeric().toInt(),
|
||||
],
|
||||
this.validationResult,
|
||||
|
||||
@@ -4,6 +4,7 @@ import moment from 'moment';
|
||||
global.__root_dir = path.join(__dirname, '..');
|
||||
global.__resources_dir = path.join(global.__root_dir, 'resources');
|
||||
global.__locales_dir = path.join(global.__resources_dir, 'locales');
|
||||
global.__views_dir = path.join(global.__root_dir, 'views');
|
||||
|
||||
moment.prototype.toMySqlDateTime = function () {
|
||||
return this.format('YYYY-MM-DD HH:mm:ss');
|
||||
|
||||
@@ -4,6 +4,7 @@ import color from 'colorette';
|
||||
import argv from 'getopts';
|
||||
import Knex from 'knex';
|
||||
import { knexSnakeCaseMappers } from 'objection';
|
||||
import '../before';
|
||||
import config from '../config';
|
||||
|
||||
function initSystemKnex() {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import dotenv from 'dotenv';
|
||||
import path from 'path';
|
||||
import { castCommaListEnvVarToArray, parseBoolean } from '@/utils';
|
||||
|
||||
dotenv.config();
|
||||
|
||||
@@ -146,6 +147,19 @@ module.exports = {
|
||||
},
|
||||
},
|
||||
|
||||
/**
|
||||
* Sign-up restrictions
|
||||
*/
|
||||
signupRestrictions: {
|
||||
disabled: parseBoolean<boolean>(process.env.SIGNUP_DISABLED, false),
|
||||
allowedDomains: castCommaListEnvVarToArray(
|
||||
process.env.SIGNUP_ALLOWED_DOMAINS
|
||||
),
|
||||
allowedEmails: castCommaListEnvVarToArray(
|
||||
process.env.SIGNUP_ALLOWED_EMAILS
|
||||
),
|
||||
},
|
||||
|
||||
/**
|
||||
* Puppeteer remote browserless connection.
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
exports.up = function (knex) {
|
||||
return knex.schema.table('users', (table) => {
|
||||
table.dropColumn('phone_number');
|
||||
});
|
||||
};
|
||||
|
||||
exports.down = function (knex) {
|
||||
return knex.schema.table('users', (table) => {});
|
||||
};
|
||||
@@ -3,17 +3,17 @@ import AccountsData from '../data/accounts';
|
||||
|
||||
export default class SeedAccounts extends TenantSeeder {
|
||||
/**
|
||||
* Seeds initial accounts to the organization.
|
||||
* Seeds initial accounts to the organization.
|
||||
*/
|
||||
up(knex) {
|
||||
const data = AccountsData.map((account) => {
|
||||
return {
|
||||
...account,
|
||||
name: this.i18n.__(account.name),
|
||||
description: this.i18n.__(account.description),
|
||||
currencyCode: this.tenant.metadata.baseCurrency,
|
||||
};
|
||||
});
|
||||
const data = AccountsData.map((account) => ({
|
||||
...account,
|
||||
name: this.i18n.__(account.name),
|
||||
description: this.i18n.__(account.description),
|
||||
currencyCode: this.tenant.metadata.baseCurrency,
|
||||
seededAt: new Date(),
|
||||
})
|
||||
);
|
||||
return knex('accounts').then(async () => {
|
||||
// Inserts seed entries.
|
||||
return knex('accounts').insert(data);
|
||||
|
||||
@@ -8,7 +8,7 @@ export default class SeedSettings extends TenantSeeder {
|
||||
up() {
|
||||
const settings = [
|
||||
// Orgnization settings.
|
||||
{ group: 'organization', key: 'accounting_basis', value: 'accural' },
|
||||
{ group: 'organization', key: 'accounting_basis', value: 'accrual' },
|
||||
|
||||
// Accounts settings.
|
||||
{ group: 'accounts', key: 'account_code_unique', value: true },
|
||||
|
||||
@@ -42,6 +42,7 @@ export enum AccountNormal {
|
||||
|
||||
export interface IAccountsTransactionsFilter {
|
||||
accountId?: number;
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
export interface IAccountTransaction {
|
||||
@@ -78,9 +79,15 @@ export interface IAccountTransaction {
|
||||
}
|
||||
export interface IAccountResponse extends IAccount {}
|
||||
|
||||
export enum IAccountsStructureType {
|
||||
Tree = 'tree',
|
||||
Flat = 'flat',
|
||||
}
|
||||
|
||||
export interface IAccountsFilter extends IDynamicListFilterDTO {
|
||||
stringifiedFilterRoles?: string;
|
||||
onlyInactive: boolean;
|
||||
structure?: IAccountsStructureType;
|
||||
}
|
||||
|
||||
export interface IAccountType {
|
||||
|
||||
@@ -1,29 +1,81 @@
|
||||
import { ISystemUser } from './User';
|
||||
import { ITenant } from './Tenancy';
|
||||
import { SystemUser } from '@/system/models';
|
||||
|
||||
export interface IRegisterDTO {
|
||||
firstName: string,
|
||||
lastName: string,
|
||||
email: string,
|
||||
password: string,
|
||||
organizationName: string,
|
||||
};
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
email: string;
|
||||
password: string;
|
||||
organizationName: string;
|
||||
}
|
||||
|
||||
export interface ILoginDTO {
|
||||
crediential: string,
|
||||
password: string,
|
||||
};
|
||||
crediential: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
export interface IPasswordReset {
|
||||
id: number,
|
||||
email: string,
|
||||
token: string,
|
||||
createdAt: Date,
|
||||
};
|
||||
id: number;
|
||||
email: string;
|
||||
token: string;
|
||||
createdAt: Date;
|
||||
}
|
||||
|
||||
export interface IAuthenticationService {
|
||||
signIn(emailOrPhone: string, password: string): Promise<{ user: ISystemUser, token: string, tenant: ITenant }>;
|
||||
signIn(
|
||||
email: string,
|
||||
password: string
|
||||
): Promise<{ user: ISystemUser; token: string; tenant: ITenant }>;
|
||||
register(registerDTO: IRegisterDTO): Promise<ISystemUser>;
|
||||
sendResetPassword(email: string): Promise<IPasswordReset>;
|
||||
resetPassword(token: string, password: string): Promise<void>;
|
||||
}
|
||||
|
||||
export interface IAuthSigningInEventPayload {
|
||||
email: string;
|
||||
password: string;
|
||||
user: ISystemUser;
|
||||
}
|
||||
|
||||
export interface IAuthSignedInEventPayload {
|
||||
email: string;
|
||||
password: string;
|
||||
user: ISystemUser;
|
||||
}
|
||||
|
||||
export interface IAuthSigningUpEventPayload {
|
||||
signupDTO: IRegisterDTO;
|
||||
}
|
||||
|
||||
export interface IAuthSignedUpEventPayload {
|
||||
signupDTO: IRegisterDTO;
|
||||
tenant: ITenant;
|
||||
user: ISystemUser;
|
||||
}
|
||||
|
||||
export interface IAuthSignInPOJO {
|
||||
user: ISystemUser;
|
||||
token: string;
|
||||
tenant: ITenant;
|
||||
}
|
||||
|
||||
export interface IAuthResetedPasswordEventPayload {
|
||||
user: SystemUser;
|
||||
token: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
|
||||
export interface IAuthSendingResetPassword {
|
||||
user: ISystemUser,
|
||||
token: string;
|
||||
}
|
||||
export interface IAuthSendedResetPassword {
|
||||
user: ISystemUser,
|
||||
token: string;
|
||||
}
|
||||
|
||||
export interface IAuthGetMetaPOJO {
|
||||
signupDisabled: boolean;
|
||||
}
|
||||
@@ -44,7 +44,7 @@ export interface IBalanceSheetQuery extends IFinancialSheetBranchesQuery {
|
||||
numberFormat: INumberFormatQuery;
|
||||
noneTransactions: boolean;
|
||||
noneZero: boolean;
|
||||
basis: 'cash' | 'accural';
|
||||
basis: 'cash' | 'accrual';
|
||||
accountIds: number[];
|
||||
|
||||
percentageOfColumn: boolean;
|
||||
|
||||
@@ -4,7 +4,7 @@ export interface ITrialBalanceSheetQuery {
|
||||
fromDate: Date | string;
|
||||
toDate: Date | string;
|
||||
numberFormat: INumberFormatQuery;
|
||||
basis: 'cash' | 'accural';
|
||||
basis: 'cash' | 'accrual';
|
||||
noneZero: boolean;
|
||||
noneTransactions: boolean;
|
||||
onlyActive: boolean;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { AnyObject } from '@casl/ability/dist/types/types';
|
||||
import { ITenant } from '@/interfaces';
|
||||
import { Model } from 'objection';
|
||||
import { Tenant } from '@/system/models';
|
||||
|
||||
export interface ISystemUser extends Model {
|
||||
id: number;
|
||||
@@ -9,7 +10,6 @@ export interface ISystemUser extends Model {
|
||||
active: boolean;
|
||||
password: string;
|
||||
email: string;
|
||||
phoneNumber: string;
|
||||
|
||||
roleId: number;
|
||||
tenantId: number;
|
||||
@@ -26,7 +26,6 @@ export interface ISystemUserDTO {
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
password: string;
|
||||
phoneNumber: string;
|
||||
active: boolean;
|
||||
email: string;
|
||||
roleId?: number;
|
||||
@@ -35,7 +34,6 @@ export interface ISystemUserDTO {
|
||||
export interface IEditUserDTO {
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
phoneNumber: string;
|
||||
active: boolean;
|
||||
email: string;
|
||||
roleId: number;
|
||||
@@ -44,7 +42,6 @@ export interface IEditUserDTO {
|
||||
export interface IInviteUserInput {
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
phoneNumber: string;
|
||||
password: string;
|
||||
}
|
||||
export interface IUserInvite {
|
||||
@@ -58,20 +55,52 @@ export interface IUserInvite {
|
||||
|
||||
export interface IInviteUserService {
|
||||
acceptInvite(token: string, inviteUserInput: IInviteUserInput): Promise<void>;
|
||||
|
||||
/**
|
||||
* Re-send user invite.
|
||||
* @param {number} tenantId -
|
||||
* @param {string} email -
|
||||
* @return {Promise<{ invite: IUserInvite }>}
|
||||
*/
|
||||
resendInvite(
|
||||
tenantId: number,
|
||||
userId: number,
|
||||
authorizedUser: ISystemUser
|
||||
): Promise<{
|
||||
invite: IUserInvite;
|
||||
user: ITenantUser;
|
||||
}>;
|
||||
|
||||
/**
|
||||
* Sends invite mail to the given email from the given tenant and user.
|
||||
* @param {number} tenantId -
|
||||
* @param {string} email -
|
||||
* @param {IUser} authorizedUser -
|
||||
* @return {Promise<IUserInvite>}
|
||||
*/
|
||||
sendInvite(
|
||||
tenantId: number,
|
||||
email: string,
|
||||
sendInviteDTO: IUserSendInviteDTO,
|
||||
authorizedUser: ISystemUser
|
||||
): Promise<{
|
||||
invite: IUserInvite;
|
||||
invitedUser: ITenantUser;
|
||||
}>;
|
||||
}
|
||||
|
||||
export interface IAcceptInviteUserService {
|
||||
/**
|
||||
* Accept the received invite.
|
||||
* @param {string} token
|
||||
* @param {IInviteUserInput} inviteUserInput
|
||||
* @throws {ServiceErrors}
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
acceptInvite(token: string, inviteUserDTO: IInviteUserInput): Promise<void>;
|
||||
|
||||
/**
|
||||
* Validate the given invite token.
|
||||
* @param {string} token - the given token string.
|
||||
* @throws {ServiceError}
|
||||
*/
|
||||
checkInvite(
|
||||
token: string
|
||||
): Promise<{ inviteToken: IUserInvite; orgName: object }>;
|
||||
@@ -111,7 +140,6 @@ export interface ITenantUser {
|
||||
id?: number;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
phoneNumber: string;
|
||||
active: boolean;
|
||||
email: string;
|
||||
roleId?: number;
|
||||
@@ -126,7 +154,7 @@ export interface IUserInvitedEventPayload {
|
||||
tenantId: number;
|
||||
user: ITenantUser;
|
||||
}
|
||||
export interface IUserInviteTenantSyncedEventPayload{
|
||||
export interface IUserInviteTenantSyncedEventPayload {
|
||||
invite: IUserInvite;
|
||||
authorizedUser: ISystemUser;
|
||||
tenantId: number;
|
||||
@@ -148,10 +176,10 @@ export interface IAcceptInviteEventPayload {
|
||||
|
||||
export interface ICheckInviteEventPayload {
|
||||
inviteToken: IUserInvite;
|
||||
tenant: ITenant
|
||||
tenant: Tenant;
|
||||
}
|
||||
|
||||
export interface IUserSendInviteDTO {
|
||||
email: string;
|
||||
roleId: number;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Container, Inject } from 'typedi';
|
||||
import AuthenticationService from '@/services/Authentication';
|
||||
import AuthenticationService from '@/services/Authentication/AuthApplication';
|
||||
|
||||
export default class WelcomeEmailJob {
|
||||
/**
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Container, Inject } from 'typedi';
|
||||
import InviteUserService from '@/services/InviteUsers/AcceptInviteUser';
|
||||
import SendInviteUsersMailMessage from '@/services/InviteUsers/SendInviteUsersMailMessage';
|
||||
|
||||
export default class UserInviteMailJob {
|
||||
/**
|
||||
@@ -21,24 +22,17 @@ export default class UserInviteMailJob {
|
||||
*/
|
||||
public async handler(job, done: Function): Promise<void> {
|
||||
const { invite, authorizedUser, tenantId } = job.attrs.data;
|
||||
|
||||
const Logger = Container.get('logger');
|
||||
const inviteUsersService = Container.get(InviteUserService);
|
||||
|
||||
Logger.info(`Send invite user mail - started: ${job.attrs.data}`);
|
||||
const sendInviteMailMessage = Container.get(SendInviteUsersMailMessage);
|
||||
|
||||
try {
|
||||
await inviteUsersService.mailMessages.sendInviteMail(
|
||||
await sendInviteMailMessage.sendInviteMail(
|
||||
tenantId,
|
||||
authorizedUser,
|
||||
invite
|
||||
);
|
||||
Logger.info(`Send invite user mail - finished: ${job.attrs.data}`);
|
||||
done();
|
||||
} catch (error) {
|
||||
Logger.info(
|
||||
`Send invite user mail - error: ${job.attrs.data}, error: ${error}`
|
||||
);
|
||||
console.log(error);
|
||||
done(error);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Container, Inject } from 'typedi';
|
||||
import AuthenticationService from '@/services/Authentication';
|
||||
import AuthenticationService from '@/services/Authentication/AuthApplication';
|
||||
|
||||
export default class WelcomeSMSJob {
|
||||
/**
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Container } from 'typedi';
|
||||
import AuthenticationService from '@/services/Authentication';
|
||||
import AuthenticationService from '@/services/Authentication/AuthApplication';
|
||||
|
||||
export default class WelcomeEmailJob {
|
||||
/**
|
||||
|
||||
@@ -109,7 +109,7 @@ export default class Mail {
|
||||
* Retrieve view content from the view directory.
|
||||
*/
|
||||
private getViewContent(): string {
|
||||
const filePath = path.join(global.__root_dir, `../views/${this.view}`);
|
||||
const filePath = path.join(global.__views_dir, `/${this.view}`);
|
||||
return fs.readFileSync(filePath, 'utf8');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ import moment from 'moment';
|
||||
import * as R from 'ramda';
|
||||
import { includes, isFunction, isObject, isUndefined, omit } from 'lodash';
|
||||
import { formatNumber } from 'utils';
|
||||
import { isArrayLikeObject } from 'lodash/fp';
|
||||
|
||||
export class Transformer {
|
||||
public context: any;
|
||||
@@ -39,12 +40,33 @@ export class Transformer {
|
||||
return object;
|
||||
};
|
||||
|
||||
/**
|
||||
*
|
||||
* @param object
|
||||
* @returns
|
||||
*/
|
||||
protected preCollectionTransform = (object: any) => {
|
||||
return object;
|
||||
};
|
||||
|
||||
/**
|
||||
*
|
||||
* @param object
|
||||
* @returns
|
||||
*/
|
||||
protected postCollectionTransform = (object: any) => {
|
||||
return object;
|
||||
};
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public work = (object: any) => {
|
||||
if (Array.isArray(object)) {
|
||||
return object.map(this.getTransformation);
|
||||
const preTransformed = this.preCollectionTransform(object);
|
||||
const transformed = preTransformed.map(this.getTransformation);
|
||||
|
||||
return this.postCollectionTransform(transformed);
|
||||
} else if (isObject(object)) {
|
||||
return this.getTransformation(object);
|
||||
}
|
||||
|
||||
@@ -22,9 +22,10 @@ import SaleInvoiceAutoIncrementSubscriber from '@/subscribers/SaleInvoices/AutoI
|
||||
import SaleInvoiceConvertFromEstimateSubscriber from '@/subscribers/SaleInvoices/ConvertFromEstimate';
|
||||
import PaymentReceiveAutoSerialSubscriber from '@/subscribers/PaymentReceive/AutoSerialIncrement';
|
||||
import SyncSystemSendInvite from '@/services/InviteUsers/SyncSystemSendInvite';
|
||||
import InviteSendMainNotification from '@/services/InviteUsers/InviteSendMailNotification';
|
||||
import InviteSendMainNotification from '@/services/InviteUsers/InviteSendMailNotificationSubscribe';
|
||||
import SyncTenantAcceptInvite from '@/services/InviteUsers/SyncTenantAcceptInvite';
|
||||
import SyncTenantUserMutate from '@/services/Users/SyncTenantUserSaved';
|
||||
import { SyncTenantUserDelete } from '@/services/Users/SyncTenantUserDeleted';
|
||||
import OrgSyncTenantAdminUserSubscriber from '@/subscribers/Organization/SyncTenantAdminUser';
|
||||
import OrgBuildSmsNotificationSubscriber from '@/subscribers/Organization/BuildSmsNotification';
|
||||
import PurgeUserAbilityCache from '@/services/Users/PurgeUserAbilityCache';
|
||||
@@ -113,6 +114,7 @@ export const susbcribers = () => {
|
||||
SyncTenantAcceptInvite,
|
||||
InviteSendMainNotification,
|
||||
SyncTenantUserMutate,
|
||||
SyncTenantUserDelete,
|
||||
OrgSyncTenantAdminUserSubscriber,
|
||||
OrgBuildSmsNotificationSubscriber,
|
||||
PurgeUserAbilityCache,
|
||||
|
||||
@@ -10,7 +10,7 @@ export class LedgerRevert {
|
||||
private tenancy: HasTenancyService;
|
||||
|
||||
@Inject()
|
||||
ledgerStorage: LedgerStorageService;
|
||||
private ledgerStorage: LedgerStorageService;
|
||||
|
||||
/**
|
||||
* Reverts the jouranl entries.
|
||||
|
||||
@@ -106,7 +106,7 @@ export default class AccountTransactionTransformer extends Transformer {
|
||||
* @returns {string}
|
||||
*/
|
||||
protected formattedFcCredit(transaction: IAccountTransaction) {
|
||||
return this.formatMoney(this.fcDebit(transaction), {
|
||||
return this.formatMoney(this.fcCredit(transaction), {
|
||||
currencyCode: transaction.currencyCode,
|
||||
excerptZero: true,
|
||||
});
|
||||
@@ -117,7 +117,7 @@ export default class AccountTransactionTransformer extends Transformer {
|
||||
* @returns {string}
|
||||
*/
|
||||
protected formattedFcDebit(transaction: IAccountTransaction) {
|
||||
return this.formatMoney(this.fcCredit(transaction), {
|
||||
return this.formatMoney(this.fcDebit(transaction), {
|
||||
currencyCode: transaction.currencyCode,
|
||||
excerptZero: true,
|
||||
});
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
import { IAccount } from '@/interfaces';
|
||||
import { IAccount, IAccountsStructureType } from '@/interfaces';
|
||||
import { Transformer } from '@/lib/Transformer/Transformer';
|
||||
import { formatNumber } from 'utils';
|
||||
import {
|
||||
assocDepthLevelToObjectTree,
|
||||
flatToNestedArray,
|
||||
formatNumber,
|
||||
nestedArrayToFlatten,
|
||||
} from 'utils';
|
||||
|
||||
export class AccountTransformer extends Transformer {
|
||||
/**
|
||||
@@ -8,7 +13,23 @@ export class AccountTransformer extends Transformer {
|
||||
* @returns {Array}
|
||||
*/
|
||||
public includeAttributes = (): string[] => {
|
||||
return ['formattedAmount'];
|
||||
return ['formattedAmount', 'flattenName'];
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieves the flatten name with all dependants accounts names.
|
||||
* @param {IAccount} account -
|
||||
* @returns {string}
|
||||
*/
|
||||
public flattenName = (account: IAccount): string => {
|
||||
const parentDependantsIds = this.options.accountsGraph.dependantsOf(
|
||||
account.id
|
||||
);
|
||||
const prefixAccounts = parentDependantsIds.map((dependId) => {
|
||||
const node = this.options.accountsGraph.getNodeData(dependId);
|
||||
return `${node.name}: `;
|
||||
});
|
||||
return `${prefixAccounts}${account.name}`;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -17,8 +38,28 @@ export class AccountTransformer extends Transformer {
|
||||
* @returns {string}
|
||||
*/
|
||||
protected formattedAmount = (account: IAccount): string => {
|
||||
return formatNumber(account.amount, {
|
||||
currencyCode: account.currencyCode,
|
||||
return formatNumber(account.amount, { currencyCode: account.currencyCode });
|
||||
};
|
||||
|
||||
/**
|
||||
* Transformes the accounts collection to flat or nested array.
|
||||
* @param {IAccount[]}
|
||||
* @returns {IAccount[]}
|
||||
*/
|
||||
protected postCollectionTransform = (accounts: IAccount[]) => {
|
||||
// Transfom the flatten to accounts tree.
|
||||
const transformed = flatToNestedArray(accounts, {
|
||||
id: 'id',
|
||||
parentId: 'parentAccountId',
|
||||
});
|
||||
// Associate `accountLevel` attr to indicate object depth.
|
||||
const transformed2 = assocDepthLevelToObjectTree(
|
||||
transformed,
|
||||
1,
|
||||
'accountLevel'
|
||||
);
|
||||
return this.options.structure === IAccountsStructureType.Flat
|
||||
? nestedArrayToFlatten(transformed2)
|
||||
: transformed2;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -22,15 +22,19 @@ export class GetAccount {
|
||||
*/
|
||||
public getAccount = async (tenantId: number, accountId: number) => {
|
||||
const { Account } = this.tenancy.models(tenantId);
|
||||
const { accountRepository } = this.tenancy.repositories(tenantId);
|
||||
|
||||
// Find the given account or throw not found error.
|
||||
const account = await Account.query().findById(accountId).throwIfNotFound();
|
||||
|
||||
const accountsGraph = await accountRepository.getDependencyGraph();
|
||||
|
||||
// Transformes the account model to POJO.
|
||||
const transformed = await this.transformer.transform(
|
||||
tenantId,
|
||||
account,
|
||||
new AccountTransformer()
|
||||
new AccountTransformer(),
|
||||
{ accountsGraph }
|
||||
);
|
||||
return this.i18nService.i18nApply(
|
||||
[['accountTypeLabel'], ['accountNormalFormatted']],
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
import { Inject, Service } from 'typedi';
|
||||
import * as R from 'ramda';
|
||||
import { IAccountsFilter, IAccountResponse, IFilterMeta } from '@/interfaces';
|
||||
import {
|
||||
IAccountsFilter,
|
||||
IAccountResponse,
|
||||
IFilterMeta,
|
||||
IAccountsStructureType,
|
||||
} from '@/interfaces';
|
||||
import TenancyService from '@/services/Tenancy/TenancyService';
|
||||
import DynamicListingService from '@/services/DynamicListing/DynamicListService';
|
||||
import { AccountTransformer } from './AccountTransform';
|
||||
@@ -38,6 +43,7 @@ export class GetAccounts {
|
||||
filterDTO: IAccountsFilter
|
||||
): Promise<{ accounts: IAccountResponse[]; filterMeta: IFilterMeta }> => {
|
||||
const { Account } = this.tenancy.models(tenantId);
|
||||
const { accountRepository } = this.tenancy.repositories(tenantId);
|
||||
|
||||
// Parses the stringified filter roles.
|
||||
const filter = this.parseListFilterDTO(filterDTO);
|
||||
@@ -53,17 +59,16 @@ export class GetAccounts {
|
||||
dynamicList.buildQuery()(builder);
|
||||
builder.modify('inactiveMode', filter.inactiveMode);
|
||||
});
|
||||
// Retrievs the formatted accounts collection.
|
||||
const preTransformedAccounts = await this.transformer.transform(
|
||||
|
||||
const accountsGraph = await accountRepository.getDependencyGraph();
|
||||
|
||||
// Retrieves the transformed accounts collection.
|
||||
const transformedAccounts = await this.transformer.transform(
|
||||
tenantId,
|
||||
accounts,
|
||||
new AccountTransformer()
|
||||
new AccountTransformer(),
|
||||
{ accountsGraph, structure: filterDTO.structure }
|
||||
);
|
||||
// Transform accounts to nested array.
|
||||
const transformedAccounts = flatToNestedArray(preTransformedAccounts, {
|
||||
id: 'id',
|
||||
parentId: 'parentAccountId',
|
||||
});
|
||||
|
||||
return {
|
||||
accounts: transformedAccounts,
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import { Service, Inject, Container } from 'typedi';
|
||||
import {
|
||||
IRegisterDTO,
|
||||
ISystemUser,
|
||||
IPasswordReset,
|
||||
IAuthGetMetaPOJO,
|
||||
} from '@/interfaces';
|
||||
import { AuthSigninService } from './AuthSignin';
|
||||
import { AuthSignupService } from './AuthSignup';
|
||||
import { AuthSendResetPassword } from './AuthSendResetPassword';
|
||||
import { GetAuthMeta } from './GetAuthMeta';
|
||||
|
||||
@Service()
|
||||
export default class AuthenticationApplication {
|
||||
@Inject()
|
||||
private authSigninService: AuthSigninService;
|
||||
|
||||
@Inject()
|
||||
private authSignupService: AuthSignupService;
|
||||
|
||||
@Inject()
|
||||
private authResetPasswordService: AuthSendResetPassword;
|
||||
|
||||
@Inject()
|
||||
private authGetMeta: GetAuthMeta;
|
||||
|
||||
/**
|
||||
* Signin and generates JWT token.
|
||||
* @throws {ServiceError}
|
||||
* @param {string} email - Email address.
|
||||
* @param {string} password - Password.
|
||||
* @return {Promise<{user: IUser, token: string}>}
|
||||
*/
|
||||
public async signIn(email: string, password: string) {
|
||||
return this.authSigninService.signIn(email, password);
|
||||
}
|
||||
|
||||
/**
|
||||
* Signup a new user.
|
||||
* @param {IRegisterDTO} signupDTO
|
||||
* @returns {Promise<ISystemUser>}
|
||||
*/
|
||||
public async signUp(signupDTO: IRegisterDTO): Promise<ISystemUser> {
|
||||
return this.authSignupService.signUp(signupDTO);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates and retrieve password reset token for the given user email.
|
||||
* @param {string} email
|
||||
* @return {<Promise<IPasswordReset>}
|
||||
*/
|
||||
public async sendResetPassword(email: string): Promise<IPasswordReset> {
|
||||
return this.authResetPasswordService.sendResetPassword(email);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resets a user password from given token.
|
||||
* @param {string} token - Password reset token.
|
||||
* @param {string} password - New Password.
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
public async resetPassword(token: string, password: string): Promise<void> {
|
||||
return this.authResetPasswordService.resetPassword(token, password);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the authentication meta for SPA.
|
||||
* @returns {Promise<IAuthGetMetaPOJO>}
|
||||
*/
|
||||
public async getAuthMeta(): Promise<IAuthGetMetaPOJO> {
|
||||
return this.authGetMeta.getAuthMeta();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
import { Inject, Service } from 'typedi';
|
||||
import uniqid from 'uniqid';
|
||||
import moment from 'moment';
|
||||
import config from '@/config';
|
||||
import {
|
||||
IAuthResetedPasswordEventPayload,
|
||||
IAuthSendedResetPassword,
|
||||
IAuthSendingResetPassword,
|
||||
IPasswordReset,
|
||||
ISystemUser,
|
||||
} from '@/interfaces';
|
||||
import { EventPublisher } from '@/lib/EventPublisher/EventPublisher';
|
||||
import events from '@/subscribers/events';
|
||||
import { PasswordReset } from '@/system/models';
|
||||
import { ERRORS } from './_constants';
|
||||
import { ServiceError } from '@/exceptions';
|
||||
import { hashPassword } from '@/utils';
|
||||
|
||||
@Service()
|
||||
export class AuthSendResetPassword {
|
||||
@Inject()
|
||||
private eventPublisher: EventPublisher;
|
||||
|
||||
@Inject('repositories')
|
||||
private sysRepositories: any;
|
||||
|
||||
/**
|
||||
* Generates and retrieve password reset token for the given user email.
|
||||
* @param {string} email
|
||||
* @return {<Promise<IPasswordReset>}
|
||||
*/
|
||||
public async sendResetPassword(email: string): Promise<PasswordReset> {
|
||||
const user = await this.validateEmailExistance(email);
|
||||
|
||||
const token: string = uniqid();
|
||||
|
||||
// Triggers sending reset password event.
|
||||
await this.eventPublisher.emitAsync(events.auth.sendingResetPassword, {
|
||||
user,
|
||||
token,
|
||||
} as IAuthSendingResetPassword);
|
||||
|
||||
// Delete all stored tokens of reset password that associate to the give email.
|
||||
this.deletePasswordResetToken(email);
|
||||
|
||||
// Creates a new password reset row with unique token.
|
||||
const passwordReset = await PasswordReset.query().insert({ email, token });
|
||||
|
||||
// Triggers sent reset password event.
|
||||
await this.eventPublisher.emitAsync(events.auth.sendResetPassword, {
|
||||
user,
|
||||
token,
|
||||
} as IAuthSendedResetPassword);
|
||||
|
||||
return passwordReset;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resets a user password from given token.
|
||||
* @param {string} token - Password reset token.
|
||||
* @param {string} password - New Password.
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
public async resetPassword(token: string, password: string): Promise<void> {
|
||||
const { systemUserRepository } = this.sysRepositories;
|
||||
|
||||
// Finds the password reset token.
|
||||
const tokenModel: IPasswordReset = await PasswordReset.query().findOne(
|
||||
'token',
|
||||
token
|
||||
);
|
||||
// In case the password reset token not found throw token invalid error..
|
||||
if (!tokenModel) {
|
||||
throw new ServiceError(ERRORS.TOKEN_INVALID);
|
||||
}
|
||||
// Different between tokne creation datetime and current time.
|
||||
if (
|
||||
moment().diff(tokenModel.createdAt, 'seconds') >
|
||||
config.resetPasswordSeconds
|
||||
) {
|
||||
// Deletes the expired token by expired token email.
|
||||
await this.deletePasswordResetToken(tokenModel.email);
|
||||
throw new ServiceError(ERRORS.TOKEN_EXPIRED);
|
||||
}
|
||||
const user = await systemUserRepository.findOneByEmail(tokenModel.email);
|
||||
|
||||
if (!user) {
|
||||
throw new ServiceError(ERRORS.USER_NOT_FOUND);
|
||||
}
|
||||
const hashedPassword = await hashPassword(password);
|
||||
|
||||
await systemUserRepository.update(
|
||||
{ password: hashedPassword },
|
||||
{ id: user.id }
|
||||
);
|
||||
// Deletes the used token.
|
||||
await this.deletePasswordResetToken(tokenModel.email);
|
||||
|
||||
// Triggers `onResetPassword` event.
|
||||
await this.eventPublisher.emitAsync(events.auth.resetPassword, {
|
||||
user,
|
||||
token,
|
||||
password,
|
||||
} as IAuthResetedPasswordEventPayload);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes the password reset token by the given email.
|
||||
* @param {string} email
|
||||
* @returns {Promise}
|
||||
*/
|
||||
private async deletePasswordResetToken(email: string) {
|
||||
return PasswordReset.query().where('email', email).delete();
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates the given email existance on the storage.
|
||||
* @throws {ServiceError}
|
||||
* @param {string} email - email address.
|
||||
*/
|
||||
private async validateEmailExistance(email: string): Promise<ISystemUser> {
|
||||
const { systemUserRepository } = this.sysRepositories;
|
||||
const userByEmail = await systemUserRepository.findOneByEmail(email);
|
||||
|
||||
if (!userByEmail) {
|
||||
throw new ServiceError(ERRORS.EMAIL_NOT_FOUND);
|
||||
}
|
||||
return userByEmail;
|
||||
}
|
||||
}
|
||||
103
packages/server/src/services/Authentication/AuthSignin.ts
Normal file
@@ -0,0 +1,103 @@
|
||||
import { Container, Inject } from 'typedi';
|
||||
import { cloneDeep } from 'lodash';
|
||||
import { Tenant } from '@/system/models';
|
||||
import {
|
||||
IAuthSignedInEventPayload,
|
||||
IAuthSigningInEventPayload,
|
||||
IAuthSignInPOJO,
|
||||
ISystemUser,
|
||||
} from '@/interfaces';
|
||||
import { ServiceError } from '@/exceptions';
|
||||
import events from '@/subscribers/events';
|
||||
import { EventPublisher } from '@/lib/EventPublisher/EventPublisher';
|
||||
import { generateToken } from './_utils';
|
||||
import { ERRORS } from './_constants';
|
||||
|
||||
@Inject()
|
||||
export class AuthSigninService {
|
||||
@Inject()
|
||||
private eventPublisher: EventPublisher;
|
||||
|
||||
@Inject('repositories')
|
||||
private sysRepositories: any;
|
||||
|
||||
/**
|
||||
* Validates the given email and password.
|
||||
* @param {ISystemUser} user
|
||||
* @param {string} email
|
||||
* @param {string} password
|
||||
*/
|
||||
public async validateSignIn(
|
||||
user: ISystemUser,
|
||||
email: string,
|
||||
password: string
|
||||
) {
|
||||
const loginThrottler = Container.get('rateLimiter.login');
|
||||
|
||||
// Validate if the user is not exist.
|
||||
if (!user) {
|
||||
await loginThrottler.hit(email);
|
||||
throw new ServiceError(ERRORS.INVALID_DETAILS);
|
||||
}
|
||||
// Validate if the given user's password is wrong.
|
||||
if (!user.verifyPassword(password)) {
|
||||
await loginThrottler.hit(email);
|
||||
throw new ServiceError(ERRORS.INVALID_DETAILS);
|
||||
}
|
||||
// Validate if the given user is inactive.
|
||||
if (!user.active) {
|
||||
throw new ServiceError(ERRORS.USER_INACTIVE);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Signin and generates JWT token.
|
||||
* @throws {ServiceError}
|
||||
* @param {string} email - Email address.
|
||||
* @param {string} password - Password.
|
||||
* @return {Promise<{user: IUser, token: string}>}
|
||||
*/
|
||||
public async signIn(
|
||||
email: string,
|
||||
password: string
|
||||
): Promise<IAuthSignInPOJO> {
|
||||
const { systemUserRepository } = this.sysRepositories;
|
||||
|
||||
// Finds the user of the given email address.
|
||||
const user = await systemUserRepository.findOneByEmail(email);
|
||||
|
||||
// Validate the given email and password.
|
||||
await this.validateSignIn(user, email, password);
|
||||
|
||||
// Triggers on signing-in event.
|
||||
await this.eventPublisher.emitAsync(events.auth.signingIn, {
|
||||
email,
|
||||
password,
|
||||
user,
|
||||
} as IAuthSigningInEventPayload);
|
||||
|
||||
const token = generateToken(user);
|
||||
|
||||
// Update the last login at of the user.
|
||||
await systemUserRepository.patchLastLoginAt(user.id);
|
||||
|
||||
// Triggers `onSignIn` event.
|
||||
await this.eventPublisher.emitAsync(events.auth.signIn, {
|
||||
email,
|
||||
password,
|
||||
user,
|
||||
} as IAuthSignedInEventPayload);
|
||||
|
||||
const tenant = await Tenant.query()
|
||||
.findById(user.tenantId)
|
||||
.withGraphFetched('metadata');
|
||||
|
||||
// Keep the user object immutable.
|
||||
const outputUser = cloneDeep(user);
|
||||
|
||||
// Remove password property from user object.
|
||||
Reflect.deleteProperty(outputUser, 'password');
|
||||
|
||||
return { user: outputUser, token, tenant };
|
||||
}
|
||||
}
|
||||
111
packages/server/src/services/Authentication/AuthSignup.ts
Normal file
@@ -0,0 +1,111 @@
|
||||
import { isEmpty, omit } from 'lodash';
|
||||
import moment from 'moment';
|
||||
import { ServiceError } from '@/exceptions';
|
||||
import {
|
||||
IAuthSignedUpEventPayload,
|
||||
IAuthSigningUpEventPayload,
|
||||
IRegisterDTO,
|
||||
ISystemUser,
|
||||
} from '@/interfaces';
|
||||
import { ERRORS } from './_constants';
|
||||
import { Inject } from 'typedi';
|
||||
import { EventPublisher } from '@/lib/EventPublisher/EventPublisher';
|
||||
import TenantsManagerService from '../Tenancy/TenantsManager';
|
||||
import events from '@/subscribers/events';
|
||||
import { hashPassword } from '@/utils';
|
||||
import config from '@/config';
|
||||
|
||||
export class AuthSignupService {
|
||||
@Inject()
|
||||
private eventPublisher: EventPublisher;
|
||||
|
||||
@Inject('repositories')
|
||||
private sysRepositories: any;
|
||||
|
||||
@Inject()
|
||||
private tenantsManager: TenantsManagerService;
|
||||
|
||||
/**
|
||||
* Registers a new tenant with user from user input.
|
||||
* @throws {ServiceErrors}
|
||||
* @param {IRegisterDTO} signupDTO
|
||||
* @returns {Promise<ISystemUser>}
|
||||
*/
|
||||
public async signUp(signupDTO: IRegisterDTO): Promise<ISystemUser> {
|
||||
const { systemUserRepository } = this.sysRepositories;
|
||||
|
||||
// Validates the signup disable restrictions.
|
||||
await this.validateSignupRestrictions(signupDTO.email);
|
||||
|
||||
// Validates the given email uniqiness.
|
||||
await this.validateEmailUniqiness(signupDTO.email);
|
||||
|
||||
const hashedPassword = await hashPassword(signupDTO.password);
|
||||
|
||||
// Triggers signin up event.
|
||||
await this.eventPublisher.emitAsync(events.auth.signingUp, {
|
||||
signupDTO,
|
||||
} as IAuthSigningUpEventPayload);
|
||||
|
||||
const tenant = await this.tenantsManager.createTenant();
|
||||
const registeredUser = await systemUserRepository.create({
|
||||
...omit(signupDTO, 'country'),
|
||||
active: true,
|
||||
password: hashedPassword,
|
||||
tenantId: tenant.id,
|
||||
inviteAcceptedAt: moment().format('YYYY-MM-DD'),
|
||||
});
|
||||
// Triggers signed up event.
|
||||
await this.eventPublisher.emitAsync(events.auth.signUp, {
|
||||
signupDTO,
|
||||
tenant,
|
||||
user: registeredUser,
|
||||
} as IAuthSignedUpEventPayload);
|
||||
|
||||
return registeredUser;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates email uniqiness on the storage.
|
||||
* @throws {ServiceErrors}
|
||||
* @param {string} email - Email address
|
||||
*/
|
||||
private async validateEmailUniqiness(email: string) {
|
||||
const { systemUserRepository } = this.sysRepositories;
|
||||
const isEmailExists = await systemUserRepository.findOneByEmail(email);
|
||||
|
||||
if (isEmailExists) {
|
||||
throw new ServiceError(ERRORS.EMAIL_EXISTS);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate sign-up disable restrictions.
|
||||
* @param {string} email
|
||||
*/
|
||||
private async validateSignupRestrictions(email: string) {
|
||||
// Can't continue if the signup is not disabled.
|
||||
if (!config.signupRestrictions.disabled) return;
|
||||
|
||||
// Validate the allowed email addresses and domains.
|
||||
if (
|
||||
!isEmpty(config.signupRestrictions.allowedEmails) ||
|
||||
!isEmpty(config.signupRestrictions.allowedDomains)
|
||||
) {
|
||||
const emailDomain = email.split('@').pop();
|
||||
const isAllowedEmail =
|
||||
config.signupRestrictions.allowedEmails.indexOf(email) !== -1;
|
||||
|
||||
const isAllowedDomain = config.signupRestrictions.allowedDomains.some(
|
||||
(domain) => emailDomain === domain
|
||||
);
|
||||
|
||||
if (!isAllowedEmail && !isAllowedDomain) {
|
||||
throw new ServiceError(ERRORS.SIGNUP_RESTRICTED_NOT_ALLOWED);
|
||||
}
|
||||
// Throw error if the signup is disabled with no exceptions.
|
||||
} else {
|
||||
throw new ServiceError(ERRORS.SIGNUP_RESTRICTED);
|
||||
}
|
||||
}
|
||||
}
|
||||
16
packages/server/src/services/Authentication/GetAuthMeta.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { Service } from 'typedi';
|
||||
import { IAuthGetMetaPOJO } from '@/interfaces';
|
||||
import config from '@/config';
|
||||
|
||||
@Service()
|
||||
export class GetAuthMeta {
|
||||
/**
|
||||
* Retrieves the authentication meta for SPA.
|
||||
* @returns {Promise<IAuthGetMetaPOJO>}
|
||||
*/
|
||||
public async getAuthMeta(): Promise<IAuthGetMetaPOJO> {
|
||||
return {
|
||||
signupDisabled: config.signupRestrictions.disabled,
|
||||
};
|
||||
}
|
||||
}
|
||||
12
packages/server/src/services/Authentication/_constants.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
export const ERRORS = {
|
||||
INVALID_DETAILS: 'INVALID_DETAILS',
|
||||
USER_INACTIVE: 'USER_INACTIVE',
|
||||
EMAIL_NOT_FOUND: 'EMAIL_NOT_FOUND',
|
||||
TOKEN_INVALID: 'TOKEN_INVALID',
|
||||
USER_NOT_FOUND: 'USER_NOT_FOUND',
|
||||
TOKEN_EXPIRED: 'TOKEN_EXPIRED',
|
||||
PHONE_NUMBER_EXISTS: 'PHONE_NUMBER_EXISTS',
|
||||
EMAIL_EXISTS: 'EMAIL_EXISTS',
|
||||
SIGNUP_RESTRICTED_NOT_ALLOWED: 'SIGNUP_RESTRICTED_NOT_ALLOWED',
|
||||
SIGNUP_RESTRICTED: 'SIGNUP_RESTRICTED',
|
||||
};
|
||||
22
packages/server/src/services/Authentication/_utils.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
import JWT from 'jsonwebtoken';
|
||||
import { ISystemUser } from '@/interfaces';
|
||||
import config from '@/config';
|
||||
|
||||
/**
|
||||
* Generates JWT token for the given user.
|
||||
* @param {ISystemUser} user
|
||||
* @return {string} token
|
||||
*/
|
||||
export const generateToken = (user: ISystemUser): string => {
|
||||
const today = new Date();
|
||||
const exp = new Date(today);
|
||||
exp.setDate(today.getDate() + 60);
|
||||
|
||||
return JWT.sign(
|
||||
{
|
||||
id: user.id, // We are gonna use this in the middleware 'isAuth'
|
||||
exp: exp.getTime() / 1000,
|
||||
},
|
||||
config.jwtSecret
|
||||
);
|
||||
};
|
||||
@@ -1,322 +0,0 @@
|
||||
import { Service, Inject, Container } from 'typedi';
|
||||
import JWT from 'jsonwebtoken';
|
||||
import uniqid from 'uniqid';
|
||||
import { omit, cloneDeep } from 'lodash';
|
||||
import moment from 'moment';
|
||||
import { PasswordReset, Tenant } from '@/system/models';
|
||||
import {
|
||||
IRegisterDTO,
|
||||
ITenant,
|
||||
ISystemUser,
|
||||
IPasswordReset,
|
||||
IAuthenticationService,
|
||||
} from '@/interfaces';
|
||||
import { hashPassword } from 'utils';
|
||||
import { ServiceError, ServiceErrors } from '@/exceptions';
|
||||
import config from '@/config';
|
||||
import events from '@/subscribers/events';
|
||||
import AuthenticationMailMessages from '@/services/Authentication/AuthenticationMailMessages';
|
||||
import TenantsManager from '@/services/Tenancy/TenantsManager';
|
||||
import { EventPublisher } from '@/lib/EventPublisher/EventPublisher';
|
||||
|
||||
const ERRORS = {
|
||||
INVALID_DETAILS: 'INVALID_DETAILS',
|
||||
USER_INACTIVE: 'USER_INACTIVE',
|
||||
EMAIL_NOT_FOUND: 'EMAIL_NOT_FOUND',
|
||||
TOKEN_INVALID: 'TOKEN_INVALID',
|
||||
USER_NOT_FOUND: 'USER_NOT_FOUND',
|
||||
TOKEN_EXPIRED: 'TOKEN_EXPIRED',
|
||||
PHONE_NUMBER_EXISTS: 'PHONE_NUMBER_EXISTS',
|
||||
EMAIL_EXISTS: 'EMAIL_EXISTS',
|
||||
};
|
||||
@Service()
|
||||
export default class AuthenticationService implements IAuthenticationService {
|
||||
@Inject('logger')
|
||||
logger: any;
|
||||
|
||||
@Inject()
|
||||
eventPublisher: EventPublisher;
|
||||
|
||||
@Inject()
|
||||
mailMessages: AuthenticationMailMessages;
|
||||
|
||||
@Inject('repositories')
|
||||
sysRepositories: any;
|
||||
|
||||
@Inject()
|
||||
tenantsManager: TenantsManager;
|
||||
|
||||
/**
|
||||
* Signin and generates JWT token.
|
||||
* @throws {ServiceError}
|
||||
* @param {string} emailOrPhone - Email or phone number.
|
||||
* @param {string} password - Password.
|
||||
* @return {Promise<{user: IUser, token: string}>}
|
||||
*/
|
||||
public async signIn(
|
||||
emailOrPhone: string,
|
||||
password: string
|
||||
): Promise<{
|
||||
user: ISystemUser;
|
||||
token: string;
|
||||
tenant: ITenant;
|
||||
}> {
|
||||
this.logger.info('[login] Someone trying to login.', {
|
||||
emailOrPhone,
|
||||
password,
|
||||
});
|
||||
const { systemUserRepository } = this.sysRepositories;
|
||||
const loginThrottler = Container.get('rateLimiter.login');
|
||||
|
||||
// Finds the user of the given email or phone number.
|
||||
const user = await systemUserRepository.findByCrediential(emailOrPhone);
|
||||
|
||||
if (!user) {
|
||||
// Hits the loging throttler to the given crediential.
|
||||
await loginThrottler.hit(emailOrPhone);
|
||||
|
||||
this.logger.info('[login] invalid data');
|
||||
throw new ServiceError(ERRORS.INVALID_DETAILS);
|
||||
}
|
||||
|
||||
this.logger.info('[login] check password validation.', {
|
||||
emailOrPhone,
|
||||
password,
|
||||
});
|
||||
if (!user.verifyPassword(password)) {
|
||||
// Hits the loging throttler to the given crediential.
|
||||
await loginThrottler.hit(emailOrPhone);
|
||||
|
||||
throw new ServiceError(ERRORS.INVALID_DETAILS);
|
||||
}
|
||||
if (!user.active) {
|
||||
this.logger.info('[login] user inactive.', { userId: user.id });
|
||||
throw new ServiceError(ERRORS.USER_INACTIVE);
|
||||
}
|
||||
|
||||
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,
|
||||
});
|
||||
await systemUserRepository.patchLastLoginAt(user.id);
|
||||
|
||||
this.logger.info('[login] Logging success.', { user, token });
|
||||
|
||||
// Triggers `onLogin` event.
|
||||
await this.eventPublisher.emitAsync(events.auth.login, {
|
||||
emailOrPhone,
|
||||
password,
|
||||
user,
|
||||
});
|
||||
const tenant = await Tenant.query().findById(user.tenantId).withGraphFetched('metadata');
|
||||
|
||||
// Keep the user object immutable.
|
||||
const outputUser = cloneDeep(user);
|
||||
|
||||
// Remove password property from user object.
|
||||
Reflect.deleteProperty(outputUser, 'password');
|
||||
|
||||
return { user: outputUser, token, tenant };
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates email and phone number uniqiness on the storage.
|
||||
* @throws {ServiceErrors}
|
||||
* @param {IRegisterDTO} registerDTO - Register data object.
|
||||
*/
|
||||
private async validateEmailAndPhoneUniqiness(registerDTO: IRegisterDTO) {
|
||||
const { systemUserRepository } = this.sysRepositories;
|
||||
|
||||
const isEmailExists = await systemUserRepository.findOneByEmail(
|
||||
registerDTO.email
|
||||
);
|
||||
const isPhoneExists = await systemUserRepository.findOneByPhoneNumber(
|
||||
registerDTO.phoneNumber
|
||||
);
|
||||
const errorReasons: ServiceError[] = [];
|
||||
|
||||
if (isPhoneExists) {
|
||||
this.logger.info('[register] phone number exists on the storage.');
|
||||
errorReasons.push(new ServiceError(ERRORS.PHONE_NUMBER_EXISTS));
|
||||
}
|
||||
if (isEmailExists) {
|
||||
this.logger.info('[register] email exists on the storage.');
|
||||
errorReasons.push(new ServiceError(ERRORS.EMAIL_EXISTS));
|
||||
}
|
||||
if (errorReasons.length > 0) {
|
||||
throw new ServiceErrors(errorReasons);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a new tenant with user from user input.
|
||||
* @throws {ServiceErrors}
|
||||
* @param {IUserDTO} user
|
||||
*/
|
||||
public async register(registerDTO: IRegisterDTO): Promise<ISystemUser> {
|
||||
this.logger.info('[register] Someone trying to register.');
|
||||
await this.validateEmailAndPhoneUniqiness(registerDTO);
|
||||
|
||||
this.logger.info('[register] Creating a new tenant organization.');
|
||||
const tenant = await this.newTenantOrganization();
|
||||
|
||||
this.logger.info('[register] Trying hashing the password.');
|
||||
const hashedPassword = await hashPassword(registerDTO.password);
|
||||
|
||||
const { systemUserRepository } = this.sysRepositories;
|
||||
const registeredUser = await systemUserRepository.create({
|
||||
...omit(registerDTO, 'country'),
|
||||
active: true,
|
||||
password: hashedPassword,
|
||||
tenantId: tenant.id,
|
||||
inviteAcceptedAt: moment().format('YYYY-MM-DD'),
|
||||
});
|
||||
// Triggers `onRegister` event.
|
||||
await this.eventPublisher.emitAsync(events.auth.register, {
|
||||
registerDTO,
|
||||
tenant,
|
||||
user: registeredUser,
|
||||
});
|
||||
return registeredUser;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates and insert new tenant organization id.
|
||||
* @async
|
||||
* @return {Promise<ITenant>}
|
||||
*/
|
||||
private async newTenantOrganization(): Promise<ITenant> {
|
||||
return this.tenantsManager.createTenant();
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate the given email existance on the storage.
|
||||
* @throws {ServiceError}
|
||||
* @param {string} email - email address.
|
||||
*/
|
||||
private async validateEmailExistance(email: string): Promise<ISystemUser> {
|
||||
const { systemUserRepository } = this.sysRepositories;
|
||||
const userByEmail = await systemUserRepository.findOneByEmail(email);
|
||||
|
||||
if (!userByEmail) {
|
||||
this.logger.info('[send_reset_password] The given email not found.');
|
||||
throw new ServiceError(ERRORS.EMAIL_NOT_FOUND);
|
||||
}
|
||||
return userByEmail;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates and retrieve password reset token for the given user email.
|
||||
* @param {string} email
|
||||
* @return {<Promise<IPasswordReset>}
|
||||
*/
|
||||
public async sendResetPassword(email: string): Promise<IPasswordReset> {
|
||||
this.logger.info('[send_reset_password] Trying to send reset password.');
|
||||
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.deletePasswordResetToken(email);
|
||||
|
||||
const token: string = uniqid();
|
||||
|
||||
this.logger.info('[send_reset_password] insert the generated token.');
|
||||
const passwordReset = await PasswordReset.query().insert({ email, token });
|
||||
|
||||
// Triggers `onSendResetPassword` event.
|
||||
await this.eventPublisher.emitAsync(events.auth.sendResetPassword, {
|
||||
user,
|
||||
token,
|
||||
});
|
||||
return passwordReset;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resets a user password from given token.
|
||||
* @param {string} token - Password reset token.
|
||||
* @param {string} password - New Password.
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
public async resetPassword(token: string, password: string): Promise<void> {
|
||||
const { systemUserRepository } = this.sysRepositories;
|
||||
|
||||
// Finds the password reset token.
|
||||
const tokenModel: IPasswordReset = await PasswordReset.query().findOne(
|
||||
'token',
|
||||
token
|
||||
);
|
||||
// In case the password reset token not found throw token invalid error..
|
||||
if (!tokenModel) {
|
||||
this.logger.info('[reset_password] token invalid.');
|
||||
throw new ServiceError(ERRORS.TOKEN_INVALID);
|
||||
}
|
||||
// Different between tokne creation datetime and current time.
|
||||
if (
|
||||
moment().diff(tokenModel.createdAt, 'seconds') >
|
||||
config.resetPasswordSeconds
|
||||
) {
|
||||
this.logger.info('[reset_password] token expired.');
|
||||
|
||||
// Deletes the expired token by expired token email.
|
||||
await this.deletePasswordResetToken(tokenModel.email);
|
||||
throw new ServiceError(ERRORS.TOKEN_EXPIRED);
|
||||
}
|
||||
const user = await systemUserRepository.findOneByEmail(tokenModel.email);
|
||||
|
||||
if (!user) {
|
||||
throw new ServiceError(ERRORS.USER_NOT_FOUND);
|
||||
}
|
||||
const hashedPassword = await hashPassword(password);
|
||||
|
||||
this.logger.info('[reset_password] saving a new hashed password.');
|
||||
await systemUserRepository.update(
|
||||
{ password: hashedPassword },
|
||||
{ id: user.id }
|
||||
);
|
||||
|
||||
// Deletes the used token.
|
||||
await this.deletePasswordResetToken(tokenModel.email);
|
||||
|
||||
// Triggers `onResetPassword` event.
|
||||
await this.eventPublisher.emitAsync(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
|
||||
* @returns {Promise}
|
||||
*/
|
||||
private async deletePasswordResetToken(email: string) {
|
||||
this.logger.info('[reset_password] trying to delete all tokens by email.');
|
||||
return PasswordReset.query().where('email', email).delete();
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates JWT token for the given user.
|
||||
* @param {ISystemUser} user
|
||||
* @return {string} token
|
||||
*/
|
||||
generateToken(user: ISystemUser): string {
|
||||
const today = new Date();
|
||||
const exp = new Date(today);
|
||||
exp.setDate(today.getDate() + 60);
|
||||
|
||||
this.logger.silly(`Sign JWT for userId: ${user.id}`);
|
||||
return JWT.sign(
|
||||
{
|
||||
id: user.id, // We are gonna use this in the middleware 'isAuth'
|
||||
exp: exp.getTime() / 1000,
|
||||
},
|
||||
config.jwtSecret
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -5,18 +5,13 @@ import {
|
||||
ICreditNoteDeletedPayload,
|
||||
ICreditNoteEditedPayload,
|
||||
ICreditNoteOpenedPayload,
|
||||
IRefundCreditNoteOpenedPayload,
|
||||
} from '@/interfaces';
|
||||
import CreditNoteGLEntries from './CreditNoteGLEntries';
|
||||
import HasTenancyService from '@/services/Tenancy/TenancyService';
|
||||
|
||||
@Service()
|
||||
export default class CreditNoteGLEntriesSubscriber {
|
||||
@Inject()
|
||||
creditNoteGLEntries: CreditNoteGLEntries;
|
||||
|
||||
@Inject()
|
||||
tenancy: HasTenancyService;
|
||||
private creditNoteGLEntries: CreditNoteGLEntries;
|
||||
|
||||
/**
|
||||
* Attaches events with handlers.
|
||||
|
||||
@@ -1,18 +1,15 @@
|
||||
import { Inject, Service } from 'typedi';
|
||||
import { uniq } from 'lodash';
|
||||
|
||||
import {
|
||||
ICurrencyEditDTO,
|
||||
ICurrencyDTO,
|
||||
ICurrenciesService,
|
||||
ICurrency,
|
||||
} from '@/interfaces';
|
||||
import {
|
||||
EventDispatcher,
|
||||
EventDispatcherInterface,
|
||||
} from 'decorators/eventDispatcher';
|
||||
import { ServiceError } from '@/exceptions';
|
||||
import TenancyService from '@/services/Tenancy/TenancyService';
|
||||
import { Tenant } from '@/system/models';
|
||||
import { TransformerInjectable } from '@/lib/Transformer/TransformerInjectable';
|
||||
import { CurrencyTransformer } from './CurrencyTransformer';
|
||||
|
||||
const ERRORS = {
|
||||
CURRENCY_NOT_FOUND: 'currency_not_found',
|
||||
@@ -23,14 +20,11 @@ const ERRORS = {
|
||||
|
||||
@Service()
|
||||
export default class CurrenciesService implements ICurrenciesService {
|
||||
@Inject('logger')
|
||||
logger: any;
|
||||
|
||||
@EventDispatcher()
|
||||
eventDispatcher: EventDispatcherInterface;
|
||||
@Inject()
|
||||
private tenancy: TenancyService;
|
||||
|
||||
@Inject()
|
||||
tenancy: TenancyService;
|
||||
private transformer: TransformerInjectable;
|
||||
|
||||
/**
|
||||
* Retrieve currency by given currency code or throw not found error.
|
||||
@@ -105,7 +99,7 @@ export default class CurrenciesService implements ICurrenciesService {
|
||||
*/
|
||||
public async newCurrency(tenantId: number, currencyDTO: ICurrencyDTO) {
|
||||
const { Currency } = this.tenancy.models(tenantId);
|
||||
|
||||
|
||||
// Validate currency code uniquiness.
|
||||
await this.validateCurrencyCodeUniquiness(
|
||||
tenantId,
|
||||
@@ -141,13 +135,15 @@ export default class CurrenciesService implements ICurrenciesService {
|
||||
* @param {number} tenantId
|
||||
* @param {string} currencyCode
|
||||
*/
|
||||
validateCannotDeleteBaseCurrency(tenantId: number, currencyCode: string) {
|
||||
const settings = this.tenancy.settings(tenantId);
|
||||
const baseCurrency = settings.get({
|
||||
group: 'organization',
|
||||
key: 'base_currency',
|
||||
});
|
||||
if (baseCurrency === currencyCode) {
|
||||
private async validateCannotDeleteBaseCurrency(
|
||||
tenantId: number,
|
||||
currencyCode: string
|
||||
) {
|
||||
const tenant = await Tenant.query()
|
||||
.findById(tenantId)
|
||||
.withGraphFetched('metadata');
|
||||
|
||||
if (tenant.metadata.baseCurrency === currencyCode) {
|
||||
throw new ServiceError(ERRORS.CANNOT_DELETE_BASE_CURRENCY);
|
||||
}
|
||||
}
|
||||
@@ -156,7 +152,7 @@ export default class CurrenciesService implements ICurrenciesService {
|
||||
* Delete the given currency code.
|
||||
* @param {number} tenantId
|
||||
* @param {string} currencyCode
|
||||
* @return {Promise<}
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
public async deleteCurrency(
|
||||
tenantId: number,
|
||||
@@ -180,19 +176,13 @@ export default class CurrenciesService implements ICurrenciesService {
|
||||
public async listCurrencies(tenantId: number): Promise<ICurrency[]> {
|
||||
const { Currency } = this.tenancy.models(tenantId);
|
||||
|
||||
const settings = this.tenancy.settings(tenantId);
|
||||
const baseCurrency = settings.get({
|
||||
group: 'organization',
|
||||
key: 'base_currency',
|
||||
});
|
||||
|
||||
const currencies = await Currency.query().onBuild((query) => {
|
||||
query.orderBy('createdAt', 'ASC');
|
||||
});
|
||||
const formattedCurrencies = currencies.map((currency) => ({
|
||||
isBaseCurrency: baseCurrency === currency.currencyCode,
|
||||
...currency,
|
||||
}));
|
||||
return formattedCurrencies;
|
||||
return this.transformer.transform(
|
||||
tenantId,
|
||||
currencies,
|
||||
new CurrencyTransformer()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import { Transformer } from '@/lib/Transformer/Transformer';
|
||||
|
||||
export class CurrencyTransformer extends Transformer {
|
||||
/**
|
||||
* Include these attributes to sale invoice object.
|
||||
* @returns {Array}
|
||||
*/
|
||||
public includeAttributes = (): string[] => {
|
||||
return ['isBaseCurrency'];
|
||||
};
|
||||
|
||||
/**
|
||||
* Detarmines whether the currency is base currency.
|
||||
* @returns {boolean}
|
||||
*/
|
||||
public isBaseCurrency(currency): boolean {
|
||||
return this.context.organization.baseCurrency === currency.currencyCode;
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,7 @@ import { ICashflowAccountTransactionsQuery, IPaginationMeta } from '@/interfaces
|
||||
@Service()
|
||||
export default class CashflowAccountTransactionsRepo {
|
||||
@Inject()
|
||||
tenancy: HasTenancyService;
|
||||
private tenancy: HasTenancyService;
|
||||
|
||||
/**
|
||||
* Retrieve the cashflow account transactions.
|
||||
|
||||
@@ -17,7 +17,7 @@ export const getDefaultPLQuery = (): IProfitLossSheetQuery => ({
|
||||
formatMoney: 'total',
|
||||
precision: 2,
|
||||
},
|
||||
basis: 'accural',
|
||||
basis: 'accrual',
|
||||
|
||||
noneZero: false,
|
||||
noneTransactions: false,
|
||||
|
||||
@@ -35,7 +35,7 @@ export default class TrialBalanceSheetService extends FinancialSheet {
|
||||
formatMoney: 'total',
|
||||
precision: 2,
|
||||
},
|
||||
basis: 'accural',
|
||||
basis: 'accrual',
|
||||
noneZero: false,
|
||||
noneTransactions: true,
|
||||
onlyActive: false,
|
||||
|
||||
@@ -3,8 +3,6 @@ import moment from 'moment';
|
||||
import { ServiceError } from '@/exceptions';
|
||||
import { Invite, SystemUser, Tenant } from '@/system/models';
|
||||
import { hashPassword } from 'utils';
|
||||
import TenancyService from '@/services/Tenancy/TenancyService';
|
||||
import InviteUsersMailMessages from '@/services/InviteUsers/InviteUsersMailMessages';
|
||||
import events from '@/subscribers/events';
|
||||
import {
|
||||
IAcceptInviteEventPayload,
|
||||
@@ -12,29 +10,16 @@ import {
|
||||
ICheckInviteEventPayload,
|
||||
IUserInvite,
|
||||
} from '@/interfaces';
|
||||
import TenantsManagerService from '@/services/Tenancy/TenantsManager';
|
||||
import { ERRORS } from './constants';
|
||||
import { EventPublisher } from '@/lib/EventPublisher/EventPublisher';
|
||||
import { IAcceptInviteUserService } from '@/interfaces';
|
||||
|
||||
@Service()
|
||||
export default class AcceptInviteUserService {
|
||||
export default class AcceptInviteUserService
|
||||
implements IAcceptInviteUserService
|
||||
{
|
||||
@Inject()
|
||||
eventPublisher: EventPublisher;
|
||||
|
||||
@Inject()
|
||||
tenancy: TenancyService;
|
||||
|
||||
@Inject('logger')
|
||||
logger: any;
|
||||
|
||||
@Inject()
|
||||
mailMessages: InviteUsersMailMessages;
|
||||
|
||||
@Inject('repositories')
|
||||
sysRepositories: any;
|
||||
|
||||
@Inject()
|
||||
tenantsManager: TenantsManagerService;
|
||||
private eventPublisher: EventPublisher;
|
||||
|
||||
/**
|
||||
* Accept the received invite.
|
||||
@@ -50,9 +35,6 @@ export default class AcceptInviteUserService {
|
||||
// Retrieve the invite token or throw not found error.
|
||||
const inviteToken = await this.getInviteTokenOrThrowError(token);
|
||||
|
||||
// Validates the user phone number.
|
||||
await this.validateUserPhoneNumberNotExists(inviteUserDTO.phoneNumber);
|
||||
|
||||
// Hash the given password.
|
||||
const hashedPassword = await hashPassword(inviteUserDTO.password);
|
||||
|
||||
|
||||
@@ -1,14 +1,11 @@
|
||||
import {
|
||||
IUserInvitedEventPayload,
|
||||
IUserInviteTenantSyncedEventPayload,
|
||||
} from '@/interfaces';
|
||||
import { IUserInviteTenantSyncedEventPayload } from '@/interfaces';
|
||||
import events from '@/subscribers/events';
|
||||
import { Inject, Service } from 'typedi';
|
||||
|
||||
@Service()
|
||||
export default class InviteSendMainNotificationSubscribe {
|
||||
@Inject('agenda')
|
||||
agenda: any;
|
||||
private agenda: any;
|
||||
|
||||
/**
|
||||
* Attaches events with handlers.
|
||||
@@ -1,12 +1,12 @@
|
||||
import path from 'path';
|
||||
import { ISystemUser } from '@/interfaces';
|
||||
import TenancyService from '@/services/Tenancy/TenancyService';
|
||||
import Mail from '@/lib/Mail';
|
||||
import { Service, Container } from 'typedi';
|
||||
import config from '@/config';
|
||||
import { Service } from 'typedi';
|
||||
import { Tenant } from '@/system/models';
|
||||
import config from '@/config';
|
||||
|
||||
@Service()
|
||||
export default class InviteUsersMailMessages {
|
||||
export default class SendInviteUsersMailMessage {
|
||||
/**
|
||||
* Sends invite mail to the given email.
|
||||
* @param user
|
||||
@@ -18,7 +18,7 @@ export default class InviteUsersMailMessages {
|
||||
.findById(tenantId)
|
||||
.withGraphFetched('metadata');
|
||||
|
||||
const root = __dirname + '/../../../views/images/bigcapital.png';
|
||||
const root = path.join(global.__views_dir, '/images/bigcapital.png');
|
||||
|
||||
const mail = new Mail()
|
||||
.setSubject(`${fromUser.firstName} has invited you to join a Bigcapital`)
|
||||
@@ -8,7 +8,7 @@ import { IAcceptInviteEventPayload } from '@/interfaces';
|
||||
@Service()
|
||||
export default class SyncTenantAcceptInvite {
|
||||
@Inject()
|
||||
tenancy: HasTenancyService;
|
||||
private tenancy: HasTenancyService;
|
||||
|
||||
/**
|
||||
* Attaches events with handlers.
|
||||
|
||||
@@ -3,7 +3,6 @@ import uniqid from 'uniqid';
|
||||
import moment from 'moment';
|
||||
import { ServiceError } from '@/exceptions';
|
||||
import TenancyService from '@/services/Tenancy/TenancyService';
|
||||
import InviteUsersMailMessages from '@/services/InviteUsers/InviteUsersMailMessages';
|
||||
import events from '@/subscribers/events';
|
||||
import {
|
||||
ISystemUser,
|
||||
@@ -13,7 +12,6 @@ import {
|
||||
IUserInvitedEventPayload,
|
||||
IUserInviteResendEventPayload,
|
||||
} from '@/interfaces';
|
||||
import TenantsManagerService from '@/services/Tenancy/TenantsManager';
|
||||
import { ERRORS } from './constants';
|
||||
import { EventPublisher } from '@/lib/EventPublisher/EventPublisher';
|
||||
import RolesService from '@/services/Roles/RolesService';
|
||||
@@ -21,25 +19,13 @@ import RolesService from '@/services/Roles/RolesService';
|
||||
@Service()
|
||||
export default class InviteTenantUserService implements IInviteUserService {
|
||||
@Inject()
|
||||
eventPublisher: EventPublisher;
|
||||
private eventPublisher: EventPublisher;
|
||||
|
||||
@Inject()
|
||||
tenancy: TenancyService;
|
||||
|
||||
@Inject('logger')
|
||||
logger: any;
|
||||
private tenancy: TenancyService;
|
||||
|
||||
@Inject()
|
||||
mailMessages: InviteUsersMailMessages;
|
||||
|
||||
@Inject('repositories')
|
||||
sysRepositories: any;
|
||||
|
||||
@Inject()
|
||||
tenantsManager: TenantsManagerService;
|
||||
|
||||
@Inject()
|
||||
rolesService: RolesService;
|
||||
private rolesService: RolesService;
|
||||
|
||||
/**
|
||||
* Sends invite mail to the given email from the given tenant and user.
|
||||
@@ -88,19 +74,15 @@ export default class InviteTenantUserService implements IInviteUserService {
|
||||
|
||||
/**
|
||||
* Re-send user invite.
|
||||
* @param {number} tenantId -
|
||||
* @param {string} email -
|
||||
* @param {number} tenantId -
|
||||
* @param {string} email -
|
||||
* @return {Promise<{ invite: IUserInvite }>}
|
||||
*/
|
||||
public async resendInvite(
|
||||
tenantId: number,
|
||||
userId: number,
|
||||
authorizedUser: ISystemUser
|
||||
): Promise<{
|
||||
user: ITenantUser;
|
||||
}> {
|
||||
const { User } = this.tenancy.models(tenantId);
|
||||
|
||||
): Promise<{ user: ITenantUser }> {
|
||||
// Retrieve the user by id or throw not found service error.
|
||||
const user = await this.getUserByIdOrThrowError(tenantId, userId);
|
||||
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
import { difference, sumBy, omit, map } from 'lodash';
|
||||
import { difference } from 'lodash';
|
||||
import { Service, Inject } from 'typedi';
|
||||
import { ServiceError } from '@/exceptions';
|
||||
import {
|
||||
IManualJournalDTO,
|
||||
IManualJournalEntry,
|
||||
IManualJournal,
|
||||
IManualJournalEntryDTO,
|
||||
} from '@/interfaces';
|
||||
import TenancyService from '@/services/Tenancy/TenancyService';
|
||||
import { ERRORS } from './constants';
|
||||
@@ -286,7 +285,7 @@ export class CommandManualJournalValidators {
|
||||
public validateJournalCurrencyWithAccountsCurrency = async (
|
||||
tenantId: number,
|
||||
manualJournalDTO: IManualJournalDTO,
|
||||
baseCurrency: string,
|
||||
baseCurrency: string
|
||||
) => {
|
||||
const { Account } = this.tenancy.models(tenantId);
|
||||
|
||||
|
||||
@@ -3,25 +3,20 @@ import * as R from 'ramda';
|
||||
import {
|
||||
IManualJournal,
|
||||
IManualJournalEntry,
|
||||
IAccount,
|
||||
ILedgerEntry,
|
||||
} from '@/interfaces';
|
||||
import { Knex } from 'knex';
|
||||
import Ledger from '@/services/Accounting/Ledger';
|
||||
import LedgerStorageService from '@/services/Accounting/LedgerStorageService';
|
||||
import HasTenancyService from '@/services/Tenancy/TenancyService';
|
||||
import { LedgerRevert } from '@/services/Accounting/LedgerStorageRevert';
|
||||
|
||||
@Service()
|
||||
export class ManualJournalGLEntries {
|
||||
@Inject()
|
||||
ledgerStorage: LedgerStorageService;
|
||||
private ledgerStorage: LedgerStorageService;
|
||||
|
||||
@Inject()
|
||||
ledgerRevert: LedgerRevert;
|
||||
|
||||
@Inject()
|
||||
tenancy: HasTenancyService;
|
||||
private tenancy: HasTenancyService;
|
||||
|
||||
/**
|
||||
* Create manual journal GL entries.
|
||||
@@ -77,7 +72,7 @@ export class ManualJournalGLEntries {
|
||||
manualJournalId: number,
|
||||
trx?: Knex.Transaction
|
||||
): Promise<void> => {
|
||||
return this.ledgerRevert.revertGLEntries(
|
||||
return this.ledgerStorage.deleteByReference(
|
||||
tenantId,
|
||||
manualJournalId,
|
||||
'Journal',
|
||||
@@ -86,7 +81,7 @@ export class ManualJournalGLEntries {
|
||||
};
|
||||
|
||||
/**
|
||||
*
|
||||
* Retrieves the ledger of the given manual journal.
|
||||
* @param {IManualJournal} manualJournal
|
||||
* @returns {Ledger}
|
||||
*/
|
||||
@@ -97,11 +92,13 @@ export class ManualJournalGLEntries {
|
||||
};
|
||||
|
||||
/**
|
||||
*
|
||||
* Retrieves the common entry details of the manual journal
|
||||
* @param {IManualJournal} manualJournal
|
||||
* @returns {}
|
||||
* @returns {Partial<ILedgerEntry>}
|
||||
*/
|
||||
private getManualJournalCommonEntry = (manualJournal: IManualJournal) => {
|
||||
private getManualJournalCommonEntry = (
|
||||
manualJournal: IManualJournal
|
||||
): Partial<ILedgerEntry> => {
|
||||
return {
|
||||
transactionNumber: manualJournal.journalNumber,
|
||||
referenceNumber: manualJournal.reference,
|
||||
@@ -118,7 +115,8 @@ export class ManualJournalGLEntries {
|
||||
};
|
||||
|
||||
/**
|
||||
*
|
||||
* Retrieves the ledger entry of the given manual journal and
|
||||
* its associated entry.
|
||||
* @param {IManualJournal} manualJournal -
|
||||
* @param {IManualJournalEntry} entry -
|
||||
* @returns {ILedgerEntry}
|
||||
@@ -149,7 +147,7 @@ export class ManualJournalGLEntries {
|
||||
);
|
||||
|
||||
/**
|
||||
*
|
||||
* Retrieves the ledger of the given manual journal.
|
||||
* @param {IManualJournal} manualJournal
|
||||
* @returns {ILedgerEntry[]}
|
||||
*/
|
||||
|
||||
@@ -14,8 +14,6 @@ export const DATE_FORMATS = [
|
||||
'MMMM dd, YYYY',
|
||||
'EEE, MMMM dd, YYYY',
|
||||
];
|
||||
export const ACCEPTED_CURRENCIES = Object.keys(currencies);
|
||||
|
||||
export const MONTHS = [
|
||||
'january',
|
||||
'february',
|
||||
|
||||
@@ -23,8 +23,11 @@ export class ProjectBillableBillSubscriber {
|
||||
events.saleInvoice.onCreated,
|
||||
this.handleIncreaseBillableBill
|
||||
);
|
||||
bus.subscribe(events.saleInvoice.onEdited, this.handleDecreaseBillableBill);
|
||||
bus.subscribe(events.saleInvoice.onDeleted, this.handleEditBillableBill);
|
||||
bus.subscribe(events.saleInvoice.onEdited, this.handleEditBillableBill);
|
||||
bus.subscribe(
|
||||
events.saleInvoice.onDeleted,
|
||||
this.handleDecreaseBillableBill
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
import { Knex } from 'knex';
|
||||
import { Inject, Service } from 'typedi';
|
||||
import async from 'async';
|
||||
import { ISaleInvoice, ISaleInvoiceDTO, ProjectLinkRefType } from '@/interfaces';
|
||||
import {
|
||||
ISaleInvoice,
|
||||
ISaleInvoiceDTO,
|
||||
ProjectLinkRefType,
|
||||
} from '@/interfaces';
|
||||
import { ProjectBillableExpense } from './ProjectBillableExpense';
|
||||
import { filterEntriesByRefType } from './_utils';
|
||||
|
||||
|
||||
@@ -21,13 +21,10 @@ export class ProjectBillableExpensesSubscriber {
|
||||
events.saleInvoice.onCreated,
|
||||
this.handleIncreaseBillableExpenses
|
||||
);
|
||||
bus.subscribe(
|
||||
events.saleInvoice.onEdited,
|
||||
this.handleDecreaseBillableExpenses
|
||||
);
|
||||
bus.subscribe(events.saleInvoice.onEdited, this.handleEditBillableExpenses);
|
||||
bus.subscribe(
|
||||
events.saleInvoice.onDeleted,
|
||||
this.handleEditBillableExpenses
|
||||
this.handleDecreaseBillableExpenses
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -10,18 +10,18 @@ export class RoleTransformer extends Transformer {
|
||||
};
|
||||
|
||||
/**
|
||||
*
|
||||
* Retrieves the localized role name if is predefined or stored name.
|
||||
* @param role
|
||||
* @returns
|
||||
* @returns {string}
|
||||
*/
|
||||
public name(role) {
|
||||
return role.predefined ? this.context.i18n.__(role.name) : role.name;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* Retrieves the localized role description if is predefined or stored description.
|
||||
* @param role
|
||||
* @returns
|
||||
* @returns {string}
|
||||
*/
|
||||
public description(role) {
|
||||
return role.predefined
|
||||
|
||||
26
packages/server/src/services/Users/SyncTenantUserDeleted.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
import events from '@/subscribers/events';
|
||||
import { ITenantUserDeletedPayload } from '@/interfaces';
|
||||
import { SystemUser } from '@/system/models';
|
||||
|
||||
export class SyncTenantUserDelete {
|
||||
/**
|
||||
* Attaches events with handlers.
|
||||
* @param bus
|
||||
*/
|
||||
public attach(bus) {
|
||||
bus.subscribe(
|
||||
events.tenantUser.onDeleted,
|
||||
this.syncSystemUserOnceUserDeleted
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes the system user once tenant user be deleted.
|
||||
* @param {ITenantUserDeletedPayload} payload -
|
||||
*/
|
||||
private syncSystemUserOnceUserDeleted = async ({
|
||||
tenantUser,
|
||||
}: ITenantUserDeletedPayload) => {
|
||||
await SystemUser.query().where('id', tenantUser.systemUserId).delete();
|
||||
};
|
||||
}
|
||||
50
packages/server/src/services/Users/UserTransformer.ts
Normal file
@@ -0,0 +1,50 @@
|
||||
import { Transformer } from '@/lib/Transformer/Transformer';
|
||||
|
||||
export class UserTransformer extends Transformer {
|
||||
/**
|
||||
* Exclude these attributes from user object.
|
||||
* @returns {Array}
|
||||
*/
|
||||
public excludeAttributes = (): string[] => {
|
||||
return ['role'];
|
||||
};
|
||||
|
||||
/**
|
||||
* Includeded attributes.
|
||||
* @returns {string[]}
|
||||
*/
|
||||
public includeAttributes = (): string[] => {
|
||||
return ['roleName', 'roleDescription', 'roleSlug'];
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieves the localized role name if is predefined or stored name.
|
||||
* @param role
|
||||
* @returns {string}
|
||||
*/
|
||||
public roleName(user) {
|
||||
return user.role.predefined
|
||||
? this.context.i18n.__(user.role.name)
|
||||
: user.role.name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the localized role description if is predefined or stored description.
|
||||
* @param user
|
||||
* @returns {string}
|
||||
*/
|
||||
public roleDescription(user) {
|
||||
return user.role.predefined
|
||||
? this.context.i18n.__(user.role.description)
|
||||
: user.role.description;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the role slug.
|
||||
* @param user
|
||||
* @returns {string}
|
||||
*/
|
||||
public roleSlug(user) {
|
||||
return user.role.slug;
|
||||
}
|
||||
}
|
||||
@@ -14,23 +14,22 @@ import RolesService from '@/services/Roles/RolesService';
|
||||
import HasTenancyService from '@/services/Tenancy/TenancyService';
|
||||
import { ERRORS } from './constants';
|
||||
import { EventPublisher } from '@/lib/EventPublisher/EventPublisher';
|
||||
import { TransformerInjectable } from '@/lib/Transformer/TransformerInjectable';
|
||||
import { UserTransformer } from './UserTransformer';
|
||||
|
||||
@Service()
|
||||
export default class UsersService {
|
||||
@Inject('logger')
|
||||
logger: any;
|
||||
|
||||
@Inject('repositories')
|
||||
repositories: any;
|
||||
@Inject()
|
||||
private rolesService: RolesService;
|
||||
|
||||
@Inject()
|
||||
rolesService: RolesService;
|
||||
private tenancy: HasTenancyService;
|
||||
|
||||
@Inject()
|
||||
tenancy: HasTenancyService;
|
||||
private eventPublisher: EventPublisher;
|
||||
|
||||
@Inject()
|
||||
eventPublisher: EventPublisher;
|
||||
private transformer: TransformerInjectable;
|
||||
|
||||
/**
|
||||
* Creates a new user.
|
||||
@@ -46,7 +45,7 @@ export default class UsersService {
|
||||
authorizedUser: ISystemUser
|
||||
): Promise<any> {
|
||||
const { User } = this.tenancy.models(tenantId);
|
||||
const { email, phoneNumber } = editUserDTO;
|
||||
const { email } = editUserDTO;
|
||||
|
||||
// Retrieve the tenant user or throw not found service error.
|
||||
const oldTenantUser = await this.getTenantUserOrThrowError(
|
||||
@@ -62,9 +61,6 @@ export default class UsersService {
|
||||
// Validate user email should be unique.
|
||||
await this.validateUserEmailUniquiness(tenantId, email, userId);
|
||||
|
||||
// Validate user phone number should be unique.
|
||||
await this.validateUserPhoneNumberUniqiness(tenantId, phoneNumber, userId);
|
||||
|
||||
// Retrieve the given role or throw not found service error.
|
||||
const role = await this.rolesService.getRoleOrThrowError(
|
||||
tenantId,
|
||||
@@ -97,9 +93,10 @@ export default class UsersService {
|
||||
// Retrieve user details or throw not found service error.
|
||||
const tenantUser = await this.getTenantUserOrThrowError(tenantId, userId);
|
||||
|
||||
// Validate the delete user should not be the last user.
|
||||
await this.validateNotLastUserDelete(tenantId);
|
||||
|
||||
// Validate the delete user should not be the last active user.
|
||||
if (tenantUser.isInviteAccepted) {
|
||||
await this.validateNotLastUserDelete(tenantId);
|
||||
}
|
||||
// Delete user from the storage.
|
||||
await User.query().findById(userId).delete();
|
||||
|
||||
@@ -189,7 +186,7 @@ export default class UsersService {
|
||||
|
||||
const users = await User.query().withGraphFetched('role');
|
||||
|
||||
return users;
|
||||
return this.transformer.transform(tenantId, users, new UserTransformer());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -229,11 +226,13 @@ export default class UsersService {
|
||||
* @param {number} tenantId
|
||||
*/
|
||||
private async validateNotLastUserDelete(tenantId: number) {
|
||||
const { systemUserRepository } = this.repositories;
|
||||
const { User } = this.tenancy.models(tenantId);
|
||||
|
||||
const usersFound = await systemUserRepository.find({ tenantId });
|
||||
const inviteAcceptedUsers = await User.query()
|
||||
.select(['id'])
|
||||
.whereNotNull('invite_accepted_at');
|
||||
|
||||
if (usersFound.length === 1) {
|
||||
if (inviteAcceptedUsers.length === 1) {
|
||||
throw new ServiceError(ERRORS.CANNOT_DELETE_LAST_USER);
|
||||
}
|
||||
}
|
||||
@@ -295,32 +294,11 @@ export default class UsersService {
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Validate user phone number should be unique.
|
||||
* @param {string} phoneNumber -
|
||||
* @param {number} userId -
|
||||
*/
|
||||
private validateUserPhoneNumberUniqiness = async (
|
||||
tenantId: number,
|
||||
phoneNumber: string,
|
||||
userId: number
|
||||
) => {
|
||||
const { User } = this.tenancy.models(tenantId);
|
||||
|
||||
const userByPhoneNumber = await User.query()
|
||||
.findOne('phone_number', phoneNumber)
|
||||
.whereNot('id', userId);
|
||||
|
||||
if (userByPhoneNumber) {
|
||||
throw new ServiceError(ERRORS.PHONE_NUMBER_ALREADY_EXIST);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Validate the authorized user cannot mutate its role.
|
||||
* @param {ITenantUser} oldTenantUser
|
||||
* @param {IEditUserDTO} editUserDTO
|
||||
* @param {ISystemUser} authorizedUser
|
||||
* @param {ITenantUser} oldTenantUser
|
||||
* @param {IEditUserDTO} editUserDTO
|
||||
* @param {ISystemUser} authorizedUser
|
||||
*/
|
||||
validateMutateRoleNotAuthorizedUser(
|
||||
oldTenantUser: ITenantUser,
|
||||
@@ -334,5 +312,4 @@ export default class UsersService {
|
||||
throw new ServiceError(ERRORS.CANNOT_AUTHORIZED_USER_MUTATE_ROLE);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,27 +1,29 @@
|
||||
import { Container, Service } from 'typedi';
|
||||
import events from '@/subscribers/events';
|
||||
import { IAuthSignedInEventPayload } from '@/interfaces';
|
||||
|
||||
@Service()
|
||||
export default class ResetLoginThrottleSubscriber {
|
||||
/**
|
||||
* Attaches events with handlers.
|
||||
* @param bus
|
||||
* @param bus
|
||||
*/
|
||||
public attach(bus) {
|
||||
bus.subscribe(events.auth.login, this.resetLoginThrottleOnceSuccessLogin);
|
||||
bus.subscribe(events.auth.signIn, this.resetLoginThrottleOnceSuccessLogin);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resets the login throttle once the login success.
|
||||
* @param {IAuthSignedInEventPayload} payload -
|
||||
*/
|
||||
private async resetLoginThrottleOnceSuccessLogin(payload) {
|
||||
const { emailOrPhone, password, user } = payload;
|
||||
|
||||
private async resetLoginThrottleOnceSuccessLogin(
|
||||
payload: IAuthSignedInEventPayload
|
||||
) {
|
||||
const { email, user } = payload;
|
||||
const loginThrottler = Container.get('rateLimiter.login');
|
||||
|
||||
// Reset the login throttle by the given email and phone number.
|
||||
await loginThrottler.reset(user.email);
|
||||
await loginThrottler.reset(user.phoneNumber);
|
||||
await loginThrottler.reset(emailOrPhone);
|
||||
await loginThrottler.reset(email);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,14 +10,14 @@ export default class AuthSendWelcomeMailSubscriber {
|
||||
* Attaches events with handlers.
|
||||
*/
|
||||
public attach(bus) {
|
||||
bus.subscribe(events.auth.register, this.sendWelcomeEmailOnceUserRegister);
|
||||
bus.subscribe(events.auth.signUp, this.sendWelcomeEmailOnceUserRegister);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends welcome email once the user register.
|
||||
*/
|
||||
private sendWelcomeEmailOnceUserRegister = async (payload) => {
|
||||
const { registerDTO, tenant, user } = payload;
|
||||
const { tenant, user } = payload;
|
||||
|
||||
// Send welcome mail to the user.
|
||||
await this.agenda.now('welcome-email', {
|
||||
|
||||
@@ -3,10 +3,17 @@ export default {
|
||||
* Authentication service.
|
||||
*/
|
||||
auth: {
|
||||
login: 'onLogin',
|
||||
register: 'onRegister',
|
||||
signIn: 'onSignIn',
|
||||
signingIn: 'onSigningIn',
|
||||
|
||||
signUp: 'onSignUp',
|
||||
signingUp: 'onSigningUp',
|
||||
|
||||
sendingResetPassword: 'onSendingResetPassword',
|
||||
sendResetPassword: 'onSendResetPassword',
|
||||
|
||||
resetPassword: 'onResetPassword',
|
||||
resetingPassword: 'onResetingPassword'
|
||||
},
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
exports.up = function (knex) {
|
||||
return knex.schema.table('users', (table) => {
|
||||
table.dropColumn('phone_number');
|
||||
});
|
||||
};
|
||||
|
||||
exports.down = function (knex) {
|
||||
return knex.schema.table('users', (table) => {});
|
||||
};
|
||||
@@ -419,6 +419,58 @@ export const parseDate = (date: string) => {
|
||||
return date ? moment(date).utcOffset(0).format('YYYY-MM-DD') : '';
|
||||
};
|
||||
|
||||
const nestedArrayToFlatten = (
|
||||
collection,
|
||||
property = 'children',
|
||||
parseItem = (a, level) => a,
|
||||
level = 1
|
||||
) => {
|
||||
const parseObject = (obj) =>
|
||||
parseItem(
|
||||
{
|
||||
..._.omit(obj, [property]),
|
||||
},
|
||||
level
|
||||
);
|
||||
|
||||
return collection.reduce((items, currentValue, index) => {
|
||||
let localItems = [...items];
|
||||
const parsedItem = parseObject(currentValue, level);
|
||||
localItems.push(parsedItem);
|
||||
|
||||
if (Array.isArray(currentValue[property])) {
|
||||
const flattenArray = nestedArrayToFlatten(
|
||||
currentValue[property],
|
||||
property,
|
||||
parseItem,
|
||||
level + 1
|
||||
);
|
||||
localItems = _.concat(localItems, flattenArray);
|
||||
}
|
||||
return localItems;
|
||||
}, []);
|
||||
};
|
||||
|
||||
const assocDepthLevelToObjectTree = (
|
||||
objects,
|
||||
level = 1,
|
||||
propertyName = 'level'
|
||||
) => {
|
||||
for (let i = 0; i < objects.length; i++) {
|
||||
const object = objects[i];
|
||||
object[propertyName] = level;
|
||||
|
||||
if (object.children) {
|
||||
assocDepthLevelToObjectTree(object.children, level + 1, propertyName);
|
||||
}
|
||||
}
|
||||
return objects;
|
||||
};
|
||||
|
||||
const castCommaListEnvVarToArray = (envVar: string): Array<string> => {
|
||||
return envVar ? envVar?.split(',')?.map(_.trim) : [];
|
||||
};
|
||||
|
||||
export {
|
||||
templateRender,
|
||||
accumSum,
|
||||
@@ -449,4 +501,7 @@ export {
|
||||
dateRangeFromToCollection,
|
||||
transformToMapKeyValue,
|
||||
mergeObjectsBykey,
|
||||
nestedArrayToFlatten,
|
||||
assocDepthLevelToObjectTree,
|
||||
castCommaListEnvVarToArray
|
||||
};
|
||||
|
||||
@@ -5,10 +5,10 @@ USER root
|
||||
WORKDIR /app
|
||||
|
||||
# Install dependencies
|
||||
COPY package.json ./
|
||||
COPY package*.json ./
|
||||
COPY lerna.json ./
|
||||
|
||||
COPY ./packages/webapp/package.json /app/packages/webapp/package.json
|
||||
COPY ./packages/webapp/package*.json /app/packages/webapp/
|
||||
|
||||
RUN npm install
|
||||
RUN npm run bootstrap
|
||||
|
||||
17
packages/webapp/package-lock.json
generated
@@ -1205,9 +1205,9 @@
|
||||
}
|
||||
},
|
||||
"@blueprintjs-formik/core": {
|
||||
"version": "0.2.1",
|
||||
"resolved": "https://registry.npmjs.org/@blueprintjs-formik/core/-/core-0.2.1.tgz",
|
||||
"integrity": "sha512-YGJe+QorDGbkWDSUg6x69LYGN62Kgvb92Iz/voqmszVRKj4KcoPvd/7coF8Jmu+ZQE6LcwM/9ccB2i63L99ITA==",
|
||||
"version": "0.3.3",
|
||||
"resolved": "https://registry.npmjs.org/@blueprintjs-formik/core/-/core-0.3.3.tgz",
|
||||
"integrity": "sha512-ko7g54YSEcSq2K/GEpmiTG0foGLqe7DwgXGhkGxYEiHhLAUv8WvQmrFsm8e/KOW7n8mLGq0uaZVe2l8m3JTGGQ==",
|
||||
"requires": {
|
||||
"lodash.get": "^4.4.2",
|
||||
"lodash.keyby": "^4.6.0",
|
||||
@@ -1227,9 +1227,9 @@
|
||||
}
|
||||
},
|
||||
"@blueprintjs-formik/select": {
|
||||
"version": "0.1.5",
|
||||
"resolved": "https://registry.npmjs.org/@blueprintjs-formik/select/-/select-0.1.5.tgz",
|
||||
"integrity": "sha512-EqGbuoiS1VrWpzjd39uVhBAmfVobdpgqalGcpODyGA+XAYoft1UU12yzTzrEOwBZpQKiC12UQwekUPspYBsVKA==",
|
||||
"version": "0.2.3",
|
||||
"resolved": "https://registry.npmjs.org/@blueprintjs-formik/select/-/select-0.2.3.tgz",
|
||||
"integrity": "sha512-j/zkX0B9wgtoHgK6Z/rlowB7F7zemrAajBU+d3caCoEYMMqwAI0XA++GytqrIhv5fEGjkZ1hkxS9j8eqX8vtjA==",
|
||||
"requires": {
|
||||
"lodash.get": "^4.4.2",
|
||||
"lodash.keyby": "^4.6.0",
|
||||
@@ -7298,6 +7298,11 @@
|
||||
"locate-path": "^3.0.0"
|
||||
}
|
||||
},
|
||||
"flat": {
|
||||
"version": "5.0.2",
|
||||
"resolved": "https://registry.npmjs.org/flat/-/flat-5.0.2.tgz",
|
||||
"integrity": "sha512-b6suED+5/3rTpUBdG1gupIl8MPFCAMA0QXwmljLhvCUKcUvdE4gWky9zpuGCcXHOsz4J9wPGNWq6OKpmIzz3hQ=="
|
||||
},
|
||||
"flat-cache": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-2.0.1.tgz",
|
||||
|
||||
@@ -3,9 +3,9 @@
|
||||
"version": "1.7.1",
|
||||
"private": true,
|
||||
"dependencies": {
|
||||
"@blueprintjs-formik/core": "^0.2.1",
|
||||
"@blueprintjs-formik/core": "^0.3.3",
|
||||
"@blueprintjs-formik/datetime": "^0.3.4",
|
||||
"@blueprintjs-formik/select": "^0.1.4",
|
||||
"@blueprintjs-formik/select": "^0.2.3",
|
||||
"@blueprintjs/core": "^3.50.2",
|
||||
"@blueprintjs/datetime": "^3.23.12",
|
||||
"@blueprintjs/popover2": "^0.11.1",
|
||||
@@ -16,8 +16,6 @@
|
||||
"@casl/react": "^2.3.0",
|
||||
"@craco/craco": "^5.9.0",
|
||||
"@reduxjs/toolkit": "^1.2.5",
|
||||
"@sentry/react": "^6.13.2",
|
||||
"@sentry/tracing": "^6.13.2",
|
||||
"@testing-library/jest-dom": "^4.2.4",
|
||||
"@testing-library/react": "^9.4.0",
|
||||
"@testing-library/user-event": "^7.2.1",
|
||||
@@ -45,6 +43,7 @@
|
||||
"deepdash": "^5.3.9",
|
||||
"dependency-graph": "^0.11.0",
|
||||
"fast-deep-equal": "^3.1.3",
|
||||
"flat": "^5.0.2",
|
||||
"formik": "^2.2.5",
|
||||
"http-proxy-middleware": "^1.0.0",
|
||||
"jest": "24.9.0",
|
||||
|
||||
|
Before Width: | Height: | Size: 1.9 KiB After Width: | Height: | Size: 1.9 KiB |
|
Before Width: | Height: | Size: 2.6 KiB After Width: | Height: | Size: 2.6 KiB |
|
Before Width: | Height: | Size: 3.8 KiB After Width: | Height: | Size: 3.8 KiB |
|
Before Width: | Height: | Size: 1.8 KiB After Width: | Height: | Size: 1.8 KiB |
|
Before Width: | Height: | Size: 3.3 KiB After Width: | Height: | Size: 3.3 KiB |
|
Before Width: | Height: | Size: 1.7 KiB After Width: | Height: | Size: 1.7 KiB |
|
Before Width: | Height: | Size: 4.1 KiB After Width: | Height: | Size: 4.1 KiB |
|
Before Width: | Height: | Size: 2.2 KiB After Width: | Height: | Size: 2.2 KiB |
|
Before Width: | Height: | Size: 2.4 KiB After Width: | Height: | Size: 2.4 KiB |
|
Before Width: | Height: | Size: 2.4 KiB After Width: | Height: | Size: 2.4 KiB |
|
Before Width: | Height: | Size: 4.0 KiB After Width: | Height: | Size: 4.0 KiB |
|
Before Width: | Height: | Size: 1.5 KiB After Width: | Height: | Size: 1.5 KiB |
|
Before Width: | Height: | Size: 1.6 KiB After Width: | Height: | Size: 1.6 KiB |
|
Before Width: | Height: | Size: 3.7 KiB After Width: | Height: | Size: 3.7 KiB |