Compare commits

..

2 Commits

Author SHA1 Message Date
a.bouhuolia
b8ce39d253 chore 2023-03-27 22:39:02 +02:00
a.bouhuolia
478670c1d5 chore: Github action to dockernize server 2023-03-27 22:37:38 +02:00
81 changed files with 1955 additions and 4640 deletions

View File

@@ -1,34 +0,0 @@
# Mail
MAIL_HOST=
MAIL_USERNAME=
MAIL_PASSWORD=
MAIL_PORT=
MAIL_SECURE=
MAIL_FROM_NAME=
MAIL_FROM_ADDRESS=
# Database
DB_USER=
DB_HOST=
DB_PASSWORD=
DB_CHARSET=
# System database
SYSTEM_DB_NAME=bigcapital_system
# Tenants databases
TENANT_DB_NAME_PERFIX=bigcapital_tenant_
# MongoDB
MONGODB_DATABASE_URL=mongodb://localhost/bigcapital
# Authentication
JWT_SECRET=b0JDZW56RnV6aEthb0RGPXVEcUI
# Application
BASE_URL=https://bigcapital.ly
CONTACT_US_MAIL=support@bigcapital.ly
# Agendash
AGENDASH_AUTH_USER=agendash
AGENDASH_AUTH_PASSWORD=123123

View File

@@ -1,81 +0,0 @@
# This workflow will build a docker container, publish it to Github Registry.
name: Build and Deploy Docker Container
on:
release:
types: [created]
workflow_dispatch:
env:
REGISTRY: ghcr.io
WEBAPP_IMAGE_NAME: bigcapital/bigcapital-webapp
SERVER_IMAGE_NAME: bigcapital/bigcapital-server
jobs:
build-publish-webapp:
name: Build and deploy webapp container
runs-on: ubuntu-latest
environment: production
steps:
- name: Checkout
uses: actions/checkout@v2
# Login to Container registry.
- name: Log in to the Container registry
uses: docker/login-action@v1
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GH_TOKEN }}
- name: Extract metadata (tags, labels) for Docker
id: meta
uses: docker/metadata-action@98669ae865ea3cffbcbaa878cf57c20bbf1c6c38
with:
images: ${{ env.REGISTRY }}/${{ env.WEBAPP_IMAGE_NAME }}
# Builds and push the Docker image.
- name: Build and push Docker image
uses: docker/build-push-action@v2
with:
context: .
file: ./packages/webapp/Dockerfile
push: true
tags: ghcr.io/bigcapitalhq/webapp:latest
labels: ${{ steps.meta.outputs.labels }}
# Send notification to Slack channel.
- name: Slack Notification built and published webapp container successfully.
uses: rtCamp/action-slack-notify@v2
env:
SLACK_WEBHOOK: ${{ secrets.SLACK_WEBHOOK }}
build-publish-server:
name: Build and deploy server container
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v2
# Login to Container registry.
- name: Log in to the Container registry
uses: docker/login-action@v1
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GH_TOKEN }}
# Builds and push the Docker image.
- name: Build and push Docker image
uses: docker/build-push-action@v2
with:
context: ./
file: ./packages/server/Dockerfile
push: true
tags: ghcr.io/bigcapitalhq/server:latest
labels: ${{ steps.meta.outputs.labels }}
# Send notification to Slack channel.
- name: Slack Notification built and published server container successfully.
uses: rtCamp/action-slack-notify@v2
env:
SLACK_WEBHOOK: ${{ secrets.SLACK_WEBHOOK }}

64
.github/workflows/docker-build.yml vendored Normal file
View File

@@ -0,0 +1,64 @@
# This workflow will build a docker container, publish it to Google Container Registry, and deploy it to GKE when a release is created
#
# To configure this workflow:
#
# 1. Ensure that your repository contains the necessary configuration for your Google Kubernetes Engine cluster, including deployment.yml, kustomization.yml, service.yml, etc.
#
# 2. Set up secrets in your workspace: GKE_PROJECT with the name of the project and GKE_SA_KEY with the Base64 encoded JSON service account key (https://github.com/GoogleCloudPlatform/github-actions/tree/docs/service-account-key/setup-gcloud#inputs).
#
# 3. Change the values for the GKE_ZONE, GKE_CLUSTER, IMAGE, and DEPLOYMENT_NAME environment variables (below).
#
# For more support on how to run the workflow, please visit https://github.com/google-github-actions/setup-gcloud/tree/master/example-workflows/gke
name: Build and Deploy Docker Container
on:
release:
types: [created]
workflow_dispatch:
env:
REGISTRY: ghcr.io
IMAGE_NAME: abouhuolia/bigcapital-webapp
jobs:
setup-build-publish-deploy:
name: Setup, Build, Publish, and Deploy
runs-on: ubuntu-latest
environment: production
steps:
- name: Checkout
uses: actions/checkout@v2
# Login to Container registry.
- name: Log in to the Container registry
uses: docker/login-action@v1
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GH_TOKEN }}
- name: Extract metadata (tags, labels) for Docker
id: meta
uses: docker/metadata-action@98669ae865ea3cffbcbaa878cf57c20bbf1c6c38
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
# Builds and push the Docker image.
- name: Build and push Docker image
uses: docker/build-push-action@v2
with:
context: .
file: ./packages/webapp/Dockerfile
push: true
tags: ghcr.io/bigcapitalhq/webapp:latest
labels: ${{ steps.meta.outputs.labels }}
# Send notification to Slack channel.
- name: Slack Notification built and published successfully.
uses: rtCamp/action-slack-notify@v2
env:
SLACK_WEBHOOK: ${{ secrets.SLACK_WEBHOOK }}

View File

@@ -0,0 +1,30 @@
name: push
on:
release:
types: [created]
workflow_dispatch:
env:
REGISTRY: ghcr.io
IMAGE_NAME: abouhuolia/bigcapital-webapp
jobs:
image-build-and-push-webapp:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v2
# Login to Container registry.
- name: Log in to the Container registry
uses: docker/login-action@v1
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GH_TOKEN }}
# Install and boostrap Lerna.
- name: Install and boostrap Lerna
working-directory: ./
run: npm install -g lerna && npm run bootstrap

3
.gitignore vendored
View File

@@ -1,3 +1,2 @@
node_modules/ node_modules/
data data
.env

View File

@@ -2,32 +2,6 @@
All notable changes to Bigcapital server-side will be in this file. All notable changes to Bigcapital server-side will be in this file.
## [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 ## [0.8.1] - 26-03-2023
`@bigcaptial/monorepo` `@bigcaptial/monorepo`

View File

@@ -1,3 +0,0 @@
This software is provided "as is" and without any express or implied warranties, including, without limitation, the implied warranties of merchantability and fitness for a particular purpose.
In no event shall the authors or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; or business interruption) however caused and on any theory of liability, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of such damage.

883
LICENSE
View File

@@ -1,660 +1,339 @@
### GNU AFFERO GENERAL PUBLIC LICENSE GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Version 3, 19 November 2007 Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Copyright (C) 2007 Free Software Foundation, Inc. Preamble
<https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this The licenses for most software are designed to take away your
license document, but changing it is not allowed. freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
### Preamble When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains
free software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you this service if you wish), that you receive source code or can get it
want it, that you can change the software or use pieces of it in new if you want it, that you can change the software or use pieces of it
free programs, and that you know you can do these things. in new free programs; and that you know you can do these things.
Developers that use our General Public Licenses protect your rights To protect your rights, we need to make restrictions that forbid
with two steps: (1) assert copyright on the software, and (2) offer anyone to deny you these rights or to ask you to surrender the rights.
you this License which gives you legal permission to copy, distribute These restrictions translate to certain responsibilities for you if you
and/or modify the software. distribute copies of the software, or if you modify it.
A secondary benefit of defending all users' freedom is that For example, if you distribute copies of such a program, whether
improvements made in alternate versions of the program, if they gratis or for a fee, you must give the recipients all the rights that
receive widespread use, become available for other developers to you have. You must make sure that they, too, receive or can get the
incorporate. Many developers of free software are heartened and source code. And you must show them these terms so they know their
encouraged by the resulting cooperation. However, in the case of rights.
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to We protect your rights with two steps: (1) copyright the software, and
ensure that, in such cases, the modified source code becomes available (2) offer you this license which gives you legal permission to copy,
to the community. It requires the operator of a network server to distribute and/or modify the software.
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and Also, for each author's protection and ours, we want to make certain
published by Affero, was designed to accomplish similar goals. This is that everyone understands that there is no warranty for this free
a different license, not a version of the Affero GPL, but Affero has software. If the software is modified by someone else and passed on, we
released a new version of the Affero GPL which permits relicensing want its recipients to know that what they have is not the original, so
under this license. that any problems introduced by others will not reflect on the original
authors' reputations.
The precise terms and conditions for copying, distribution and Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow. modification follow.
### TERMS AND CONDITIONS GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
#### 0. Definitions. 0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
"This License" refers to version 3 of the GNU Affero General Public Activities other than copying, distribution and modification are not
License. covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
"Copyright" also means copyright-like laws that apply to other kinds 1. You may copy and distribute verbatim copies of the Program's
of works, such as semiconductor masks. source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
"The Program" refers to any copyrightable work licensed under this You may charge a fee for the physical act of transferring a copy, and
License. Each licensee is addressed as "you". "Licensees" and you may at your option offer warranty protection in exchange for a fee.
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work 2. You may modify your copy or copies of the Program or any portion
in a fashion requiring copyright permission, other than the making of of it, thus forming a work based on the Program, and copy and
an exact copy. The resulting work is called a "modified version" of distribute such modifications or work under the terms of Section 1
the earlier work or a work "based on" the earlier work. above, provided that you also meet all of these conditions:
A "covered work" means either the unmodified Program or a work based a) You must cause the modified files to carry prominent notices
on the Program. stating that you changed the files and the date of any change.
To "propagate" a work means to do anything with it that, without b) You must cause any work that you distribute or publish, that in
permission, would make you directly or secondarily liable for whole or in part contains or is derived from the Program or any
infringement under applicable copyright law, except executing it on a part thereof, to be licensed as a whole at no charge to all third
computer or modifying a private copy. Propagation includes copying, parties under the terms of this License.
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other c) If the modified program normally reads commands interactively
parties to make or receive copies. Mere interaction with a user when run, you must cause it, when started running for such
through a computer network, with no transfer of a copy, is not interactive use in the most ordinary way, to print or display an
conveying. announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
An interactive user interface displays "Appropriate Legal Notices" to These requirements apply to the modified work as a whole. If
the extent that it includes a convenient and prominently visible identifiable sections of that work are not derived from the Program,
feature that (1) displays an appropriate copyright notice, and (2) and can be reasonably considered independent and separate works in
tells the user that there is no warranty for the work (except to the themselves, then this License, and its terms, do not apply to those
extent that warranties are provided), that licensees may convey the sections when you distribute them as separate works. But when you
work under this License, and how to view a copy of this License. If distribute the same sections as part of a whole which is a work based
the interface presents a list of user commands or options, such as a on the Program, the distribution of the whole must be on the terms of
menu, a prominent item in the list meets this criterion. this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
#### 1. Source Code. Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
The "source code" for a work means the preferred form of the work for In addition, mere aggregation of another work not based on the Program
making modifications to it. "Object code" means any non-source form of with the Program (or with a work based on the Program) on a volume of
a work. a storage or distribution medium does not bring the other work under
the scope of this License.
A "Standard Interface" means an interface that either is an official 3. You may copy and distribute the Program (or a work based on it,
standard defined by a recognized standards body, or, in the case of under Section 2) in object code or executable form under the terms of
interfaces specified for a particular programming language, one that Sections 1 and 2 above provided that you also do one of the following:
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other a) Accompany it with the complete corresponding machine-readable
than the work as a whole, that (a) is included in the normal form of source code, which must be distributed under the terms of Sections
packaging a Major Component, but which is not part of that Major 1 and 2 above on a medium customarily used for software interchange; or,
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all b) Accompany it with a written offer, valid for at least three
the source code needed to generate, install, and (for an executable years, to give any third party, for a charge no more than your
work) run the object code and to modify the work, including scripts to cost of physically performing source distribution, a complete
control those activities. However, it does not include the work's machine-readable copy of the corresponding source code, to be
System Libraries, or general-purpose tools or generally available free distributed under the terms of Sections 1 and 2 above on a medium
programs which are used unmodified in performing those activities but customarily used for software interchange; or,
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users can c) Accompany it with the information you received as to the offer
regenerate automatically from other parts of the Corresponding Source. to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The Corresponding Source for a work in source code form is that same The source code for a work means the preferred form of the work for
work. making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
#### 2. Basic Permissions. If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
All rights granted under this License are granted for the term of 4. You may not copy, modify, sublicense, or distribute the Program
copyright on the Program, and are irrevocable provided the stated except as expressly provided under this License. Any attempt
conditions are met. This License explicitly affirms your unlimited otherwise to copy, modify, sublicense or distribute the Program is
permission to run the unmodified Program. The output from running a void, and will automatically terminate your rights under this License.
covered work is covered by this License only if the output, given its However, parties who have received copies, or rights, from you under
content, constitutes a covered work. This License acknowledges your this License will not have their licenses terminated so long as such
rights of fair use or other equivalent, as provided by copyright law. parties remain in full compliance.
You may make, run and propagate covered works that you do not convey, 5. You are not required to accept this License, since you have not
without conditions so long as your license otherwise remains in force. signed it. However, nothing else grants you permission to modify or
You may convey covered works to others for the sole purpose of having distribute the Program or its derivative works. These actions are
them make modifications exclusively for you, or provide you with prohibited by law if you do not accept this License. Therefore, by
facilities for running those works, provided that you comply with the modifying or distributing the Program (or any work based on the
terms of this License in conveying all material for which you do not Program), you indicate your acceptance of this License to do so, and
control copyright. Those thus making or running the covered works for all its terms and conditions for copying, distributing or modifying
you must do so exclusively on your behalf, under your direction and the Program or works based on it.
control, on terms that prohibit them from making any copies of your
copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under the 6. Each time you redistribute the Program (or any work based on the
conditions stated below. Sublicensing is not allowed; section 10 makes Program), the recipient automatically receives a license from the
it unnecessary. original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
#### 3. Protecting Users' Legal Rights From Anti-Circumvention Law. restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such
circumvention is effected by exercising rights under this License with
respect to the covered work, and you disclaim any intention to limit
operation or modification of the work as a means of enforcing, against
the work's users, your or third parties' legal rights to forbid
circumvention of technological measures.
#### 4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
#### 5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these
conditions:
- a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
- b) The work must carry prominent notices stating that it is
released under this License and any conditions added under
section 7. This requirement modifies the requirement in section 4
to "keep intact all notices".
- c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
- d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
#### 6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of
sections 4 and 5, provided that you also convey the machine-readable
Corresponding Source under the terms of this License, in one of these
ways:
- a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
- b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the Corresponding
Source from a network server at no charge.
- c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
- d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
- e) Convey the object code using peer-to-peer transmission,
provided you inform other peers where the object code and
Corresponding Source of the work are being offered to the general
public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal,
family, or household purposes, or (2) anything designed or sold for
incorporation into a dwelling. In determining whether a product is a
consumer product, doubtful cases shall be resolved in favor of
coverage. For a particular product received by a particular user,
"normally used" refers to a typical or common use of that class of
product, regardless of the status of the particular user or of the way
in which the particular user actually uses, or expects or is expected
to use, the product. A product is a consumer product regardless of
whether the product has substantial commercial, industrial or
non-consumer uses, unless such uses represent the only significant
mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to
install and execute modified versions of a covered work in that User
Product from a modified version of its Corresponding Source. The
information must suffice to ensure that the continued functioning of
the modified object code is in no case prevented or interfered with
solely because modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or
updates for a work that has been modified or installed by the
recipient, or for the User Product in which it has been modified or
installed. Access to a network may be denied when the modification
itself materially and adversely affects the operation of the network
or violates the rules and protocols for communication across the
network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
#### 7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders
of that material) supplement the terms of this License with terms:
- a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
- b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
- c) Prohibiting misrepresentation of the origin of that material,
or requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
- d) Limiting the use for publicity purposes of names of licensors
or authors of the material; or
- e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
- f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions
of it) with contractual assumptions of liability to the recipient,
for any liability that these contractual assumptions directly
impose on those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions; the
above requirements apply either way.
#### 8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your license
from a particular copyright holder is reinstated (a) provisionally,
unless and until the copyright holder explicitly and finally
terminates your license, and (b) permanently, if the copyright holder
fails to notify you of the violation by some reasonable means prior to
60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
#### 9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run
a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
#### 10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
#### 11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims owned
or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License. this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free 7. If, as a consequence of a court judgment or allegation of patent
patent license under the contributor's essential patent claims, to infringement or for any other reason (not limited to patent issues),
make, use, sell, offer for sale, import and otherwise run, modify and conditions are imposed on you (whether by court order, agreement or
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within the
scope of its coverage, prohibits the exercise of, or is conditioned on
the non-exercise of one or more of the rights that are specifically
granted under this License. You may not convey a covered work if you
are a party to an arrangement with a third party that is in the
business of distributing software, under which you make payment to the
third party based on the extent of your activity of conveying the
work, and under which the third party grants, to any of the parties
who would receive the covered work from you, a discriminatory patent
license (a) in connection with copies of the covered work conveyed by
you (or copies made from those copies), or (b) primarily for and in
connection with specific products or compilations that contain the
covered work, unless you entered into that arrangement, or that patent
license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
#### 12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a excuse you from the conditions of this License. If you cannot
covered work so as to satisfy simultaneously your obligations under distribute so as to satisfy simultaneously your obligations under this
this License and any other pertinent obligations, then as a License and any other pertinent obligations, then as a consequence you
consequence you may not convey it at all. For example, if you agree to may not distribute the Program at all. For example, if a patent
terms that obligate you to collect a royalty for further conveying license would not permit royalty-free redistribution of the Program by
from those to whom you convey the Program, the only way you could all those who receive copies directly or indirectly through you, then
satisfy both those terms and this License would be to refrain entirely the only way you could satisfy both it and this License would be to
from conveying the Program. refrain entirely from distribution of the Program.
#### 13. Remote Network Interaction; Use with the GNU General Public License. If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
Notwithstanding any other provision of this License, if you modify the It is not the purpose of this section to induce you to infringe any
Program, your modified version must prominently offer all users patents or other property right claims or to contest validity of any
interacting with it remotely through a computer network (if your such claims; this section has the sole purpose of protecting the
version supports such interaction) an opportunity to receive the integrity of the free software distribution system, which is
Corresponding Source of your version by providing access to the implemented by public license practices. Many people have made
Corresponding Source from a network server at no charge, through some generous contributions to the wide range of software distributed
standard or customary means of facilitating copying of software. This through that system in reliance on consistent application of that
Corresponding Source shall include the Corresponding Source for any system; it is up to the author/donor to decide if he or she is willing
work covered by version 3 of the GNU General Public License that is to distribute software through any other system and a licensee cannot
incorporated pursuant to the following paragraph. impose that choice.
Notwithstanding any other provision of this License, you have This section is intended to make thoroughly clear what is believed to
permission to link or combine any covered work with a work licensed be a consequence of the rest of this License.
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
#### 14. Revised Versions of this License. 8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
The Free Software Foundation may publish revised and/or new versions 9. The Free Software Foundation may publish revised and/or new versions
of the GNU Affero General Public License from time to time. Such new of the General Public License from time to time. Such new versions will
versions will be similar in spirit to the present version, but may be similar in spirit to the present version, but may differ in detail to
differ in detail to address new problems or concerns. address new problems or concerns.
Each version is given a distinguishing version number. If the Program Each version is given a distinguishing version number. If the Program
specifies that a certain numbered version of the GNU Affero General specifies a version number of this License which applies to it and "any
Public License "or any later version" applies to it, you have the later version", you have the option of following the terms and conditions
option of following the terms and conditions either of that numbered either of that version or of any later version published by the Free
version or of any later version published by the Free Software Software Foundation. If the Program does not specify a version number of
Foundation. If the Program does not specify a version number of the this License, you may choose any version ever published by the Free Software
GNU Affero General Public License, you may choose any version ever Foundation.
published by the Free Software Foundation.
If the Program specifies that a proxy can decide which future versions 10. If you wish to incorporate parts of the Program into other free
of the GNU Affero General Public License can be used, that proxy's programs whose distribution conditions are different, write to the author
public statement of acceptance of a version permanently authorizes you to ask for permission. For software which is copyrighted by the Free
to choose that version for the Program. Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
Later license versions may give you additional or different NO WARRANTY
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
#### 15. Disclaimer of Warranty. 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
CORRECTION. POSSIBILITY OF SUCH DAMAGES.
#### 16. Limitation of Liability. END OF TERMS AND CONDITIONS
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING How to Apply These Terms to Your New Programs
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR
CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES
ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT
NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR
LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM
TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER
PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
#### 17. Interpretation of Sections 15 and 16. If you develop a new program, and you want it to be of the greatest
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
### How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these free software which everyone can redistribute and change under these terms.
terms.
To do so, attach the following notices to the program. It is safest to To do so, attach the following notices to the program. It is safest
attach them to the start of each source file to most effectively state to attach them to the start of each source file to most effectively
the exclusion of warranty; and each file should have at least the convey the exclusion of warranty; and each file should have at least
"copyright" line and a pointer to where the full notice is found. the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.> <one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author> Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as it under the terms of the GNU General Public License as published by
published by the Free Software Foundation, either version 3 of the the Free Software Foundation; either version 2 of the License, or
License, or (at your option) any later version. (at your option) any later version.
This program is distributed in the hope that it will be useful, This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU Affero General Public License You should have received a copy of the GNU General Public License along
along with this program. If not, see <https://www.gnu.org/licenses/>. with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper Also add information on how to contact you by electronic and paper mail.
mail.
If your software can interact with users remotely through a computer If the program is interactive, make it output a short notice like this
network, you should also make sure that it provides a way for users to when it starts in an interactive mode:
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for
the specific requirements.
You should also get your employer (if you work as a programmer) or Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if school, if any, to sign a "copyright disclaimer" for the program, if
necessary. For more information on this, and how to apply and follow necessary. Here is a sample; alter the names:
the GNU AGPL, see <https://www.gnu.org/licenses/>.
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.

View File

@@ -1,132 +0,0 @@
# This is a production version of the Bigcapital docker-compose.yml file.
version: '3.3'
services:
nginx:
container_name: bigcapital-nginx-gateway
build:
context: ./docker/nginx
args:
- SERVER_PROXY_PORT=3000
- WEB_SSL=false
- SELF_SIGNED=false
volumes:
- ./data/logs/nginx/:/var/log/nginx
- ./docker/certbot/certs/:/var/certs
ports:
- "80:80"
- "443:443"
tty: true
depends_on:
- server
- webapp
webapp:
container_name: bigcapital-webapp
image: ghcr.io/bigcapitalhq/webapp:latest
server:
container_name: bigcapital-server
image: ghcr.io/bigcapitalhq/server:latest
links:
- mysql
- mongo
- redis
depends_on:
- mysql
- mongo
- redis
environment:
# Mail
- MAIL_HOST=${MAIL_HOST}
- MAIL_USERNAME=${MAIL_USERNAM}
- MAIL_PASSWORD=${MAIL_PASSWORD}
- MAIL_PORT=${MAIL_PORT}
- MAIL_SECURE=${MAIL_SECURE}
- MAIL_FROM_NAME=${MAIL_FROM_NAME}
- MAIL_FROM_ADDRESS=${MAIL_FROM_ADDRESS}
# Database
- DB_HOST=mysql
- DB_USER=${DB_USER}
- DB_PASSWORD=${DB_PASSWORD}
- DB_CHARSET=${DB_CHARSET}
# System database
- SYSTEM_DB_NAME=${SYSTEM_DB_NAME}
# Tenants databases
- TENANT_DB_NAME_PERFIX=${TENANT_DB_NAME_PERFIX}
# Authentication
- JWT_SECRET=${JWT_SECRET}
# MongoDB
- MONGODB_DATABASE_URL=mongodb://mongo/bigcapital
# Application
- BASE_URL=${BASE_URL}
# Agendash
- AGENDASH_AUTH_USER=${AGENDASH_AUTH_USER}
- AGENDASH_AUTH_PASSWORD=${AGENDASH_AUTH_PASSWORD}
database_migration:
container_name: bigcapital-database-migration
build:
context: ./
dockerfile: docker/migration/Dockerfile
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
environment:
- MYSQL_DATABASE=${SYSTEM_DB_NAME}
- MYSQL_USER=${DB_USER}
- MYSQL_PASSWORD=${DB_PASSWORD}
- MYSQL_ROOT_PASSWORD=${DB_PASSWORD}
volumes:
- mysql:/var/lib/mysql
expose:
- '3306'
mongo:
container_name: bigcapital-mongo
build: ./docker/mongo
expose:
- '27017'
volumes:
- mongo:/var/lib/mongodb
redis:
container_name: bigcapital-redis
build:
context: ./docker/redis
expose:
- "6379"
volumes:
- 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

View File

@@ -1,21 +1,16 @@
# WARNING!
# This is a development version of THE Bigcapital docker-compose.yml file.
# Avoid using this file in your production environment.
# We're exposing here sensitive ports and mounting code volumes for rapid development and debugging of the server stack.
version: '3.3' version: '3.3'
services: services:
mysql: mysql:
build: build:
context: ./docker/mysql context: ./docker/mysql
environment: args:
- MYSQL_DATABASE=${SYSTEM_DB_NAME} - MYSQL_DATABASE=bigcapital_system
- MYSQL_USER=${DB_USER} - MYSQL_USER=default_user
- MYSQL_PASSWORD=${DB_PASSWORD} - MYSQL_PASSWORD=secret
- MYSQL_ROOT_PASSWORD=${DB_PASSWORD} - MYSQL_ROOT_PASSWORD=root
volumes: volumes:
- mysql:/var/lib/mysql - ./data/mysql/:/var/lib/mysql
expose: expose:
- '3306' - '3306'
ports: ports:
@@ -26,7 +21,7 @@ services:
expose: expose:
- '27017' - '27017'
volumes: volumes:
- mongo:/var/lib/mongodb - ./data/mongo/:/var/lib/mongodb
ports: ports:
- '27017:27017' - '27017:27017'
@@ -36,18 +31,4 @@ services:
expose: expose:
- "6379" - "6379"
volumes: volumes:
- redis:/data - ./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

View File

@@ -1,38 +0,0 @@
FROM ghcr.io/bigcapitalhq/server:latest as build
ARG DB_HOST= \
DB_USER= \
DB_PASSWORD= \
DB_CHARSET= \
# System database.
SYSTEM_DB_NAME= \
SYSTEM_DB_PASSWORD= \
SYSTEM_DB_USER= \
SYSTEM_DB_HOST= \
SYSTEM_DB_CHARSET=
ENV DB_HOST=$DB_HOST \
DB_USER=$DB_USER \
DB_PASSWORD=$DB_PASSWORD \
DB_CHARSET=$DB_CHARSET \
# System database.
SYSTEM_DB_HOST=$SYSTEM_DB_HOST \
SYSTEM_DB_USER=$SYSTEM_DB_USER \
SYSTEM_DB_PASSWORD=$SYSTEM_DB_PASSWORD \
SYSTEM_DB_NAME=$SYSTEM_DB_NAME \
SYSTEM_DB_CHARSET=$SYSTEM_DB_CHARSET
USER root
RUN apk update && \
apk upgrade && \
apk add git
RUN apk add --no-cache bash
# Change working dir to the server package.
WORKDIR /app/packages/server
RUN git clone https://github.com/vishnubob/wait-for-it.git
# Once we listen the mysql port run the migration task.
CMD ["./wait-for-it/wait-for-it.sh", "mysql:3306", "--", "node", "./build/commands.js", "system:migrate:latest"]

View File

@@ -1,8 +1,9 @@
FROM mysql:5.7 FROM mysql:5.7
USER root
ADD my.cnf /etc/mysql/conf.d/my.cnf ADD my.cnf /etc/mysql/conf.d/my.cnf
RUN chown -R mysql:root /var/lib/mysql/
ARG MYSQL_DATABASE=default_database ARG MYSQL_DATABASE=default_database
ARG MYSQL_USER=default_user ARG MYSQL_USER=default_user
ARG MYSQL_PASSWORD=secret ARG MYSQL_PASSWORD=secret
@@ -13,14 +14,5 @@ ENV MYSQL_USER=$MYSQL_USER
ENV MYSQL_PASSWORD=$MYSQL_PASSWORD ENV MYSQL_PASSWORD=$MYSQL_PASSWORD
ENV MYSQL_ROOT_PASSWORD=$MYSQL_ROOT_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"] CMD ["mysqld"]
EXPOSE 3306 EXPOSE 3306

View File

@@ -1,18 +0,0 @@
#!/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

View File

@@ -1,2 +0,0 @@
GRANT ALL PRIVILEGES ON *.* TO '{MYSQL_USER}'@'%' IDENTIFIED BY '{MYSQL_PASSWORD}' WITH GRANT OPTION;
FLUSH PRIVILEGES;

View File

@@ -1,21 +0,0 @@
FROM nginx:1.11
RUN mkdir /etc/nginx/sites-available && rm /etc/nginx/conf.d/default.conf
ADD nginx.conf /etc/nginx/
COPY scripts /root/scripts/
COPY certs /etc/ssl/
COPY sites /etc/nginx/templates
ARG SERVER_PROXY_PORT=3000
ARG WEB_SSL=false
ARG SELF_SIGNED=false
ENV SERVER_PROXY_PORT=$SERVER_PROXY_PORT
ENV WEB_SSL=$WEB_SSL
ENV SELF_SIGNED=$SELF_SIGNED
RUN /bin/bash /root/scripts/build-nginx.sh
CMD nginx

View File

@@ -1,33 +0,0 @@
user www-data;
worker_processes auto;
pid /run/nginx.pid;
daemon off;
events {
worker_connections 2048;
use epoll;
}
http {
server_tokens off;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 15;
types_hash_max_size 2048;
client_max_body_size 20M;
open_file_cache max=100;
gzip on;
gzip_disable "msie6";
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers 'ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA:ECDHE-ECDSA-DES-CBC3-SHA:ECDHE-RSA-DES-CBC3-SHA:EDH-RSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:DES-CBC3-SHA:!DSS';
include /etc/nginx/mime.types;
default_type application/octet-stream;
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-available/*;
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
}

View File

@@ -1,9 +0,0 @@
#!/bin/bash
for conf in /etc/nginx/templates/*.conf; do
mv $conf "/etc/nginx/sites-available/"$(basename $conf) > /dev/null
done
for template in /etc/nginx/templates/*.template; do
envsubst < $template > "/etc/nginx/sites-available/"$(basename $template)".conf"
done

View File

@@ -1,16 +0,0 @@
server {
listen 80 default_server;
location /api {
proxy_pass http://server:${SERVER_PROXY_PORT};
}
location / {
proxy_pass http://webapp;
}
location /.well-known/acme-challenge/ {
root /var/www/letsencrypt/;
log_not_found off;
}
}

View File

@@ -9,7 +9,6 @@
"build:webapp": "lerna run build --scope \"@bigcapital/webapp\"", "build:webapp": "lerna run build --scope \"@bigcapital/webapp\"",
"dev:server": "lerna run dev --scope \"@bigcapital/server\"", "dev:server": "lerna run dev --scope \"@bigcapital/server\"",
"build:server": "lerna run build --scope \"@bigcapital/server\"", "build:server": "lerna run build --scope \"@bigcapital/server\"",
"serve:server": "lerna run serve --scope \"@bigcapital/server\"",
"prepare": "husky install" "prepare": "husky install"
}, },
"workspaces": [ "workspaces": [

View File

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

View File

@@ -1,93 +0,0 @@
FROM node:14.20-alpine as build
USER root
ARG MAIL_HOST= \
MAIL_USERNAME= \
MAIL_PASSWORD= \
MAIL_PORT= \
MAIL_SECURE= \
MAIL_FROM_NAME= \
MAIL_FROM_ADDRESS= \
# Database
DB_HOST= \
DB_USER= \
DB_PASSWORD= \
DB_CHARSET= \
# System database.
SYSTEM_DB_NAME= \
SYSTEM_DB_PASSWORD= \
SYSTEM_DB_USER= \
SYSTEM_DB_HOST= \
SYSTEM_DB_CHARSET= \
# Tenant databases.
TENANT_DB_USER= \
TENANT_DB_PASSWORD= \
TENANT_DB_HOST= \
TENANT_DB_NAME_PERFIX= \
TENANT_DB_CHARSET= \
# MongoDB
MONGODB_DATABASE_URL= \
# Authentication
JWT_SECRET= \
# Application
BASE_URL= \
# Agendash
AGENDASH_AUTH_USER=agendash \
AGENDASH_AUTH_PASSWORD=123123
ENV MAIL_HOST=$MAIL_HOST \
MAIL_USERNAME=$MAIL_USERNAME \
MAIL_PASSWORD=$MAIL_PASSWORD \
MAIL_PORT=$MAIL_PORT \
MAIL_SECURE=$MAIL_SECURE \
MAIL_FROM_NAME=$MAIL_FROM_NAME \
MAIL_FROM_ADDRESS=$MAIL_FROM_ADDRESS \
# Database
DB_HOST=$DB_HOST \
DB_USER=$DB_USER \
DB_PASSWORD=$DB_PASSWORD \
DB_CHARSET=$DB_CHARSET \
# System database.
SYSTEM_DB_HOST=$SYSTEM_DB_HOST \
SYSTEM_DB_USER=$SYSTEM_DB_USER \
SYSTEM_DB_PASSWORD=$SYSTEM_DB_PASSWORD \
SYSTEM_DB_NAME=$SYSTEM_DB_NAME \
SYSTEM_DB_CHARSET=$SYSTEM_DB_CHARSET \
# Tenant databases.
TENANT_DB_NAME_PERFIX=$TENANT_DB_NAME_PERFIX \
TENANT_DB_HOST=$TENANT_DB_HOST \
TENANT_DB_PASSWORD=$TENANT_DB_PASSWORD \
TENANT_DB_USER=$TENANT_DB_USER \
TENANT_DB_CHARSET=$TENANT_DB_CHARSET \
# Authentication
JWT_SECRET=$JWT_SECRET \
# Agendash
AGENDASH_AUTH_USER=$AGENDASH_AUTH_USER \
AGENDASH_AUTH_PASSWORD=$AGENDASH_AUTH_PASSWORD \
# MongoDB
MONGODB_DATABASE_URL=$MONGODB_DATABASE_URL \
# Application
BASE_URL=$BASE_URL
# Create app directory.
WORKDIR /app
RUN chown node:node /
# Copy application dependency manifests to the container image.
COPY ./package*.json ./
COPY ./packages/server/package*.json ./packages/server/
COPY ./lerna.json ./lerna.json
# Install app dependencies for production.
RUN npm install
RUN npm run bootstrap
COPY --chown=node:node ./packages/server ./packages/server
# # Creates a "dist" folder with the production build
RUN npm run build:server --skip-nx-cache
CMD [ "node", "./packages/server/build/index.js" ]

View File

@@ -11,7 +11,6 @@
"build:app": "cross-env NODE_ENV=production webpack --config scripts/webpack.config.js", "build:app": "cross-env NODE_ENV=production webpack --config scripts/webpack.config.js",
"build:commands": "cross-env NODE_ENV=production webpack --config scripts/webpack.cli.js", "build:commands": "cross-env NODE_ENV=production webpack --config scripts/webpack.cli.js",
"build": "npm-run-all build:*", "build": "npm-run-all build:*",
"serve": "node ./build/index.js",
"lint:fix": "eslint --fix ./**/*.ts" "lint:fix": "eslint --fix ./**/*.ts"
}, },
"author": "Ahmed Bouhuolia, <a.bouhuolia@gmail.com>", "author": "Ahmed Bouhuolia, <a.bouhuolia@gmail.com>",

View File

@@ -1,23 +1,26 @@
import { Request, Response, Router } from 'express'; import { Request, Response, Router } from 'express';
import { check, ValidationChain } from 'express-validator'; import { check, ValidationChain } from 'express-validator';
import { Service, Inject } from 'typedi'; import { Service, Inject } from 'typedi';
import countries from 'country-codes-list';
import parsePhoneNumber from 'libphonenumber-js';
import BaseController from '@/api/controllers/BaseController'; import BaseController from '@/api/controllers/BaseController';
import asyncMiddleware from '@/api/middleware/asyncMiddleware'; import asyncMiddleware from '@/api/middleware/asyncMiddleware';
import AuthenticationService from '@/services/Authentication';
import { ILoginDTO, ISystemUser, IRegisterDTO } from '@/interfaces'; import { ILoginDTO, ISystemUser, IRegisterDTO } from '@/interfaces';
import { ServiceError, ServiceErrors } from '@/exceptions'; import { ServiceError, ServiceErrors } from '@/exceptions';
import { DATATYPES_LENGTH } from '@/data/DataTypes'; import { DATATYPES_LENGTH } from '@/data/DataTypes';
import LoginThrottlerMiddleware from '@/api/middleware/LoginThrottlerMiddleware'; import LoginThrottlerMiddleware from '@/api/middleware/LoginThrottlerMiddleware';
import AuthenticationApplication from '@/services/Authentication/AuthApplication'; import config from '@/config';
@Service() @Service()
export default class AuthenticationController extends BaseController { export default class AuthenticationController extends BaseController {
@Inject() @Inject()
private authApplication: AuthenticationApplication; authService: AuthenticationService;
/** /**
* Constructor method. * Constructor method.
*/ */
public router() { router() {
const router = Router(); const router = Router();
router.post( router.post(
@@ -53,10 +56,9 @@ export default class AuthenticationController extends BaseController {
} }
/** /**
* Login validation schema. * Login schema.
* @returns {ValidationChain[]}
*/ */
private get loginSchema(): ValidationChain[] { get loginSchema(): ValidationChain[] {
return [ return [
check('crediential').exists().isEmail(), check('crediential').exists().isEmail(),
check('password').exists().isLength({ min: 5 }), check('password').exists().isLength({ min: 5 }),
@@ -64,10 +66,9 @@ export default class AuthenticationController extends BaseController {
} }
/** /**
* Register validation schema. * Register schema.
* @returns {ValidationChain[]}
*/ */
private get registerSchema(): ValidationChain[] { get registerSchema(): ValidationChain[] {
return [ return [
check('first_name') check('first_name')
.exists() .exists()
@@ -88,20 +89,71 @@ export default class AuthenticationController extends BaseController {
.trim() .trim()
.escape() .escape()
.isLength({ max: DATATYPES_LENGTH.STRING }), .isLength({ max: DATATYPES_LENGTH.STRING }),
check('phone_number')
.exists()
.isString()
.trim()
.escape()
.custom(this.phoneNumberValidator)
.isLength({ max: DATATYPES_LENGTH.STRING }),
check('password') check('password')
.exists() .exists()
.isString() .isString()
.trim() .trim()
.escape() .escape()
.isLength({ max: DATATYPES_LENGTH.STRING }), .isLength({ max: DATATYPES_LENGTH.STRING }),
check('country')
.exists()
.isString()
.trim()
.escape()
.custom(this.countryValidator)
.isLength({ max: DATATYPES_LENGTH.STRING }),
]; ];
} }
/** /**
* Reset password schema. * Country validator.
* @returns {ValidationChain[]}
*/ */
private get resetPasswordSchema(): ValidationChain[] { 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.
*/
get resetPasswordSchema(): ValidationChain[] {
return [ return [
check('password') check('password')
.exists() .exists()
@@ -118,9 +170,8 @@ export default class AuthenticationController extends BaseController {
/** /**
* Send reset password validation schema. * Send reset password validation schema.
* @returns {ValidationChain[]}
*/ */
private get sendResetPasswordSchema(): ValidationChain[] { get sendResetPasswordSchema(): ValidationChain[] {
return [check('email').exists().isEmail().trim().escape()]; return [check('email').exists().isEmail().trim().escape()];
} }
@@ -129,11 +180,11 @@ export default class AuthenticationController extends BaseController {
* @param {Request} req * @param {Request} req
* @param {Response} res * @param {Response} res
*/ */
private async login(req: Request, res: Response, next: Function): Response { async login(req: Request, res: Response, next: Function): Response {
const userDTO: ILoginDTO = this.matchedBodyData(req); const userDTO: ILoginDTO = this.matchedBodyData(req);
try { try {
const { token, user, tenant } = await this.authApplication.signIn( const { token, user, tenant } = await this.authService.signIn(
userDTO.crediential, userDTO.crediential,
userDTO.password userDTO.password
); );
@@ -148,11 +199,13 @@ export default class AuthenticationController extends BaseController {
* @param {Request} req * @param {Request} req
* @param {Response} res * @param {Response} res
*/ */
private async register(req: Request, res: Response, next: Function) { async register(req: Request, res: Response, next: Function) {
const registerDTO: IRegisterDTO = this.matchedBodyData(req); const registerDTO: IRegisterDTO = this.matchedBodyData(req);
try { try {
await this.authApplication.signUp(registerDTO); const registeredUser: ISystemUser = await this.authService.register(
registerDTO
);
return res.status(200).send({ return res.status(200).send({
type: 'success', type: 'success',
@@ -169,11 +222,11 @@ export default class AuthenticationController extends BaseController {
* @param {Request} req * @param {Request} req
* @param {Response} res * @param {Response} res
*/ */
private async sendResetPassword(req: Request, res: Response, next: Function) { async sendResetPassword(req: Request, res: Response, next: Function) {
const { email } = this.matchedBodyData(req); const { email } = this.matchedBodyData(req);
try { try {
await this.authApplication.sendResetPassword(email); await this.authService.sendResetPassword(email);
return res.status(200).send({ return res.status(200).send({
code: 'SEND_RESET_PASSWORD_SUCCESS', code: 'SEND_RESET_PASSWORD_SUCCESS',
@@ -191,12 +244,12 @@ export default class AuthenticationController extends BaseController {
* @param {Request} req * @param {Request} req
* @param {Response} res * @param {Response} res
*/ */
private async resetPassword(req: Request, res: Response, next: Function) { async resetPassword(req: Request, res: Response, next: Function) {
const { token } = req.params; const { token } = req.params;
const { password } = req.body; const { password } = req.body;
try { try {
await this.authApplication.resetPassword(token, password); await this.authService.resetPassword(token, password);
return res.status(200).send({ return res.status(200).send({
type: 'RESET_PASSWORD_SUCCESS', type: 'RESET_PASSWORD_SUCCESS',
@@ -210,7 +263,7 @@ export default class AuthenticationController extends BaseController {
/** /**
* Handles the service errors. * Handles the service errors.
*/ */
private handlerErrors(error, req: Request, res: Response, next: Function) { handlerErrors(error, req: Request, res: Response, next: Function) {
if (error instanceof ServiceError) { if (error instanceof ServiceError) {
if ( if (
['INVALID_DETAILS', 'invalid_password'].indexOf(error.errorType) !== -1 ['INVALID_DETAILS', 'invalid_password'].indexOf(error.errorType) !== -1
@@ -242,10 +295,18 @@ export default class AuthenticationController extends BaseController {
errors: [{ type: 'EMAIL.NOT.REGISTERED', code: 500 }], errors: [{ type: 'EMAIL.NOT.REGISTERED', code: 500 }],
}); });
} }
if (error.errorType === 'EMAIL_EXISTS') { }
return res.status(400).send({ if (error instanceof ServiceErrors) {
errors: [{ type: 'EMAIL.EXISTS', code: 600 }], const errorReasons = [];
});
if (error.hasType('PHONE_NUMBER_EXISTS')) {
errorReasons.push({ type: 'PHONE_NUMBER_EXISTS', code: 100 });
}
if (error.hasType('EMAIL_EXISTS')) {
errorReasons.push({ type: 'EMAIL.EXISTS', code: 200 });
}
if (errorReasons.length > 0) {
return res.boom.badRequest(null, { errors: errorReasons });
} }
} }
next(error); next(error);

View File

@@ -11,10 +11,10 @@ import AcceptInviteUserService from '@/services/InviteUsers/AcceptInviteUser';
@Service() @Service()
export default class InviteUsersController extends BaseController { export default class InviteUsersController extends BaseController {
@Inject() @Inject()
private inviteUsersService: InviteTenantUserService; inviteUsersService: InviteTenantUserService;
@Inject() @Inject()
private acceptInviteService: AcceptInviteUserService; acceptInviteService: AcceptInviteUserService;
/** /**
* Routes that require authentication. * Routes that require authentication.
@@ -68,13 +68,13 @@ export default class InviteUsersController extends BaseController {
/** /**
* Invite DTO schema validation. * Invite DTO schema validation.
* @returns {ValidationChain[]}
*/ */
private get inviteUserDTO() { get inviteUserDTO() {
return [ return [
check('first_name').exists().trim().escape(), check('first_name').exists().trim().escape(),
check('last_name').exists().trim().escape(), check('last_name').exists().trim().escape(),
check('password').exists().trim().escape().isLength({ min: 5 }), check('phone_number').exists().trim().escape(),
check('password').exists().trim().escape(),
param('token').exists().trim().escape(), param('token').exists().trim().escape(),
]; ];
} }
@@ -85,13 +85,17 @@ export default class InviteUsersController extends BaseController {
* @param {Response} res - Response object. * @param {Response} res - Response object.
* @param {NextFunction} next - Next function. * @param {NextFunction} next - Next function.
*/ */
private async sendInvite(req: Request, res: Response, next: Function) { async sendInvite(req: Request, res: Response, next: Function) {
const sendInviteDTO = this.matchedBodyData(req); const sendInviteDTO = this.matchedBodyData(req);
const { tenantId } = req; const { tenantId } = req;
const { user } = req; const { user } = req;
try { try {
await this.inviteUsersService.sendInvite(tenantId, sendInviteDTO, user); const { invite } = await this.inviteUsersService.sendInvite(
tenantId,
sendInviteDTO,
user
);
return res.status(200).send({ return res.status(200).send({
type: 'success', type: 'success',
code: 'INVITE.SENT.SUCCESSFULLY', code: 'INVITE.SENT.SUCCESSFULLY',
@@ -108,7 +112,7 @@ export default class InviteUsersController extends BaseController {
* @param {Response} res - Response object. * @param {Response} res - Response object.
* @param {NextFunction} next - Next function. * @param {NextFunction} next - Next function.
*/ */
private async resendInvite(req: Request, res: Response, next: NextFunction) { async resendInvite(req: Request, res: Response, next: NextFunction) {
const { tenantId, user } = req; const { tenantId, user } = req;
const { userId } = req.params; const { userId } = req.params;
@@ -131,7 +135,7 @@ export default class InviteUsersController extends BaseController {
* @param {Response} res - * @param {Response} res -
* @param {NextFunction} next - * @param {NextFunction} next -
*/ */
private async accept(req: Request, res: Response, next: Function) { async accept(req: Request, res: Response, next: Function) {
const inviteUserInput: IInviteUserInput = this.matchedBodyData(req, { const inviteUserInput: IInviteUserInput = this.matchedBodyData(req, {
locations: ['body'], locations: ['body'],
includeOptionals: true, includeOptionals: true,
@@ -157,7 +161,7 @@ export default class InviteUsersController extends BaseController {
* @param {Response} res - * @param {Response} res -
* @param {NextFunction} next - * @param {NextFunction} next -
*/ */
private async invited(req: Request, res: Response, next: Function) { async invited(req: Request, res: Response, next: Function) {
const { token } = req.params; const { token } = req.params;
try { try {
@@ -177,12 +181,7 @@ export default class InviteUsersController extends BaseController {
/** /**
* Handles the service error. * Handles the service error.
*/ */
private handleServicesError( handleServicesError(error, req: Request, res: Response, next: Function) {
error,
req: Request,
res: Response,
next: Function
) {
if (error instanceof ServiceError) { if (error instanceof ServiceError) {
if (error.errorType === 'EMAIL_EXISTS') { if (error.errorType === 'EMAIL_EXISTS') {
return res.status(400).send({ return res.status(400).send({

View File

@@ -8,12 +8,18 @@ import JWTAuth from '@/api/middleware/jwtAuth';
import TenancyMiddleware from '@/api/middleware/TenancyMiddleware'; import TenancyMiddleware from '@/api/middleware/TenancyMiddleware';
import AttachCurrentTenantUser from '@/api/middleware/AttachCurrentTenantUser'; import AttachCurrentTenantUser from '@/api/middleware/AttachCurrentTenantUser';
import OrganizationService from '@/services/Organization/OrganizationService'; import OrganizationService from '@/services/Organization/OrganizationService';
import { MONTHS, ACCEPTED_LOCALES } from '@/services/Organization/constants'; import {
ACCEPTED_CURRENCIES,
MONTHS,
ACCEPTED_LOCALES,
} from '@/services/Organization/constants';
import { DATE_FORMATS } from '@/services/Miscellaneous/DateFormats/constants'; import { DATE_FORMATS } from '@/services/Miscellaneous/DateFormats/constants';
import { ServiceError } from '@/exceptions'; import { ServiceError } from '@/exceptions';
import BaseController from '@/api/controllers/BaseController'; import BaseController from '@/api/controllers/BaseController';
const ACCEPTED_LOCATIONS = ['libya'];
@Service() @Service()
export default class OrganizationController extends BaseController { export default class OrganizationController extends BaseController {
@Inject() @Inject()
@@ -59,8 +65,8 @@ export default class OrganizationController extends BaseController {
return [ return [
check('name').exists().trim(), check('name').exists().trim(),
check('industry').optional().isString(), check('industry').optional().isString(),
check('location').exists().isString().isISO31661Alpha2(), check('location').exists().isString().isIn(ACCEPTED_LOCATIONS),
check('base_currency').exists().isISO4217(), check('base_currency').exists().isIn(ACCEPTED_CURRENCIES),
check('timezone').exists().isIn(moment.tz.names()), check('timezone').exists().isIn(moment.tz.names()),
check('fiscal_year').exists().isIn(MONTHS), check('fiscal_year').exists().isIn(MONTHS),
check('language').exists().isString().isIn(ACCEPTED_LOCALES), check('language').exists().isString().isIn(ACCEPTED_LOCALES),

View File

@@ -47,6 +47,7 @@ export default class UsersController extends BaseController {
check('first_name').exists(), check('first_name').exists(),
check('last_name').exists(), check('last_name').exists(),
check('email').exists().isEmail(), check('email').exists().isEmail(),
check('phone_number').optional().isMobilePhone(),
check('role_id').exists().isNumeric().toInt(), check('role_id').exists().isNumeric().toInt(),
], ],
this.validationResult, this.validationResult,

View File

@@ -4,7 +4,6 @@ import color from 'colorette';
import argv from 'getopts'; import argv from 'getopts';
import Knex from 'knex'; import Knex from 'knex';
import { knexSnakeCaseMappers } from 'objection'; import { knexSnakeCaseMappers } from 'objection';
import '../before';
import config from '../config'; import config from '../config';
function initSystemKnex() { function initSystemKnex() {

View File

@@ -1,7 +1,13 @@
import dotenv from 'dotenv'; import dotenv from 'dotenv';
import path from 'path';
dotenv.config(); // Set the NODE_ENV to 'development' by default
// process.env.NODE_ENV = process.env.NODE_ENV || 'development';
const envFound = dotenv.config();
if (envFound.error) {
// This error should crash whole process
throw new Error("⚠️ Couldn't find .env file ⚠️");
}
module.exports = { module.exports = {
/** /**
@@ -13,36 +19,36 @@ module.exports = {
* System database configuration. * System database configuration.
*/ */
system: { system: {
db_client: process.env.SYSTEM_DB_CLIENT || process.env.DB_CLIENT || 'mysql', db_client: process.env.SYSTEM_DB_CLIENT,
db_host: process.env.SYSTEM_DB_HOST || process.env.DB_HOST, db_host: process.env.SYSTEM_DB_HOST,
db_user: process.env.SYSTEM_DB_USER || process.env.DB_USER, db_user: process.env.SYSTEM_DB_USER,
db_password: process.env.SYSTEM_DB_PASSWORD || process.env.DB_PASSWORD, db_password: process.env.SYSTEM_DB_PASSWORD,
db_name: process.env.SYSTEM_DB_NAME, db_name: process.env.SYSTEM_DB_NAME,
charset: process.env.SYSTEM_DB_CHARSET || process.env.DB_CHARSET, charset: process.env.SYSTEM_DB_CHARSET,
migrations_dir: path.join(global.__root_dir, './src/system/migrations'), migrations_dir: process.env.SYSTEM_MIGRATIONS_DIR,
seeds_dir: path.join(global.__root_dir, './src/system/seeds'), seeds_dir: process.env.SYSTEM_SEEDS_DIR,
}, },
/** /**
* Tenant database configuration. * Tenant database configuration.
*/ */
tenant: { tenant: {
db_client: process.env.TENANT_DB_CLIENT || process.env.DB_CLIENT || 'mysql', db_client: process.env.TENANT_DB_CLIENT,
db_name_prefix: process.env.TENANT_DB_NAME_PERFIX, db_name_prefix: process.env.TENANT_DB_NAME_PERFIX,
db_host: process.env.TENANT_DB_HOST || process.env.DB_HOST, db_host: process.env.TENANT_DB_HOST,
db_user: process.env.TENANT_DB_USER || process.env.DB_USER, db_user: process.env.TENANT_DB_USER,
db_password: process.env.TENANT_DB_PASSWORD || process.env.DB_PASSWORD, db_password: process.env.TENANT_DB_PASSWORD,
charset: process.env.TENANT_DB_CHARSET || process.env.DB_CHARSET, charset: process.env.TENANT_DB_CHARSET,
migrations_dir: path.join(global.__root_dir, './src/database/migrations'), migrations_dir: process.env.TENANT_MIGRATIONS_DIR,
seeds_dir: path.join(global.__root_dir, './src/database/seeds/core'), seeds_dir: process.env.TENANT_SEEDS_DIR,
}, },
/** /**
* Databases manager config. * Databases manager config.
*/ */
manager: { manager: {
superUser: process.env.SYSTEM_DB_USER || process.env.DB_USER, superUser: process.env.DB_MANAGER_SUPER_USER,
superPassword: process.env.SYSTEM_DB_PASSWORD || process.env.DB_PASSWORD, superPassword: process.env.DB_MANAGER_SUPER_PASSWORD,
}, },
/** /**
@@ -113,6 +119,14 @@ module.exports = {
prefix: '/api', prefix: '/api',
}, },
/**
* Licenses api basic authentication.
*/
licensesAuth: {
user: process.env.LICENSES_AUTH_USER,
password: process.env.LICENSES_AUTH_PASSWORD,
},
/** /**
* Redis storage configuration. * Redis storage configuration.
*/ */

View File

@@ -1,9 +0,0 @@
exports.up = function (knex) {
return knex.schema.table('users', (table) => {
table.dropColumn('phone_number');
});
};
exports.down = function (knex) {
return knex.schema.table('users', (table) => {});
};

View File

@@ -1,77 +1,29 @@
import { ISystemUser } from './User'; import { ISystemUser } from './User';
import { ITenant } from './Tenancy'; import { ITenant } from './Tenancy';
import { SystemUser } from '@/system/models';
export interface IRegisterDTO { export interface IRegisterDTO {
firstName: string; firstName: string,
lastName: string; lastName: string,
email: string; email: string,
password: string; password: string,
organizationName: string; organizationName: string,
} };
export interface ILoginDTO { export interface ILoginDTO {
crediential: string; crediential: string,
password: string; password: string,
} };
export interface IPasswordReset { export interface IPasswordReset {
id: number; id: number,
email: string; email: string,
token: string; token: string,
createdAt: Date; createdAt: Date,
} };
export interface IAuthenticationService { export interface IAuthenticationService {
signIn( signIn(emailOrPhone: string, password: string): Promise<{ user: ISystemUser, token: string, tenant: ITenant }>;
email: string,
password: string
): Promise<{ user: ISystemUser; token: string; tenant: ITenant }>;
register(registerDTO: IRegisterDTO): Promise<ISystemUser>; register(registerDTO: IRegisterDTO): Promise<ISystemUser>;
sendResetPassword(email: string): Promise<IPasswordReset>; sendResetPassword(email: string): Promise<IPasswordReset>;
resetPassword(token: string, password: string): Promise<void>; 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;
} }

View File

@@ -9,6 +9,7 @@ export interface ISystemUser extends Model {
active: boolean; active: boolean;
password: string; password: string;
email: string; email: string;
phoneNumber: string;
roleId: number; roleId: number;
tenantId: number; tenantId: number;
@@ -25,6 +26,7 @@ export interface ISystemUserDTO {
firstName: string; firstName: string;
lastName: string; lastName: string;
password: string; password: string;
phoneNumber: string;
active: boolean; active: boolean;
email: string; email: string;
roleId?: number; roleId?: number;
@@ -33,6 +35,7 @@ export interface ISystemUserDTO {
export interface IEditUserDTO { export interface IEditUserDTO {
firstName: string; firstName: string;
lastName: string; lastName: string;
phoneNumber: string;
active: boolean; active: boolean;
email: string; email: string;
roleId: number; roleId: number;
@@ -41,6 +44,7 @@ export interface IEditUserDTO {
export interface IInviteUserInput { export interface IInviteUserInput {
firstName: string; firstName: string;
lastName: string; lastName: string;
phoneNumber: string;
password: string; password: string;
} }
export interface IUserInvite { export interface IUserInvite {
@@ -107,6 +111,7 @@ export interface ITenantUser {
id?: number; id?: number;
firstName: string; firstName: string;
lastName: string; lastName: string;
phoneNumber: string;
active: boolean; active: boolean;
email: string; email: string;
roleId?: number; roleId?: number;

View File

@@ -1,5 +1,5 @@
import { Container, Inject } from 'typedi'; import { Container, Inject } from 'typedi';
import AuthenticationService from '@/services/Authentication/AuthApplication'; import AuthenticationService from '@/services/Authentication';
export default class WelcomeEmailJob { export default class WelcomeEmailJob {
/** /**

View File

@@ -1,5 +1,5 @@
import { Container, Inject } from 'typedi'; import { Container, Inject } from 'typedi';
import AuthenticationService from '@/services/Authentication/AuthApplication'; import AuthenticationService from '@/services/Authentication';
export default class WelcomeSMSJob { export default class WelcomeSMSJob {
/** /**

View File

@@ -1,5 +1,5 @@
import { Container } from 'typedi'; import { Container } from 'typedi';
import AuthenticationService from '@/services/Authentication/AuthApplication'; import AuthenticationService from '@/services/Authentication';
export default class WelcomeEmailJob { export default class WelcomeEmailJob {
/** /**

View File

@@ -1,6 +1,6 @@
import 'reflect-metadata'; // We need this in order to use @Decorators import 'reflect-metadata'; // We need this in order to use @Decorators
import './before';
import '@/config'; import '@/config';
import './before';
import express from 'express'; import express from 'express';
import loadersFactory from 'loaders'; import loadersFactory from 'loaders';

View File

@@ -1,56 +0,0 @@
import { Service, Inject, Container } from 'typedi';
import { IRegisterDTO, ISystemUser, IPasswordReset } from '@/interfaces';
import { AuthSigninService } from './AuthSignin';
import { AuthSignupService } from './AuthSignup';
import { AuthSendResetPassword } from './AuthSendResetPassword';
@Service()
export default class AuthenticationApplication {
@Inject()
private authSigninService: AuthSigninService;
@Inject()
private authSignupService: AuthSignupService;
@Inject()
private authResetPasswordService: AuthSendResetPassword;
/**
* 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);
}
}

View File

@@ -1,130 +0,0 @@
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;
}
}

View File

@@ -1,103 +0,0 @@
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 };
}
}

View File

@@ -1,77 +0,0 @@
import { 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';
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 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);
}
}
}

View File

@@ -1,10 +0,0 @@
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',
};

View File

@@ -1,22 +0,0 @@
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
);
};

View File

@@ -0,0 +1,322 @@
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
);
}
}

View File

@@ -3,6 +3,8 @@ import moment from 'moment';
import { ServiceError } from '@/exceptions'; import { ServiceError } from '@/exceptions';
import { Invite, SystemUser, Tenant } from '@/system/models'; import { Invite, SystemUser, Tenant } from '@/system/models';
import { hashPassword } from 'utils'; import { hashPassword } from 'utils';
import TenancyService from '@/services/Tenancy/TenancyService';
import InviteUsersMailMessages from '@/services/InviteUsers/InviteUsersMailMessages';
import events from '@/subscribers/events'; import events from '@/subscribers/events';
import { import {
IAcceptInviteEventPayload, IAcceptInviteEventPayload,
@@ -10,13 +12,29 @@ import {
ICheckInviteEventPayload, ICheckInviteEventPayload,
IUserInvite, IUserInvite,
} from '@/interfaces'; } from '@/interfaces';
import TenantsManagerService from '@/services/Tenancy/TenantsManager';
import { ERRORS } from './constants'; import { ERRORS } from './constants';
import { EventPublisher } from '@/lib/EventPublisher/EventPublisher'; import { EventPublisher } from '@/lib/EventPublisher/EventPublisher';
@Service() @Service()
export default class AcceptInviteUserService { export default class AcceptInviteUserService {
@Inject() @Inject()
private eventPublisher: EventPublisher; eventPublisher: EventPublisher;
@Inject()
tenancy: TenancyService;
@Inject('logger')
logger: any;
@Inject()
mailMessages: InviteUsersMailMessages;
@Inject('repositories')
sysRepositories: any;
@Inject()
tenantsManager: TenantsManagerService;
/** /**
* Accept the received invite. * Accept the received invite.
@@ -32,6 +50,9 @@ export default class AcceptInviteUserService {
// Retrieve the invite token or throw not found error. // Retrieve the invite token or throw not found error.
const inviteToken = await this.getInviteTokenOrThrowError(token); const inviteToken = await this.getInviteTokenOrThrowError(token);
// Validates the user phone number.
await this.validateUserPhoneNumberNotExists(inviteUserDTO.phoneNumber);
// Hash the given password. // Hash the given password.
const hashedPassword = await hashPassword(inviteUserDTO.password); const hashedPassword = await hashPassword(inviteUserDTO.password);

View File

@@ -14,6 +14,8 @@ export const DATE_FORMATS = [
'MMMM dd, YYYY', 'MMMM dd, YYYY',
'EEE, MMMM dd, YYYY', 'EEE, MMMM dd, YYYY',
]; ];
export const ACCEPTED_CURRENCIES = Object.keys(currencies);
export const MONTHS = [ export const MONTHS = [
'january', 'january',
'february', 'february',

View File

@@ -17,17 +17,20 @@ import { EventPublisher } from '@/lib/EventPublisher/EventPublisher';
@Service() @Service()
export default class UsersService { export default class UsersService {
@Inject('logger')
logger: any;
@Inject('repositories') @Inject('repositories')
private repositories: any; repositories: any;
@Inject() @Inject()
private rolesService: RolesService; rolesService: RolesService;
@Inject() @Inject()
private tenancy: HasTenancyService; tenancy: HasTenancyService;
@Inject() @Inject()
private eventPublisher: EventPublisher; eventPublisher: EventPublisher;
/** /**
* Creates a new user. * Creates a new user.
@@ -43,7 +46,7 @@ export default class UsersService {
authorizedUser: ISystemUser authorizedUser: ISystemUser
): Promise<any> { ): Promise<any> {
const { User } = this.tenancy.models(tenantId); const { User } = this.tenancy.models(tenantId);
const { email } = editUserDTO; const { email, phoneNumber } = editUserDTO;
// Retrieve the tenant user or throw not found service error. // Retrieve the tenant user or throw not found service error.
const oldTenantUser = await this.getTenantUserOrThrowError( const oldTenantUser = await this.getTenantUserOrThrowError(
@@ -59,6 +62,9 @@ export default class UsersService {
// Validate user email should be unique. // Validate user email should be unique.
await this.validateUserEmailUniquiness(tenantId, email, userId); 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. // Retrieve the given role or throw not found service error.
const role = await this.rolesService.getRoleOrThrowError( const role = await this.rolesService.getRoleOrThrowError(
tenantId, tenantId,
@@ -289,6 +295,27 @@ 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. * Validate the authorized user cannot mutate its role.
* @param {ITenantUser} oldTenantUser * @param {ITenantUser} oldTenantUser

View File

@@ -1,29 +1,27 @@
import { Container, Service } from 'typedi'; import { Container, Service } from 'typedi';
import events from '@/subscribers/events'; import events from '@/subscribers/events';
import { IAuthSignedInEventPayload } from '@/interfaces';
@Service() @Service()
export default class ResetLoginThrottleSubscriber { export default class ResetLoginThrottleSubscriber {
/** /**
* Attaches events with handlers. * Attaches events with handlers.
* @param bus * @param bus
*/ */
public attach(bus) { public attach(bus) {
bus.subscribe(events.auth.signIn, this.resetLoginThrottleOnceSuccessLogin); bus.subscribe(events.auth.login, this.resetLoginThrottleOnceSuccessLogin);
} }
/** /**
* Resets the login throttle once the login success. * Resets the login throttle once the login success.
* @param {IAuthSignedInEventPayload} payload -
*/ */
private async resetLoginThrottleOnceSuccessLogin( private async resetLoginThrottleOnceSuccessLogin(payload) {
payload: IAuthSignedInEventPayload const { emailOrPhone, password, user } = payload;
) {
const { email, user } = payload;
const loginThrottler = Container.get('rateLimiter.login'); const loginThrottler = Container.get('rateLimiter.login');
// Reset the login throttle by the given email and phone number. // Reset the login throttle by the given email and phone number.
await loginThrottler.reset(user.email); await loginThrottler.reset(user.email);
await loginThrottler.reset(email); await loginThrottler.reset(user.phoneNumber);
await loginThrottler.reset(emailOrPhone);
} }
} }

View File

@@ -10,14 +10,14 @@ export default class AuthSendWelcomeMailSubscriber {
* Attaches events with handlers. * Attaches events with handlers.
*/ */
public attach(bus) { public attach(bus) {
bus.subscribe(events.auth.signUp, this.sendWelcomeEmailOnceUserRegister); bus.subscribe(events.auth.register, this.sendWelcomeEmailOnceUserRegister);
} }
/** /**
* Sends welcome email once the user register. * Sends welcome email once the user register.
*/ */
private sendWelcomeEmailOnceUserRegister = async (payload) => { private sendWelcomeEmailOnceUserRegister = async (payload) => {
const { tenant, user } = payload; const { registerDTO, tenant, user } = payload;
// Send welcome mail to the user. // Send welcome mail to the user.
await this.agenda.now('welcome-email', { await this.agenda.now('welcome-email', {

View File

@@ -3,17 +3,10 @@ export default {
* Authentication service. * Authentication service.
*/ */
auth: { auth: {
signIn: 'onSignIn', login: 'onLogin',
signingIn: 'onSigningIn', register: 'onRegister',
signUp: 'onSignUp',
signingUp: 'onSigningUp',
sendingResetPassword: 'onSendingResetPassword',
sendResetPassword: 'onSendResetPassword', sendResetPassword: 'onSendResetPassword',
resetPassword: 'onResetPassword', resetPassword: 'onResetPassword',
resetingPassword: 'onResetingPassword'
}, },
/** /**

View File

@@ -1,9 +0,0 @@
exports.up = function (knex) {
return knex.schema.table('users', (table) => {
table.dropColumn('phone_number');
});
};
exports.down = function (knex) {
return knex.schema.table('users', (table) => {});
};

View File

@@ -13,7 +13,7 @@ import AppIntlLoader from './AppIntlLoader';
import PrivateRoute from '@/components/Guards/PrivateRoute'; import PrivateRoute from '@/components/Guards/PrivateRoute';
import GlobalErrors from '@/containers/GlobalErrors/GlobalErrors'; import GlobalErrors from '@/containers/GlobalErrors/GlobalErrors';
import DashboardPrivatePages from '@/components/Dashboard/PrivatePages'; import DashboardPrivatePages from '@/components/Dashboard/PrivatePages';
import { Authentication } from '@/containers/Authentication/Authentication'; import Authentication from '@/components/Authentication';
import { SplashScreen, DashboardThemeProvider } from '../components'; import { SplashScreen, DashboardThemeProvider } from '../components';
import { queryConfig } from '../hooks/query/base'; import { queryConfig } from '../hooks/query/base';

View File

@@ -0,0 +1,62 @@
// @ts-nocheck
import React from 'react';
import { Redirect, Route, Switch, Link, useLocation } from 'react-router-dom';
import BodyClassName from 'react-body-classname';
import { TransitionGroup, CSSTransition } from 'react-transition-group';
import authenticationRoutes from '@/routes/authentication';
import { Icon, FormattedMessage as T } from '@/components';
import { useIsAuthenticated } from '@/hooks/state';
import '@/style/pages/Authentication/Auth.scss';
function PageFade(props) {
return <CSSTransition {...props} classNames="authTransition" timeout={500} />;
}
export default function AuthenticationWrapper({ ...rest }) {
const to = { pathname: '/' };
const location = useLocation();
const isAuthenticated = useIsAuthenticated();
const locationKey = location.pathname;
return (
<>
{isAuthenticated ? (
<Redirect to={to} />
) : (
<BodyClassName className={'authentication'}>
<div class="authentication-page">
<a
href={'http://bigcapital.ly'}
className={'authentication-page__goto-bigcapital'}
>
<T id={'go_to_bigcapital_com'} />
</a>
<div class="authentication-page__form-wrapper">
<div class="authentication-insider">
<div className={'authentication-insider__logo-section'}>
<Icon icon="bigcapital" height={37} width={214} />
</div>
<TransitionGroup>
<PageFade key={locationKey}>
<Switch>
{authenticationRoutes.map((route, index) => (
<Route
key={index}
path={route.path}
exact={route.exact}
component={route.component}
/>
))}
</Switch>
</PageFade>
</TransitionGroup>
</div>
</div>
</div>
</BodyClassName>
)}
</>
);
}

File diff suppressed because it is too large Load Diff

View File

@@ -3,4 +3,5 @@ import intl from 'react-intl-universal';
export const getLanguages = () => [ export const getLanguages = () => [
{ name: intl.get('english'), value: 'en' }, { name: intl.get('english'), value: 'en' },
{ name: intl.get('arabic'), value: 'ar' },
]; ];

View File

@@ -1,7 +1,20 @@
// @ts-nocheck // @ts-nocheck
import React from 'react'; import React from 'react';
import moment from 'moment';
import intl from 'react-intl-universal';
import { Icon } from '@/components/Icon'; import { Icon } from '@/components/Icon';
export default function AuthCopyright() { export default function AuthCopyright() {
return <Icon width={122} height={22} icon={'bigcapital'} />; return (
<div class="auth-copyright">
<div class="auth-copyright__text">
{intl.get('all_rights_reserved', {
pre: moment().subtract(1, 'years').year(),
current: moment().get('year'),
})}
</div>
<Icon width={122} height={22} icon={'bigcapital'} />
</div>
);
} }

View File

@@ -1,8 +1,6 @@
// @ts-nocheck // @ts-nocheck
import React from 'react'; import React from 'react';
import styled from 'styled-components';
import AuthCopyright from './AuthCopyright'; import AuthCopyright from './AuthCopyright';
import { AuthInsiderContent, AuthInsiderCopyright } from './_components';
/** /**
* Authentication insider page. * Authentication insider page.
@@ -11,21 +9,16 @@ export default function AuthInsider({
logo = true, logo = true,
copyright = true, copyright = true,
children, children,
classNames,
}) { }) {
return ( return (
<AuthInsiderContent> <div class="authentication-insider__content">
<AuthInsiderContentWrap className={classNames?.content}> <div class="authentication-insider__form">
{children} { children }
</AuthInsiderContentWrap> </div>
{copyright && ( <div class="authentication-insider__footer">
<AuthInsiderCopyright className={classNames?.copyrightWrap}> <AuthCopyright />
<AuthCopyright /> </div>
</AuthInsiderCopyright> </div>
)}
</AuthInsiderContent>
); );
} }
const AuthInsiderContentWrap = styled.div``;

View File

@@ -1,66 +0,0 @@
// @ts-nocheck
import React from 'react';
import { Redirect, Route, Switch, useLocation } from 'react-router-dom';
import BodyClassName from 'react-body-classname';
import styled from 'styled-components';
import { TransitionGroup, CSSTransition } from 'react-transition-group';
import authenticationRoutes from '@/routes/authentication';
import { Icon, FormattedMessage as T } from '@/components';
import { useIsAuthenticated } from '@/hooks/state';
import '@/style/pages/Authentication/Auth.scss';
export function Authentication() {
const to = { pathname: '/' };
const location = useLocation();
const isAuthenticated = useIsAuthenticated();
const locationKey = location.pathname;
if (isAuthenticated) {
return <Redirect to={to} />;
}
return (
<BodyClassName className={'authentication'}>
<AuthPage>
<AuthInsider>
<AuthLogo>
<Icon icon="bigcapital" height={37} width={214} />
</AuthLogo>
<TransitionGroup>
<CSSTransition
timeout={500}
key={locationKey}
classNames="authTransition"
>
<Switch>
{authenticationRoutes.map((route, index) => (
<Route
key={index}
path={route.path}
exact={route.exact}
component={route.component}
/>
))}
</Switch>
</CSSTransition>
</TransitionGroup>
</AuthInsider>
</AuthPage>
</BodyClassName>
);
}
const AuthPage = styled.div``;
const AuthInsider = styled.div`
width: 384px;
margin: 0 auto;
margin-bottom: 40px;
padding-top: 80px;
`;
const AuthLogo = styled.div`
text-align: center;
margin-bottom: 40px;
`;

View File

@@ -4,21 +4,13 @@ import intl from 'react-intl-universal';
import { Formik } from 'formik'; import { Formik } from 'formik';
import { useHistory } from 'react-router-dom'; import { useHistory } from 'react-router-dom';
import { Intent, Position } from '@blueprintjs/core'; import { Intent, Position } from '@blueprintjs/core';
import { FormattedMessage as T } from '@/components';
import { isEmpty } from 'lodash'; import { isEmpty } from 'lodash';
import { useInviteAcceptContext } from './InviteAcceptProvider'; import { useInviteAcceptContext } from './InviteAcceptProvider';
import { AppToaster } from '@/components'; import { AppToaster } from '@/components';
import { InviteAcceptSchema } from './utils'; import { InviteAcceptSchema } from './utils';
import InviteAcceptFormContent from './InviteAcceptFormContent'; import InviteAcceptFormContent from './InviteAcceptFormContent';
import { AuthInsiderCard } from './_components';
const initialValues = {
organization_name: '',
invited_email: '',
first_name: '',
last_name: '',
password: '',
};
export default function InviteAcceptForm() { export default function InviteAcceptForm() {
const history = useHistory(); const history = useHistory();
@@ -27,8 +19,9 @@ export default function InviteAcceptForm() {
const { inviteAcceptMutate, inviteMeta, token } = useInviteAcceptContext(); const { inviteAcceptMutate, inviteMeta, token } = useInviteAcceptContext();
// Invite value. // Invite value.
const inviteFormValue = { const inviteValue = {
...initialValues, organization_name: '',
invited_email: '',
...(!isEmpty(inviteMeta) ...(!isEmpty(inviteMeta)
? { ? {
invited_email: inviteMeta.email, invited_email: inviteMeta.email,
@@ -40,17 +33,19 @@ export default function InviteAcceptForm() {
// Handle form submitting. // Handle form submitting.
const handleSubmit = (values, { setSubmitting, setErrors }) => { const handleSubmit = (values, { setSubmitting, setErrors }) => {
inviteAcceptMutate([values, token]) inviteAcceptMutate([values, token])
.then(() => { .then((response) => {
AppToaster.show({ AppToaster.show({
message: intl.getHTML( message: intl.getHTML(
'congrats_your_account_has_been_created_and_invited', 'congrats_your_account_has_been_created_and_invited',
{ {
organization_name: inviteMeta.organizationName, organization_name: inviteValue.organization_name,
}, },
), ),
intent: Intent.SUCCESS, intent: Intent.SUCCESS,
}); });
history.push('/auth/login'); history.push('/auth/login');
setSubmitting(false);
}) })
.catch( .catch(
({ ({
@@ -85,13 +80,23 @@ export default function InviteAcceptForm() {
}; };
return ( return (
<AuthInsiderCard> <div className={'invite-form'}>
<div className={'authentication-page__label-section'}>
<h3>
<T id={'welcome_to_bigcapital'} />
</h3>
<p>
<T id={'enter_your_personal_information'} />{' '}
<b>{inviteValue.organization_name}</b> <T id={'organization'} />
</p>
</div>
<Formik <Formik
validationSchema={InviteAcceptSchema} validationSchema={InviteAcceptSchema}
initialValues={inviteFormValue} initialValues={inviteValue}
onSubmit={handleSubmit} onSubmit={handleSubmit}
component={InviteAcceptFormContent} component={InviteAcceptFormContent}
/> />
</AuthInsiderCard> </div>
); );
} }

View File

@@ -1,73 +1,110 @@
// @ts-nocheck // @ts-nocheck
import React, { useState } from 'react'; import React from 'react';
import intl from 'react-intl-universal'; import intl from 'react-intl-universal';
import { Button, InputGroup, Intent } from '@blueprintjs/core'; import { Button, InputGroup, Intent, FormGroup } from '@blueprintjs/core';
import { Form, useFormikContext } from 'formik'; import { Form, ErrorMessage, FastField, useFormikContext } from 'formik';
import { Link } from 'react-router-dom'; import { Link } from 'react-router-dom';
import { Tooltip2 } from '@blueprintjs/popover2'; import { Col, Row, FormattedMessage as T } from '@/components';
import styled from 'styled-components'; import { inputIntent } from '@/utils';
import {
Col,
FFormGroup,
FInputGroup,
Row,
FormattedMessage as T,
} from '@/components';
import { useInviteAcceptContext } from './InviteAcceptProvider'; import { useInviteAcceptContext } from './InviteAcceptProvider';
import { AuthSubmitButton } from './_components'; import { PasswordRevealer } from './components';
/** /**
* Invite user form. * Invite user form.
*/ */
export default function InviteUserFormContent() { export default function InviteUserFormContent() {
const [showPassword, setShowPassword] = useState<boolean>(false); // Invite accept context.
const { inviteMeta } = useInviteAcceptContext(); const { inviteMeta } = useInviteAcceptContext();
// Formik context.
const { isSubmitting } = useFormikContext(); const { isSubmitting } = useFormikContext();
const [passwordType, setPasswordType] = React.useState('password');
// Handle password revealer changing. // Handle password revealer changing.
const handleLockClick = () => { const handlePasswordRevealerChange = React.useCallback(
setShowPassword(!showPassword); (shown) => {
}; const type = shown ? 'text' : 'password';
const lockButton = ( setPasswordType(type);
<Tooltip2 content={`${showPassword ? 'Hide' : 'Show'} Password`}> },
<Button [setPasswordType],
icon={showPassword ? 'unlock' : 'lock'}
intent={Intent.WARNING}
minimal={true}
onClick={handleLockClick}
small={true}
/>
</Tooltip2>
); );
return ( return (
<Form> <Form>
<Row> <Row>
<Col md={6}> <Col md={6}>
<FFormGroup name={'first_name'} label={<T id={'first_name'} />}> <FastField name={'first_name'}>
<FInputGroup name={'first_name'} large={true} /> {({ form, field, meta: { error, touched } }) => (
</FFormGroup> <FormGroup
label={<T id={'first_name'} />}
className={'form-group--first_name'}
intent={inputIntent({ error, touched })}
helperText={<ErrorMessage name={'first_name'} />}
>
<InputGroup
intent={inputIntent({ error, touched })}
{...field}
/>
</FormGroup>
)}
</FastField>
</Col> </Col>
<Col md={6}> <Col md={6}>
<FFormGroup name={'last_name'} label={<T id={'last_name'} />}> <FastField name={'last_name'}>
<FInputGroup name={'last_name'} large={true} /> {({ form, field, meta: { error, touched } }) => (
</FFormGroup> <FormGroup
label={<T id={'last_name'} />}
className={'form-group--last_name'}
intent={inputIntent({ error, touched })}
helperText={<ErrorMessage name={'last_name'} />}
>
<InputGroup
intent={inputIntent({ error, touched })}
{...field}
/>
</FormGroup>
)}
</FastField>
</Col> </Col>
</Row> </Row>
<FFormGroup name={'password'} label={<T id={'password'} />}> <FastField name={'phone_number'}>
<FInputGroup {({ form, field, meta: { error, touched } }) => (
name={'password'} <FormGroup
large={true} label={<T id={'phone_number'} />}
rightElement={lockButton} className={'form-group--phone_number'}
type={showPassword ? 'text' : 'password'} intent={inputIntent({ error, touched })}
/> helperText={<ErrorMessage name={'phone_number'} />}
</FFormGroup> >
<InputGroup intent={inputIntent({ error, touched })} {...field} />
</FormGroup>
)}
</FastField>
<InviteAcceptFooterParagraphs> <FastField name={'password'}>
{({ form, field, meta: { error, touched } }) => (
<FormGroup
label={<T id={'password'} />}
labelInfo={
<PasswordRevealer onChange={handlePasswordRevealerChange} />
}
className={'form-group--password has-password-revealer'}
intent={inputIntent({ error, touched })}
helperText={<ErrorMessage name={'password'} />}
>
<InputGroup
lang={true}
type={passwordType}
intent={inputIntent({ error, touched })}
{...field}
/>
</FormGroup>
)}
</FastField>
<div className={'invite-form__statement-section'}>
<p> <p>
<T id={'you_email_address_is'} /> <b>{inviteMeta.email},</b> <br /> <T id={'you_email_address_is'} /> <b>{inviteMeta.email},</b> <br />
<T id={'you_will_use_this_address_to_sign_in_to_bigcapital'} /> <T id={'you_will_use_this_address_to_sign_in_to_bigcapital'} />
@@ -78,25 +115,18 @@ export default function InviteUserFormContent() {
privacy: (msg) => <Link>{msg}</Link>, privacy: (msg) => <Link>{msg}</Link>,
})} })}
</p> </p>
</InviteAcceptFooterParagraphs> </div>
<InviteAuthSubmitButton <div className={'authentication-page__submit-button-wrap'}>
intent={Intent.PRIMARY} <Button
type="submit" intent={Intent.PRIMARY}
fill={true} type="submit"
large={true} fill={true}
loading={isSubmitting} loading={isSubmitting}
> >
<T id={'create_account'} /> <T id={'create_account'} />
</InviteAuthSubmitButton> </Button>
</div>
</Form> </Form>
); );
} }
const InviteAcceptFooterParagraphs = styled.div`
opacity: 0.8;
`;
const InviteAuthSubmitButton = styled(AuthSubmitButton)`
margin-top: 1.6rem;
`;

View File

@@ -1,8 +1,8 @@
// @ts-nocheck // @ts-nocheck
import React, { createContext, useContext, useEffect } from 'react'; import React, { createContext, useContext } from 'react';
import { useHistory } from 'react-router-dom';
import { useInviteMetaByToken, useAuthInviteAccept } from '@/hooks/query'; import { useInviteMetaByToken, useAuthInviteAccept } from '@/hooks/query';
import { InviteAcceptLoading } from './components'; import { InviteAcceptLoading } from './components';
import { useHistory } from 'react-router-dom';
const InviteAcceptContext = createContext(); const InviteAcceptContext = createContext();
@@ -22,10 +22,11 @@ function InviteAcceptProvider({ token, ...props }) {
const { mutateAsync: inviteAcceptMutate } = useAuthInviteAccept({ const { mutateAsync: inviteAcceptMutate } = useAuthInviteAccept({
retry: false, retry: false,
}); });
// History context. // History context.
const history = useHistory(); const history = useHistory();
useEffect(() => { React.useEffect(() => {
if (inviteMetaError) { history.push('/auth/login'); } if (inviteMetaError) { history.push('/auth/login'); }
}, [history, inviteMetaError]); }, [history, inviteMetaError]);

View File

@@ -1,25 +1,14 @@
// @ts-nocheck // @ts-nocheck
import React from 'react'; import React from 'react';
import { Formik } from 'formik';
import { Link } from 'react-router-dom'; import { Link } from 'react-router-dom';
import { Formik } from 'formik';
import { AppToaster as Toaster, FormattedMessage as T } from '@/components'; import { AppToaster as Toaster, FormattedMessage as T } from '@/components';
import AuthInsider from '@/containers/Authentication/AuthInsider'; import AuthInsider from '@/containers/Authentication/AuthInsider';
import { useAuthLogin } from '@/hooks/query'; import { useAuthLogin } from '@/hooks/query';
import LoginForm from './LoginForm'; import LoginForm from './LoginForm';
import { LoginSchema, transformLoginErrorsToToasts } from './utils'; import { LoginSchema, transformLoginErrorsToToasts } from './utils';
import {
AuthFooterLinks,
AuthFooterLink,
AuthInsiderCard,
} from './_components';
const initialValues = {
crediential: '',
password: '',
keepLoggedIn: false
};
/** /**
* Login page. * Login page.
@@ -49,32 +38,34 @@ export default function Login() {
return ( return (
<AuthInsider> <AuthInsider>
<AuthInsiderCard> <div className="login-form">
<div className={'authentication-page__label-section'}>
<h3>
<T id={'log_in'} />
</h3>
{/* <T id={'need_bigcapital_account'} />
<Link to="/auth/register">
{' '}
<T id={'create_an_account'} />
</Link> */}
</div>
<Formik <Formik
initialValues={initialValues} initialValues={{
crediential: '',
password: '',
}}
validationSchema={LoginSchema} validationSchema={LoginSchema}
onSubmit={handleSubmit} onSubmit={handleSubmit}
component={LoginForm} component={LoginForm}
/> />
</AuthInsiderCard>
<LoginFooterLinks /> <div class="authentication-page__footer-links">
<Link to={'/auth/send_reset_password'}>
<T id={'forget_my_password'} />
</Link>
</div>
</div>
</AuthInsider> </AuthInsider>
); );
} }
function LoginFooterLinks() {
return (
<AuthFooterLinks>
<AuthFooterLink>
Don't have an account? <Link to={'/auth/register'}>Sign up</Link>
</AuthFooterLink>
<AuthFooterLink>
<Link to={'/auth/send_reset_password'}>
<T id={'forget_my_password'} />
</Link>
</AuthFooterLink>
</AuthFooterLinks>
);
}

View File

@@ -1,63 +1,89 @@
// @ts-nocheck // @ts-nocheck
import React, { useState } from 'react'; import React from 'react';
import { Button, Intent } from '@blueprintjs/core'; import {
import { Form } from 'formik'; Button,
import { Tooltip2 } from '@blueprintjs/popover2'; InputGroup,
Intent,
import { FFormGroup, FInputGroup, FCheckbox, T } from '@/components'; FormGroup,
import { AuthSubmitButton } from './_components'; Checkbox,
} from '@blueprintjs/core';
import { Form, ErrorMessage, Field } from 'formik';
import { T } from '@/components';
import { inputIntent } from '@/utils';
import { PasswordRevealer } from './components';
/** /**
* Login form. * Login form.
*/ */
export default function LoginForm({ isSubmitting }) { export default function LoginForm({ isSubmitting }) {
const [showPassword, setShowPassword] = useState<boolean>(false); const [passwordType, setPasswordType] = React.useState('password');
// Handle password revealer changing. // Handle password revealer changing.
const handleLockClick = () => { const handlePasswordRevealerChange = React.useCallback(
setShowPassword(!showPassword); (shown) => {
}; const type = shown ? 'text' : 'password';
setPasswordType(type);
const lockButton = ( },
<Tooltip2 content={`${showPassword ? 'Hide' : 'Show'} Password`}> [setPasswordType],
<Button
icon={showPassword ? 'unlock' : 'lock'}
intent={Intent.WARNING}
minimal={true}
onClick={handleLockClick}
small={true}
/>
</Tooltip2>
); );
return ( return (
<Form> <Form className={'authentication-page__form'}>
<FFormGroup name={'crediential'} label={<T id={'email_address'} />}> <Field name={'crediential'}>
<FInputGroup name={'crediential'} large={true} /> {({ form, field, meta: { error, touched } }) => (
</FFormGroup> <FormGroup
label={<T id={'email_or_phone_number'} />}
intent={inputIntent({ error, touched })}
helperText={<ErrorMessage name={'crediential'} />}
className={'form-group--crediential'}
>
<InputGroup
intent={inputIntent({ error, touched })}
large={true}
{...field}
/>
</FormGroup>
)}
</Field>
<FFormGroup name={'password'} label={<T id={'password'} />}> <Field name={'password'}>
<FInputGroup {({ form, field, meta: { error, touched } }) => (
name={'password'} <FormGroup
large={true} label={<T id={'password'} />}
type={showPassword ? 'text' : 'password'} labelInfo={
rightElement={lockButton} <PasswordRevealer onChange={handlePasswordRevealerChange} />
/> }
</FFormGroup> intent={inputIntent({ error, touched })}
helperText={<ErrorMessage name={'password'} />}
className={'form-group--password has-password-revealer'}
>
<InputGroup
large={true}
intent={inputIntent({ error, touched })}
type={passwordType}
{...field}
/>
</FormGroup>
)}
</Field>
<FCheckbox name={'keepLoggedIn'}> <div className={'login-form__checkbox-section'}>
<T id={'keep_me_logged_in'} /> <Checkbox large={true} className={'checkbox--remember-me'}>
</FCheckbox> <T id={'keep_me_logged_in'} />
</Checkbox>
</div>
<AuthSubmitButton <div className={'authentication-page__submit-button-wrap'}>
type={'submit'} <Button
intent={Intent.PRIMARY} type={'submit'}
fill={true} intent={Intent.PRIMARY}
large={true} fill={true}
loading={isSubmitting} lang={true}
> loading={isSubmitting}
<T id={'log_in'} /> >
</AuthSubmitButton> <T id={'log_in'} />
</Button>
</div>
</Form> </Form>
); );
} }

View File

@@ -11,18 +11,6 @@ import { useAuthLogin, useAuthRegister } from '@/hooks/query/authentication';
import RegisterForm from './RegisterForm'; import RegisterForm from './RegisterForm';
import { RegisterSchema, transformRegisterErrorsToForm } from './utils'; import { RegisterSchema, transformRegisterErrorsToForm } from './utils';
import {
AuthFooterLinks,
AuthFooterLink,
AuthInsiderCard,
} from './_components';
const initialValues = {
first_name: '',
last_name: '',
email: '',
password: '',
};
/** /**
* Register form. * Register form.
@@ -31,6 +19,18 @@ export default function RegisterUserForm() {
const { mutateAsync: authLoginMutate } = useAuthLogin(); const { mutateAsync: authLoginMutate } = useAuthLogin();
const { mutateAsync: authRegisterMutate } = useAuthRegister(); const { mutateAsync: authRegisterMutate } = useAuthRegister();
const initialValues = useMemo(
() => ({
first_name: '',
last_name: '',
email: '',
phone_number: '',
password: '',
country: 'LY',
}),
[],
);
const handleSubmit = (values, { setSubmitting, setErrors }) => { const handleSubmit = (values, { setSubmitting, setErrors }) => {
authRegisterMutate(values) authRegisterMutate(values)
.then((response) => { .then((response) => {
@@ -66,32 +66,24 @@ export default function RegisterUserForm() {
return ( return (
<AuthInsider> <AuthInsider>
<AuthInsiderCard> <div className={'register-form'}>
<div className={'authentication-page__label-section'}>
<h3>
<T id={'register_a_new_organization'} />
</h3>
<T id={'you_have_a_bigcapital_account'} />
<Link to="/auth/login">
<T id={'login'} />
</Link>
</div>
<Formik <Formik
initialValues={initialValues} initialValues={initialValues}
validationSchema={RegisterSchema} validationSchema={RegisterSchema}
onSubmit={handleSubmit} onSubmit={handleSubmit}
component={RegisterForm} component={RegisterForm}
/> />
</AuthInsiderCard> </div>
<RegisterFooterLinks />
</AuthInsider> </AuthInsider>
); );
} }
function RegisterFooterLinks() {
return (
<AuthFooterLinks>
<AuthFooterLink>
Return to <Link to={'/auth/login'}>Sign In</Link>
</AuthFooterLink>
<AuthFooterLink>
<Link to={'/auth/send_reset_password'}>
<T id={'forget_my_password'} />
</Link>
</AuthFooterLink>
</AuthFooterLinks>
);
}

View File

@@ -1,101 +1,148 @@
// @ts-nocheck // @ts-nocheck
import React from 'react'; import React from 'react';
import { Form } from 'formik';
import intl from 'react-intl-universal'; import intl from 'react-intl-universal';
import { Intent, Button } from '@blueprintjs/core';
import { Link } from 'react-router-dom';
import { Tooltip2 } from '@blueprintjs/popover2';
import styled from 'styled-components';
import { import {
FFormGroup, Button,
FInputGroup, InputGroup,
Row, Intent,
Col, FormGroup,
FormattedMessage as T, Spinner,
} from '@/components'; } from '@blueprintjs/core';
import { AuthSubmitButton, AuthenticationLoadingOverlay } from './_components'; import { ErrorMessage, Field, Form } from 'formik';
import { FormattedMessage as T } from '@/components';
import { Link } from 'react-router-dom';
import { Row, Col, If } from '@/components';
import { PasswordRevealer } from './components';
import { inputIntent } from '@/utils';
/** /**
* Register form. * Register form.
*/ */
export default function RegisterForm({ isSubmitting }) { export default function RegisterForm({ isSubmitting }) {
const [showPassword, setShowPassword] = React.useState<boolean>(false); const [passwordType, setPasswordType] = React.useState('password');
// Handle password revealer changing. // Handle password revealer changing.
const handleLockClick = () => { const handlePasswordRevealerChange = React.useCallback(
setShowPassword(!showPassword); (shown) => {
}; const type = shown ? 'text' : 'password';
setPasswordType(type);
const lockButton = ( },
<Tooltip2 content={`${showPassword ? 'Hide' : 'Show'} Password`}> [setPasswordType],
<Button
icon={showPassword ? 'unlock' : 'lock'}
intent={Intent.WARNING}
minimal={true}
onClick={handleLockClick}
small={true}
/>
</Tooltip2>
); );
return ( return (
<RegisterFormRoot> <Form className={'authentication-page__form'}>
<Row className={'name-section'}> <Row className={'name-section'}>
<Col md={6}> <Col md={6}>
<FFormGroup name={'first_name'} label={<T id={'first_name'} />}> <Field name={'first_name'}>
<FInputGroup name={'first_name'} large={true} /> {({ form, field, meta: { error, touched } }) => (
</FFormGroup> <FormGroup
label={<T id={'first_name'} />}
intent={inputIntent({ error, touched })}
helperText={<ErrorMessage name={'first_name'} />}
className={'form-group--first-name'}
>
<InputGroup
intent={inputIntent({ error, touched })}
{...field}
/>
</FormGroup>
)}
</Field>
</Col> </Col>
<Col md={6}> <Col md={6}>
<FFormGroup name={'last_name'} label={<T id={'last_name'} />}> <Field name={'last_name'}>
<FInputGroup name={'last_name'} large={true} /> {({ form, field, meta: { error, touched } }) => (
</FFormGroup> <FormGroup
label={<T id={'last_name'} />}
intent={inputIntent({ error, touched })}
helperText={<ErrorMessage name={'last_name'} />}
className={'form-group--last-name'}
>
<InputGroup
intent={inputIntent({ error, touched })}
{...field}
/>
</FormGroup>
)}
</Field>
</Col> </Col>
</Row> </Row>
<FFormGroup name={'email'} label={<T id={'email'} />}> <Field name={'phone_number'}>
<FInputGroup name={'email'} large={true} /> {({ form, field, meta: { error, touched } }) => (
</FFormGroup> <FormGroup
label={<T id={'phone_number'} />}
intent={inputIntent({ error, touched })}
helperText={<ErrorMessage name={'phone_number'} />}
className={'form-group--phone-number'}
>
<InputGroup intent={inputIntent({ error, touched })} {...field} />
</FormGroup>
)}
</Field>
<FFormGroup name={'password'} label={<T id={'password'} />}> <Field name={'email'}>
<FInputGroup {({ form, field, meta: { error, touched } }) => (
name={'password'} <FormGroup
type={showPassword ? 'text' : 'password'} label={<T id={'email'} />}
rightElement={lockButton} intent={inputIntent({ error, touched })}
large={true} helperText={<ErrorMessage name={'email'} />}
/> className={'form-group--email'}
</FFormGroup> >
<InputGroup intent={inputIntent({ error, touched })} {...field} />
</FormGroup>
)}
</Field>
<TermsConditionsText> <Field name={'password'}>
{intl.getHTML('signing_in_or_creating', { {({ form, field, meta: { error, touched } }) => (
terms: (msg) => <Link>{msg}</Link>, <FormGroup
privacy: (msg) => <Link>{msg}</Link>, label={<T id={'password'} />}
})} labelInfo={
</TermsConditionsText> <PasswordRevealer onChange={handlePasswordRevealerChange} />
}
intent={inputIntent({ error, touched })}
helperText={<ErrorMessage name={'password'} />}
className={'form-group--password has-password-revealer'}
>
<InputGroup
lang={true}
type={passwordType}
intent={inputIntent({ error, touched })}
{...field}
/>
</FormGroup>
)}
</Field>
<AuthSubmitButton <div className={'register-form__agreement-section'}>
className={'btn-register'} <p>
intent={Intent.PRIMARY} {intl.getHTML('signing_in_or_creating', {
type="submit" terms: (msg) => <Link>{msg}</Link>,
fill={true} privacy: (msg) => <Link>{msg}</Link>,
large={true} })}
loading={isSubmitting} </p>
> </div>
<T id={'register'} />
</AuthSubmitButton>
{isSubmitting && <AuthenticationLoadingOverlay />} <div className={'authentication-page__submit-button-wrap'}>
</RegisterFormRoot> <Button
className={'btn-register'}
intent={Intent.PRIMARY}
type="submit"
fill={true}
loading={isSubmitting}
>
<T id={'register'} />
</Button>
</div>
<If condition={isSubmitting}>
<div class="authentication-page__loading-overlay">
<Spinner size={50} />
</div>
</If>
</Form>
); );
} }
const TermsConditionsText = styled.p`
opacity: 0.8;
margin-bottom: 1.4rem;
`;
const RegisterFormRoot = styled(Form)`
position: relative;
`;

View File

@@ -4,23 +4,14 @@ import intl from 'react-intl-universal';
import { Formik } from 'formik'; import { Formik } from 'formik';
import { Intent, Position } from '@blueprintjs/core'; import { Intent, Position } from '@blueprintjs/core';
import { Link, useParams, useHistory } from 'react-router-dom'; import { Link, useParams, useHistory } from 'react-router-dom';
import { AppToaster, FormattedMessage as T } from '@/components';
import { AppToaster } from '@/components';
import { useAuthResetPassword } from '@/hooks/query'; import { useAuthResetPassword } from '@/hooks/query';
import AuthInsider from '@/containers/Authentication/AuthInsider'; import AuthInsider from '@/containers/Authentication/AuthInsider';
import {
AuthFooterLink,
AuthFooterLinks,
AuthInsiderCard,
} from './_components';
import ResetPasswordForm from './ResetPasswordForm'; import ResetPasswordForm from './ResetPasswordForm';
import { ResetPasswordSchema } from './utils'; import { ResetPasswordSchema } from './utils';
const initialValues = {
password: '',
confirm_password: '',
};
/** /**
* Reset password page. * Reset password page.
*/ */
@@ -31,13 +22,22 @@ export default function ResetPassword() {
// Authentication reset password. // Authentication reset password.
const { mutateAsync: authResetPasswordMutate } = useAuthResetPassword(); const { mutateAsync: authResetPasswordMutate } = useAuthResetPassword();
// Initial values of the form.
const initialValues = useMemo(
() => ({
password: '',
confirm_password: '',
}),
[],
);
// Handle the form submitting. // Handle the form submitting.
const handleSubmit = (values, { setSubmitting }) => { const handleSubmit = (values, { setSubmitting }) => {
authResetPasswordMutate([token, values]) authResetPasswordMutate([token, values])
.then((response) => { .then((response) => {
AppToaster.show({ AppToaster.show({
message: intl.get('password_successfully_updated'), message: intl.get('password_successfully_updated'),
intent: Intent.SUCCESS, intent: Intent.DANGER,
position: Position.BOTTOM, position: Position.BOTTOM,
}); });
history.push('/auth/login'); history.push('/auth/login');
@@ -64,30 +64,24 @@ export default function ResetPassword() {
return ( return (
<AuthInsider> <AuthInsider>
<AuthInsiderCard> <div className={'submit-np-form'}>
<div className={'authentication-page__label-section'}>
<h3>
<T id={'choose_a_new_password'} />
</h3>
<T id={'you_remembered_your_password'} />{' '}
<Link to="/auth/login">
<T id={'login'} />
</Link>
</div>
<Formik <Formik
initialValues={initialValues} initialValues={initialValues}
validationSchema={ResetPasswordSchema} validationSchema={ResetPasswordSchema}
onSubmit={handleSubmit} onSubmit={handleSubmit}
component={ResetPasswordForm} component={ResetPasswordForm}
/> />
</AuthInsiderCard> </div>
<ResetPasswordFooterLinks />
</AuthInsider> </AuthInsider>
); );
} }
function ResetPasswordFooterLinks() {
return (
<AuthFooterLinks>
<AuthFooterLink>
Don't have an account? <Link to={'/auth/register'}>Sign up</Link>
</AuthFooterLink>
<AuthFooterLink>
Return to <Link to={'/auth/login'}>Sign In</Link>
</AuthFooterLink>
</AuthFooterLinks>
);
}

View File

@@ -1,9 +1,9 @@
// @ts-nocheck // @ts-nocheck
import React from 'react'; import React from 'react';
import { Intent } from '@blueprintjs/core'; import { Button, InputGroup, Intent, FormGroup } from '@blueprintjs/core';
import { Form } from 'formik'; import { Form, ErrorMessage, FastField } from 'formik';
import { FFormGroup, FInputGroup, FormattedMessage as T } from '@/components'; import { FormattedMessage as T } from '@/components';
import { AuthSubmitButton } from './_components'; import { inputIntent } from '@/utils';
/** /**
* Reset password form. * Reset password form.
@@ -11,23 +11,54 @@ import { AuthSubmitButton } from './_components';
export default function ResetPasswordForm({ isSubmitting }) { export default function ResetPasswordForm({ isSubmitting }) {
return ( return (
<Form> <Form>
<FFormGroup name={'password'} label={<T id={'new_password'} />}> <FastField name={'password'}>
<FInputGroup name={'password'} type={'password'} large={true} /> {({ form, field, meta: { error, touched } }) => (
</FFormGroup> <FormGroup
label={<T id={'new_password'} />}
intent={inputIntent({ error, touched })}
helperText={<ErrorMessage name={'password'} />}
className={'form-group--password'}
>
<InputGroup
lang={true}
type={'password'}
intent={inputIntent({ error, touched })}
{...field}
/>
</FormGroup>
)}
</FastField>
<FFormGroup name={'confirm_password'} label={<T id={'new_password'} />}> <FastField name={'confirm_password'}>
<FInputGroup name={'confirm_password'} type={'password'} large={true} /> {({ form, field, meta: { error, touched } }) => (
</FFormGroup> <FormGroup
label={<T id={'new_password'} />}
labelInfo={'(again):'}
intent={inputIntent({ error, touched })}
helperText={<ErrorMessage name={'confirm_password'} />}
className={'form-group--confirm-password'}
>
<InputGroup
lang={true}
type={'password'}
intent={inputIntent({ error, touched })}
{...field}
/>
</FormGroup>
)}
</FastField>
<AuthSubmitButton <div className={'authentication-page__submit-button-wrap'}>
fill={true} <Button
intent={Intent.PRIMARY} fill={true}
type="submit" className={'btn-new'}
loading={isSubmitting} intent={Intent.PRIMARY}
large={true} type="submit"
> loading={isSubmitting}
<T id={'submit'} /> >
</AuthSubmitButton> <T id={'submit'} />
</Button>
</div>
</Form> </Form>
); );
} }

View File

@@ -5,32 +5,33 @@ import { Formik } from 'formik';
import { Link, useHistory } from 'react-router-dom'; import { Link, useHistory } from 'react-router-dom';
import { Intent } from '@blueprintjs/core'; import { Intent } from '@blueprintjs/core';
import { AppToaster } from '@/components'; import { AppToaster, FormattedMessage as T } from '@/components';
import { useAuthSendResetPassword } from '@/hooks/query'; import { useAuthSendResetPassword } from '@/hooks/query';
import SendResetPasswordForm from './SendResetPasswordForm'; import SendResetPasswordForm from './SendResetPasswordForm';
import {
AuthFooterLink,
AuthFooterLinks,
AuthInsiderCard,
} from './_components';
import { import {
SendResetPasswordSchema, SendResetPasswordSchema,
transformSendResetPassErrorsToToasts, transformSendResetPassErrorsToToasts,
} from './utils'; } from './utils';
import AuthInsider from '@/containers/Authentication/AuthInsider';
const initialValues = { import AuthInsider from '@/containers/Authentication/AuthInsider';
crediential: '',
};
/** /**
* Send reset password page. * Send reset password page.
*/ */
export default function SendResetPassword({ requestSendResetPassword }) { export default function SendResetPassword({ requestSendResetPassword }) {
const history = useHistory(); const history = useHistory();
const { mutateAsync: sendResetPasswordMutate } = useAuthSendResetPassword(); const { mutateAsync: sendResetPasswordMutate } = useAuthSendResetPassword();
// Initial values.
const initialValues = useMemo(
() => ({
crediential: '',
}),
[],
);
// Handle form submitting. // Handle form submitting.
const handleSubmit = (values, { setSubmitting }) => { const handleSubmit = (values, { setSubmitting }) => {
sendResetPasswordMutate({ email: values.crediential }) sendResetPasswordMutate({ email: values.crediential })
@@ -60,30 +61,28 @@ export default function SendResetPassword({ requestSendResetPassword }) {
return ( return (
<AuthInsider> <AuthInsider>
<AuthInsiderCard> <div className="reset-form">
<div className={'authentication-page__label-section'}>
<h3>
<T id={'you_can_t_login'} />
</h3>
<p>
<T id={'we_ll_send_a_recovery_link_to_your_email'} />
</p>
</div>
<Formik <Formik
initialValues={initialValues} initialValues={initialValues}
onSubmit={handleSubmit} onSubmit={handleSubmit}
validationSchema={SendResetPasswordSchema} validationSchema={SendResetPasswordSchema}
component={SendResetPasswordForm} component={SendResetPasswordForm}
/> />
</AuthInsiderCard> <div class="authentication-page__footer-links">
<Link to="/auth/login">
<SendResetPasswordFooterLinks /> <T id={'return_to_log_in'} />
</Link>
</div>
</div>
</AuthInsider> </AuthInsider>
); );
} }
function SendResetPasswordFooterLinks() {
return (
<AuthFooterLinks>
<AuthFooterLink>
Don't have an account? <Link to={'/auth/register'}>Sign up</Link>
</AuthFooterLink>
<AuthFooterLink>
Return to <Link to={'/auth/login'}>Sign In</Link>
</AuthFooterLink>
</AuthFooterLinks>
);
}

View File

@@ -1,41 +1,43 @@
// @ts-nocheck // @ts-nocheck
import React from 'react'; import React from 'react';
import { Intent } from '@blueprintjs/core'; import { Button, InputGroup, Intent, FormGroup } from '@blueprintjs/core';
import { Form } from 'formik'; import { Form, ErrorMessage, FastField } from 'formik';
import styled from 'styled-components'; import { FormattedMessage as T } from '@/components';
import { inputIntent } from '@/utils';
import { FInputGroup, FFormGroup, FormattedMessage as T } from '@/components';
import { AuthSubmitButton } from './_components';
/** /**
* Send reset password form. * Send reset password form.
*/ */
export default function SendResetPasswordForm({ isSubmitting }) { export default function SendResetPasswordForm({ isSubmitting }) {
return ( return (
<Form> <Form className={'send-reset-password'}>
<TopParagraph> <FastField name={'crediential'}>
Enter the email address associated with your account and we'll send you {({ form, field, meta: { error, touched } }) => (
a link to reset your password. <FormGroup
</TopParagraph> label={<T id={'email_or_phone_number'} />}
intent={inputIntent({ error, touched })}
helperText={<ErrorMessage name={'crediential'} />}
className={'form-group--crediential'}
>
<InputGroup
intent={inputIntent({ error, touched })}
large={true}
{...field}
/>
</FormGroup>
)}
</FastField>
<FFormGroup name={'crediential'} label={<T id={'email_address'} />}> <div className={'authentication-page__submit-button-wrap'}>
<FInputGroup name={'crediential'} large={true} /> <Button
</FFormGroup> type={'submit'}
intent={Intent.PRIMARY}
<AuthSubmitButton fill={true}
type={'submit'} loading={isSubmitting}
intent={Intent.PRIMARY} >
fill={true} <T id={'send_reset_password_mail'} />
large={true} </Button>
loading={isSubmitting} </div>
>
Reset Password
</AuthSubmitButton>
</Form> </Form>
); );
} }
const TopParagraph = styled.p`
margin-bottom: 1.6rem;
opacity: 0.8;
`;

View File

@@ -1,76 +0,0 @@
import React from 'react';
import styled from 'styled-components';
import { Spinner } from '@blueprintjs/core';
import { Button } from '@blueprintjs/core';
export function AuthenticationLoadingOverlay() {
return (
<AuthOverlayRoot>
<Spinner size={50} />
</AuthOverlayRoot>
);
}
const AuthOverlayRoot = styled.div`
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
background: rgba(252, 253, 255, 0.5);
display: flex;
justify-content: center;
`;
export const AuthInsiderContent = styled.div`
position: relative;
`;
export const AuthInsiderCard = styled.div`
border: 1px solid #d5d5d5;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04);
padding: 26px 22px;
background: #ffff;
border-radius: 3px;
`;
export const AuthInsiderCopyright = styled.div`
text-align: center;
font-size: 12px;
color: #666;
margin-top: 1.2rem;
.bp3-icon-bigcapital {
svg {
path {
fill: #a3a3a3;
}
}
}
`;
export const AuthFooterLinks = styled.div`
display: flex;
flex-direction: column;
gap: 10px;
padding-left: 1.2rem;
padding-right: 1.2rem;
margin-top: 1rem;
`;
export const AuthFooterLink = styled.p`
color: #666;
margin: 0;
`;
export const AuthSubmitButton = styled(Button)`
margin-top: 20px;
&.bp3-intent-primary {
background-color: #0052cc;
&:disabled,
&.bp3-disabled {
background-color: rgba(0, 82, 204, 0.4);
}
}
`;

View File

@@ -1,42 +1,57 @@
// @ts-nocheck // @ts-nocheck
import React from 'react'; import React from 'react';
import styled from 'styled-components'; import ContentLoader from 'react-content-loader';
import { AuthInsiderCard } from './_components'; import { If, Icon, FormattedMessage as T } from '@/components';
import { Skeleton } from '@/components'; import { saveInvoke } from '@/utils';
export function PasswordRevealer({ defaultShown = false, onChange }) {
const [shown, setShown] = React.useState(defaultShown);
const handleClick = () => {
setShown(!shown);
saveInvoke(onChange, !shown);
};
return (
<span class="password-revealer" onClick={handleClick}>
<If condition={shown}>
<Icon icon="eye-slash" />{' '}
<span class="text">
<T id={'hide'} />
</span>
</If>
<If condition={!shown}>
<Icon icon="eye" />{' '}
<span class="text">
<T id={'show'} />
</span>
</If>
</span>
);
}
/** /**
* Invite accept loading space. * Invite accept loading space.
*/ */
export function InviteAcceptLoading({ isLoading, children }) { export function InviteAcceptLoading({ isLoading, children, ...props }) {
return isLoading ? ( return isLoading ? (
<AuthInsiderCard> <ContentLoader
<Fields> speed={2}
<SkeletonField /> width={400}
<SkeletonField /> height={280}
<SkeletonField /> viewBox="0 0 400 280"
</Fields> backgroundColor="#f3f3f3"
</AuthInsiderCard> foregroundColor="#e6e6e6"
{...props}
>
<rect x="0" y="80" rx="2" ry="2" width="200" height="20" />
<rect x="0" y="0" rx="2" ry="2" width="250" height="30" />
<rect x="0" y="38" rx="2" ry="2" width="300" height="15" />
<rect x="0" y="175" rx="2" ry="2" width="200" height="20" />
<rect x="1" y="205" rx="2" ry="2" width="385" height="38" />
<rect x="0" y="110" rx="2" ry="2" width="385" height="38" />
</ContentLoader>
) : ( ) : (
children children
); );
} }
function SkeletonField() {
return (
<SkeletonFieldRoot>
<Skeleton>XXXX XXXX</Skeleton>
<Skeleton minWidth={100}>XXXX XXXX XXXX XXXX</Skeleton>
</SkeletonFieldRoot>
);
}
const Fields = styled.div`
display: flex;
flex-direction: column;
gap: 20px;
`;
const SkeletonFieldRoot = styled.div`
display: flex;
flex-direction: column;
gap: 8px;
`;

View File

@@ -15,19 +15,42 @@ const REGISTER_ERRORS = {
}; };
export const LoginSchema = Yup.object().shape({ export const LoginSchema = Yup.object().shape({
crediential: Yup.string().required().email().label(intl.get('email')), crediential: Yup.string()
password: Yup.string().required().min(4).label(intl.get('password')), .required()
.email()
.label(intl.get('email')),
password: Yup.string()
.required()
.min(4)
.label(intl.get('password')),
}); });
export const RegisterSchema = Yup.object().shape({ export const RegisterSchema = Yup.object().shape({
first_name: Yup.string().required().label(intl.get('first_name_')), first_name: Yup.string()
last_name: Yup.string().required().label(intl.get('last_name_')), .required()
email: Yup.string().email().required().label(intl.get('email')), .label(intl.get('first_name_')),
password: Yup.string().min(4).required().label(intl.get('password')), last_name: Yup.string()
.required()
.label(intl.get('last_name_')),
email: Yup.string()
.email()
.required()
.label(intl.get('email')),
phone_number: Yup.string()
.matches()
.required()
.label(intl.get('phone_number_')),
password: Yup.string()
.min(4)
.required()
.label(intl.get('password')),
}); });
export const ResetPasswordSchema = Yup.object().shape({ export const ResetPasswordSchema = Yup.object().shape({
password: Yup.string().min(4).required().label(intl.get('password')), password: Yup.string()
.min(4)
.required()
.label(intl.get('password')),
confirm_password: Yup.string() confirm_password: Yup.string()
.oneOf([Yup.ref('password'), null]) .oneOf([Yup.ref('password'), null])
.required() .required()
@@ -36,13 +59,27 @@ export const ResetPasswordSchema = Yup.object().shape({
// Validation schema. // Validation schema.
export const SendResetPasswordSchema = Yup.object().shape({ export const SendResetPasswordSchema = Yup.object().shape({
crediential: Yup.string().required().email().label(intl.get('email')), crediential: Yup.string()
.required()
.email()
.label(intl.get('email')),
}); });
export const InviteAcceptSchema = Yup.object().shape({ export const InviteAcceptSchema = Yup.object().shape({
first_name: Yup.string().required().label(intl.get('first_name_')), first_name: Yup.string()
last_name: Yup.string().required().label(intl.get('last_name_')), .required()
password: Yup.string().min(4).required().label(intl.get('password')), .label(intl.get('first_name_')),
last_name: Yup.string()
.required()
.label(intl.get('last_name_')),
phone_number: Yup.string()
.matches()
.required()
.label(intl.get('phone_number')),
password: Yup.string()
.min(4)
.required()
.label(intl.get('password')),
}); });
export const transformSendResetPassErrorsToToasts = (errors) => { export const transformSendResetPassErrorsToToasts = (errors) => {
@@ -55,7 +92,7 @@ export const transformSendResetPassErrorsToToasts = (errors) => {
}); });
} }
return toastBuilders; return toastBuilders;
}; }
export const transformLoginErrorsToToasts = (errors) => { export const transformLoginErrorsToToasts = (errors) => {
const toastBuilders = []; const toastBuilders = [];
@@ -72,25 +109,25 @@ export const transformLoginErrorsToToasts = (errors) => {
intent: Intent.DANGER, intent: Intent.DANGER,
}); });
} }
if (errors.find((e) => e.type === LOGIN_ERRORS.LOGIN_TO_MANY_ATTEMPTS)) { if (
errors.find((e) => e.type === LOGIN_ERRORS.LOGIN_TO_MANY_ATTEMPTS)
) {
toastBuilders.push({ toastBuilders.push({
message: intl.get('your_account_has_been_locked'), message: intl.get('your_account_has_been_locked'),
intent: Intent.DANGER, intent: Intent.DANGER,
}); });
} }
return toastBuilders; return toastBuilders;
}; }
export const transformRegisterErrorsToForm = (errors) => { export const transformRegisterErrorsToForm = (errors) => {
const formErrors = {}; const formErrors = {};
if (errors.some((e) => e.type === REGISTER_ERRORS.PHONE_NUMBER_EXISTS)) { if (errors.some((e) => e.type === REGISTER_ERRORS.PHONE_NUMBER_EXISTS)) {
formErrors.phone_number = intl.get( formErrors.phone_number = intl.get('the_phone_number_already_used_in_another_account');
'the_phone_number_already_used_in_another_account',
);
} }
if (errors.some((e) => e.type === REGISTER_ERRORS.EMAIL_EXISTS)) { if (errors.some((e) => e.type === REGISTER_ERRORS.EMAIL_EXISTS)) {
formErrors.email = intl.get('the_email_already_used_in_another_account'); formErrors.email = intl.get('the_email_already_used_in_another_account');
} }
return formErrors; return formErrors;
}; }

View File

@@ -6,6 +6,10 @@ const Schema = Yup.object().shape({
email: Yup.string().email().required().label(intl.get('email')), email: Yup.string().email().required().label(intl.get('email')),
first_name: Yup.string().required().label(intl.get('first_name_')), first_name: Yup.string().required().label(intl.get('first_name_')),
last_name: Yup.string().required().label(intl.get('last_name_')), last_name: Yup.string().required().label(intl.get('last_name_')),
phone_number: Yup.string()
.matches()
.required()
.label(intl.get('phone_number_')),
role_id: Yup.string().required().label(intl.get('roles.label.role_name_')), role_id: Yup.string().required().label(intl.get('roles.label.role_name_')),
}); });

View File

@@ -13,14 +13,7 @@ import UserFormContent from './UserFormContent';
import { useUserFormContext } from './UserFormProvider'; import { useUserFormContext } from './UserFormProvider';
import { transformErrors } from './utils'; import { transformErrors } from './utils';
import { compose, objectKeysTransform, transformToForm } from '@/utils'; import { compose, objectKeysTransform } from '@/utils';
const initialValues = {
first_name: '',
last_name: '',
email: '',
role_id: '',
};
/** /**
* User form. * User form.
@@ -34,9 +27,12 @@ function UserForm({
const { dialogName, user, userId, isEditMode, EditUserMutate } = const { dialogName, user, userId, isEditMode, EditUserMutate } =
useUserFormContext(); useUserFormContext();
const initialFormValues = { const initialValues = {
...initialValues, ...(isEditMode &&
...(isEditMode && transformToForm(user, initialValues)), pick(
objectKeysTransform(user, snakeCase),
Object.keys(UserFormSchema.fields),
)),
}; };
const handleSubmit = (values, { setSubmitting, setErrors }) => { const handleSubmit = (values, { setSubmitting, setErrors }) => {
@@ -72,7 +68,7 @@ function UserForm({
return ( return (
<Formik <Formik
validationSchema={UserFormSchema} validationSchema={UserFormSchema}
initialValues={initialFormValues} initialValues={initialValues}
onSubmit={handleSubmit} onSubmit={handleSubmit}
> >
<UserFormContent calloutCode={calloutCode} /> <UserFormContent calloutCode={calloutCode} />

View File

@@ -8,10 +8,9 @@ import {
Button, Button,
} from '@blueprintjs/core'; } from '@blueprintjs/core';
import { FastField, Form, useFormikContext, ErrorMessage } from 'formik'; import { FastField, Form, useFormikContext, ErrorMessage } from 'formik';
import classNames from 'classnames'; import { FormattedMessage as T } from '@/components';
import { FFormGroup, FInputGroup, FormattedMessage as T } from '@/components';
import { CLASSES } from '@/constants/classes'; import { CLASSES } from '@/constants/classes';
import classNames from 'classnames';
import { inputIntent } from '@/utils'; import { inputIntent } from '@/utils';
import { ListSelect, FieldRequiredHint } from '@/components'; import { ListSelect, FieldRequiredHint } from '@/components';
import { useUserFormContext } from './UserFormProvider'; import { useUserFormContext } from './UserFormProvider';
@@ -24,7 +23,6 @@ import { UserFormCalloutAlerts } from './components';
*/ */
function UserFormContent({ function UserFormContent({
calloutCode, calloutCode,
// #withDialogActions // #withDialogActions
closeDialog, closeDialog,
}) { }) {
@@ -41,20 +39,60 @@ function UserFormContent({
<UserFormCalloutAlerts calloutCodes={calloutCode} /> <UserFormCalloutAlerts calloutCodes={calloutCode} />
{/* ----------- Email ----------- */} {/* ----------- Email ----------- */}
<FFormGroup name={'email'} label={<T id={'email'} />}> <FastField name={'email'}>
<FInputGroup name={'email'} /> {({ field, meta: { error, touched } }) => (
</FFormGroup> <FormGroup
label={<T id={'email'} />}
labelInfo={<FieldRequiredHint />}
className={classNames('form-group--email', CLASSES.FILL)}
intent={inputIntent({ error, touched })}
helperText={<ErrorMessage name="email" />}
>
<InputGroup medium={true} {...field} />
</FormGroup>
)}
</FastField>
{/* ----------- First name ----------- */} {/* ----------- First name ----------- */}
<FFormGroup name={'first_name'} label={<T id={'first_name'} />}> <FastField name={'first_name'}>
<FInputGroup name={'first_name'} /> {({ form, field, meta: { error, touched } }) => (
</FFormGroup> <FormGroup
label={<T id={'first_name'} />}
labelInfo={<FieldRequiredHint />}
intent={inputIntent({ error, touched })}
helperText={<ErrorMessage name={'first_name'} />}
>
<InputGroup intent={inputIntent({ error, touched })} {...field} />
</FormGroup>
)}
</FastField>
{/* ----------- Last name ----------- */} {/* ----------- Last name ----------- */}
<FFormGroup name={'last_name'} label={<T id={'last_name'} />}> <FastField name={'last_name'}>
<FInputGroup name={'last_name'} /> {({ form, field, meta: { error, touched } }) => (
</FFormGroup> <FormGroup
label={<T id={'last_name'} />}
labelInfo={<FieldRequiredHint />}
intent={inputIntent({ error, touched })}
helperText={<ErrorMessage name={'last_name'} />}
>
<InputGroup intent={inputIntent({ error, touched })} {...field} />
</FormGroup>
)}
</FastField>
{/* ----------- Phone name ----------- */}
<FastField name={'phone_number'}>
{({ form, field, meta: { error, touched } }) => (
<FormGroup
label={<T id={'phone_number'} />}
labelInfo={<FieldRequiredHint />}
intent={inputIntent({ error, touched })}
helperText={<ErrorMessage name={'phone_number'} />}
>
<InputGroup intent={inputIntent({ error, touched })} {...field} />
</FormGroup>
)}
</FastField>
{/* ----------- Role name ----------- */} {/* ----------- Role name ----------- */}
<FastField name={'role_id'}> <FastField name={'role_id'}>
{({ form, field: { value }, meta: { error, touched } }) => ( {({ form, field: { value }, meta: { error, touched } }) => (
@@ -89,12 +127,7 @@ function UserFormContent({
<T id={'cancel'} /> <T id={'cancel'} />
</Button> </Button>
<Button <Button intent={Intent.PRIMARY} type="submit" disabled={isSubmitting}>
intent={Intent.PRIMARY}
type="submit"
disabled={isSubmitting}
loading={isSubmitting}
>
<T id={'edit'} /> <T id={'edit'} />
</Button> </Button>
</div> </div>

View File

@@ -15,15 +15,14 @@ import {
} from '@/components'; } from '@/components';
import { inputIntent } from '@/utils'; import { inputIntent } from '@/utils';
import { CLASSES } from '@/constants/classes'; import { CLASSES } from '@/constants/classes';
import { getCountries } from '@/constants/countries';
import { getAllCurrenciesOptions } from '@/constants/currencies'; import { getAllCurrenciesOptions } from '@/constants/currencies';
import { getFiscalYear } from '@/constants/fiscalYearOptions'; import { getFiscalYear } from '@/constants/fiscalYearOptions';
import { getLanguages } from '@/constants/languagesOptions'; import { getLanguages } from '@/constants/languagesOptions';
import { useGeneralFormContext } from './GeneralFormProvider'; import { useGeneralFormContext } from './GeneralFormProvider';
import { getAllCountries } from '@/utils/countries';
import { shouldBaseCurrencyUpdate } from './utils'; import { shouldBaseCurrencyUpdate } from './utils';
const Countries = getAllCountries();
/** /**
* Preferences general form. * Preferences general form.
*/ */
@@ -31,6 +30,7 @@ export default function PreferencesGeneralForm({ isSubmitting }) {
const history = useHistory(); const history = useHistory();
const FiscalYear = getFiscalYear(); const FiscalYear = getFiscalYear();
const Countries = getCountries();
const Languages = getLanguages(); const Languages = getLanguages();
const Currencies = getAllCurrenciesOptions(); const Currencies = getAllCurrenciesOptions();

View File

@@ -5,12 +5,15 @@ import {
Button, Button,
Intent, Intent,
FormGroup, FormGroup,
InputGroup,
MenuItem, MenuItem,
Classes, Classes,
} from '@blueprintjs/core'; } from '@blueprintjs/core';
import classNames from 'classnames'; import classNames from 'classnames';
import { TimezonePicker } from '@blueprintjs/timezone'; import { TimezonePicker } from '@blueprintjs/timezone';
import { FFormGroup, FInputGroup, FormattedMessage as T } from '@/components'; import useAutofocus from '@/hooks/useAutofocus'
import { FormattedMessage as T } from '@/components';
import { getCountries } from '@/constants/countries';
import { Col, Row, ListSelect } from '@/components'; import { Col, Row, ListSelect } from '@/components';
import { inputIntent } from '@/utils'; import { inputIntent } from '@/utils';
@@ -18,9 +21,6 @@ import { inputIntent } from '@/utils';
import { getFiscalYear } from '@/constants/fiscalYearOptions'; import { getFiscalYear } from '@/constants/fiscalYearOptions';
import { getLanguages } from '@/constants/languagesOptions'; import { getLanguages } from '@/constants/languagesOptions';
import { getAllCurrenciesOptions } from '@/constants/currencies'; import { getAllCurrenciesOptions } from '@/constants/currencies';
import { getAllCountries } from '@/utils/countries';
const countries = getAllCountries();
/** /**
* Setup organization form. * Setup organization form.
@@ -29,6 +29,9 @@ export default function SetupOrganizationForm({ isSubmitting, values }) {
const FiscalYear = getFiscalYear(); const FiscalYear = getFiscalYear();
const Languages = getLanguages(); const Languages = getLanguages();
const currencies = getAllCurrenciesOptions(); const currencies = getAllCurrenciesOptions();
const countries = getCountries();
const accountRef = useAutofocus();
return ( return (
<Form> <Form>
@@ -37,9 +40,22 @@ export default function SetupOrganizationForm({ isSubmitting, values }) {
</h3> </h3>
{/* ---------- Organization name ---------- */} {/* ---------- Organization name ---------- */}
<FFormGroup name={'name'} label={<T id={'legal_organization_name'} />}> <FastField name={'name'}>
<FInputGroup name={'name'} /> {({ form, field, meta: { error, touched } }) => (
</FFormGroup> <FormGroup
label={<T id={'legal_organization_name'} />}
className={'form-group--name'}
intent={inputIntent({ error, touched })}
helperText={<ErrorMessage name={'name'} />}
>
<InputGroup
{...field}
intent={inputIntent({ error, touched })}
inputRef={accountRef}
/>
</FormGroup>
)}
</FastField>
{/* ---------- Location ---------- */} {/* ---------- Location ---------- */}
<FastField name={'location'}> <FastField name={'location'}>
@@ -55,11 +71,11 @@ export default function SetupOrganizationForm({ isSubmitting, values }) {
> >
<ListSelect <ListSelect
items={countries} items={countries}
onItemSelect={({ countryCode }) => { onItemSelect={({ value }) => {
form.setFieldValue('location', countryCode); form.setFieldValue('location', value);
}} }}
selectedItem={value} selectedItem={value}
selectedItemProp={'countryCode'} selectedItemProp={'value'}
defaultText={<T id={'select_business_location'} />} defaultText={<T id={'select_business_location'} />}
textProp={'name'} textProp={'name'}
popoverProps={{ minimal: true }} popoverProps={{ minimal: true }}

View File

@@ -16,7 +16,7 @@ import { getSetupOrganizationValidation } from './SetupOrganization.schema';
// Initial values. // Initial values.
const defaultValues = { const defaultValues = {
name: '', name: '',
location: '', location: 'libya',
baseCurrency: '', baseCurrency: '',
language: 'en', language: 'en',
fiscalYear: '', fiscalYear: '',

View File

@@ -31,14 +31,13 @@
"phone_number": "Phone Number", "phone_number": "Phone Number",
"you_email_address_is": "You email address is", "you_email_address_is": "You email address is",
"you_will_use_this_address_to_sign_in_to_bigcapital": "You will use this address to sign in to Bigcapital.", "you_will_use_this_address_to_sign_in_to_bigcapital": "You will use this address to sign in to Bigcapital.",
"signing_in_or_creating": "By signing in or creating an account, you agree with our <a>Terms & Conditions </a> and <a> Privacy Statement </a> ", "signing_in_or_creating": "By signing in or creating an account, you agree with our <br/> <a>Terms & Conditions </a> and <a> Privacy Statement </a> ",
"and": "And", "and": "And",
"create_account": "Create Account", "create_account": "Create Account",
"success": "Success", "success": "Success",
"register_a_new_organization": "Register a New Organization.", "register_a_new_organization": "Register a New Organization.",
"organization_name": "Organization Name", "organization_name": "Organization Name",
"email": "Email", "email": "Email",
"email_address": "Email Address",
"register": "Register", "register": "Register",
"password_successfully_updated": "The Password for your account was successfully updated.", "password_successfully_updated": "The Password for your account was successfully updated.",
"choose_a_new_password": "Choose a new password", "choose_a_new_password": "Choose a new password",

View File

@@ -1,32 +1,224 @@
body.authentication { body.authentication {
background-color: #fcfdff; background-color: #fcfdff;
} }
.authTransition { .authentication-insider {
width: 384px;
margin: 0 auto;
margin-bottom: 40px;
padding-top: 80px;
&__logo-section {
text-align: center;
margin-bottom: 60px;
}
&__content {
position: relative;
}
&__footer {
.auth-copyright {
text-align: center;
font-size: 12px;
color: #666;
.bp3-icon-bigcapital {
margin-top: 9px;
svg {
path {
fill: #a3a3a3;
}
}
}
}
}
}
.authTransition{
&-enter { &-enter {
opacity: 0; opacity: 0;
} }
&-enter-active { &-enter-active {
opacity: 1; opacity: 1;
transition: opacity 250ms ease-in-out; transition: opacity 250ms ease-in-out;
} }
&-enter-done { &-enter-done {
opacity: 1; opacity: 1;
} }
&-exit { &-exit {
opacity: 1; opacity: 1;
} }
&-exit-active { &-exit-active {
opacity: 0.5; opacity: 0.5;
transition: opacity 250ms ease-in-out; transition: opacity 250ms ease-in-out;
} }
&-exit-active { &-exit-active {
opacity: 0; opacity: 0;
display: none; display: none;
} }
}
}
.authentication-page {
&__goto-bigcapital {
position: fixed;
margin-top: 30px;
margin-left: 30px;
color: #777;
}
.bp3-input {
min-height: 40px;
}
.bp3-form-group {
margin-bottom: 25px;
}
.bp3-form-group.has-password-revealer {
.bp3-label {
display: flex;
justify-content: space-between;
}
.password-revealer {
.text {
font-size: 12px;
}
}
}
.bp3-button.bp3-fill.bp3-intent-primary {
font-size: 16px;
}
&__label-section {
margin-bottom: 30px;
color: #555;
h3 {
font-weight: 500;
font-size: 22px;
color: #2d2b43;
margin: 0 0 12px;
}
a {
text-decoration: underline;
color: #0040bd;
}
}
&__form-wrapper {
width: 100%;
margin: 0 auto;
}
&__footer-links {
padding: 9px;
border-top: 1px solid #ddd;
border-bottom: 1px solid #ddd;
text-align: center;
margin-bottom: 1.2rem;
a {
color: #0052cc;
}
}
&__loading-overlay {
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
background: rgba(252, 253, 255, 0.5);
display: flex;
justify-content: center;
}
&__submit-button-wrap {
margin: 0px 0px 24px 0px;
.bp3-button {
background-color: #0052cc;
min-height: 45px;
}
}
// Login Form
// ------------------------------
.login-form {
// width: 690px;
// margin: 0px auto;
// padding: 85px 50px;
.checkbox {
&--remember-me {
margin: -6px 0 26px 0px;
font-size: 14px;
}
}
}
// Register form
// ----------------------------
.register-form {
&__agreement-section {
margin-top: -10px;
p {
font-size: 13px;
margin-top: -10px;
margin-bottom: 24px;
line-height: 1.65;
}
}
&__submit-button-wrap {
margin: 25px 0px 25px 0px;
.bp3-button {
min-height: 45px;
background-color: #0052cc;
}
}
}
// Send reset password
// ----------------------------
.send-reset-password {
.form-group--crediential {
margin-bottom: 36px;
}
}
// Invite form.
// ----------------
.invite-form {
&__statement-section {
margin-top: -10px;
p {
font-size: 14px;
margin-bottom: 20px;
line-height: 1.65;
}
}
.authentication-page__loading-overlay {
background: rgba(252, 253, 255, 0.9);
}
}
}

View File

@@ -55,11 +55,6 @@
height: 40px; height: 40px;
font-size: 15px; font-size: 15px;
width: 100%; width: 100%;
&:disabled,
&.bp3-loading{
background-color: rgba(28, 36, 72, 0.5);
}
} }
} }
} }

View File

@@ -1,10 +0,0 @@
import { Countries } from '@/constants/countries';
export const getAllCountries = () => {
return Object.keys(Countries).map((countryCode) => {
return {
...Countries[countryCode],
countryCode,
}
});
};