🎉 Start project but-3
This commit is contained in:
commit
341889b6f7
6
.commitlintrc.js
Normal file
6
.commitlintrc.js
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
module.exports = {
|
||||||
|
rules: {
|
||||||
|
'start-with-gitmoji': [2, 'always'],
|
||||||
|
},
|
||||||
|
plugins: ['gitmoji'],
|
||||||
|
}
|
9
.env.example
Normal file
9
.env.example
Normal file
@ -0,0 +1,9 @@
|
|||||||
|
|
||||||
|
|
||||||
|
NODE_ENV="development"
|
||||||
|
MONGO_URL=""
|
||||||
|
PORT="2011"
|
||||||
|
|
||||||
|
TZ="Europe/Paris"
|
||||||
|
JWT_SECRET="3$iFp58e4Fo@"
|
||||||
|
FILE_SECRET="rmlncds234$DsfvnckdnoierxQQG4"
|
4
.eslintignore
Normal file
4
.eslintignore
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
node_modules/
|
||||||
|
.husky/
|
||||||
|
.idea/
|
||||||
|
dist/
|
25
.eslintrc
Normal file
25
.eslintrc
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
{
|
||||||
|
"env": {
|
||||||
|
"node": true,
|
||||||
|
"es6": true,
|
||||||
|
"browser": true,
|
||||||
|
"jest": true
|
||||||
|
},
|
||||||
|
"parserOptions": {
|
||||||
|
"ecmaVersion": "latest"
|
||||||
|
},
|
||||||
|
"extends": ["eslint:recommended", "plugin:node/recommended"],
|
||||||
|
"parser": "@babel/eslint-parser",
|
||||||
|
"rules": {
|
||||||
|
"node/exports-style": ["error", "module.exports"],
|
||||||
|
"node/file-extension-in-import": ["error", "always"],
|
||||||
|
"node/prefer-global/buffer": ["error", "always"],
|
||||||
|
"node/prefer-global/console": ["error", "always"],
|
||||||
|
"node/prefer-global/process": ["error", "always"],
|
||||||
|
"node/prefer-global/url-search-params": ["error", "always"],
|
||||||
|
"node/prefer-global/url": ["error", "always"],
|
||||||
|
"node/prefer-promises/dns": "error",
|
||||||
|
"node/prefer-promises/fs": "error",
|
||||||
|
"no-console": "warn"
|
||||||
|
}
|
||||||
|
}
|
10
.gitignore
vendored
Normal file
10
.gitignore
vendored
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
.idea/
|
||||||
|
node_modules/
|
||||||
|
yarn-error.log
|
||||||
|
.env
|
||||||
|
.env.production
|
||||||
|
deploy.key
|
||||||
|
dist/
|
||||||
|
.DS_Store
|
||||||
|
coverage
|
||||||
|
coverage.txt
|
3
.lintstagedrc.json
Normal file
3
.lintstagedrc.json
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
{
|
||||||
|
"*.{js,jsx,ts}": "prettier --write"
|
||||||
|
}
|
3
.prettierignore
Normal file
3
.prettierignore
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
node_modules/
|
||||||
|
.husky/
|
||||||
|
dist/
|
10
.prettierrc
Normal file
10
.prettierrc
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
{
|
||||||
|
"semi": false,
|
||||||
|
"trailingComma": "all",
|
||||||
|
"singleQuote": true,
|
||||||
|
"printWidth": 120,
|
||||||
|
"importOrder": ["^express$", "<THIRD_PARTY_MODULES>", "^@firgal/(.*)", "^@(.*)", "(.*)"],
|
||||||
|
"importOrderSortSpecifiers": true,
|
||||||
|
"importOrderSeparation": true,
|
||||||
|
"importOrderParserPlugins": ["typescript", "classProperties", "decorators-legacy"]
|
||||||
|
}
|
373
LICENSE.md
Normal file
373
LICENSE.md
Normal file
@ -0,0 +1,373 @@
|
|||||||
|
Mozilla Public License Version 2.0
|
||||||
|
==================================
|
||||||
|
|
||||||
|
1. Definitions
|
||||||
|
--------------
|
||||||
|
|
||||||
|
1.1. "Contributor"
|
||||||
|
means each individual or legal entity that creates, contributes to
|
||||||
|
the creation of, or owns Covered Software.
|
||||||
|
|
||||||
|
1.2. "Contributor Version"
|
||||||
|
means the combination of the Contributions of others (if any) used
|
||||||
|
by a Contributor and that particular Contributor's Contribution.
|
||||||
|
|
||||||
|
1.3. "Contribution"
|
||||||
|
means Covered Software of a particular Contributor.
|
||||||
|
|
||||||
|
1.4. "Covered Software"
|
||||||
|
means Source Code Form to which the initial Contributor has attached
|
||||||
|
the notice in Exhibit A, the Executable Form of such Source Code
|
||||||
|
Form, and Modifications of such Source Code Form, in each case
|
||||||
|
including portions thereof.
|
||||||
|
|
||||||
|
1.5. "Incompatible With Secondary Licenses"
|
||||||
|
means
|
||||||
|
|
||||||
|
(a) that the initial Contributor has attached the notice described
|
||||||
|
in Exhibit B to the Covered Software; or
|
||||||
|
|
||||||
|
(b) that the Covered Software was made available under the terms of
|
||||||
|
version 1.1 or earlier of the License, but not also under the
|
||||||
|
terms of a Secondary License.
|
||||||
|
|
||||||
|
1.6. "Executable Form"
|
||||||
|
means any form of the work other than Source Code Form.
|
||||||
|
|
||||||
|
1.7. "Larger Work"
|
||||||
|
means a work that combines Covered Software with other material, in
|
||||||
|
a separate file or files, that is not Covered Software.
|
||||||
|
|
||||||
|
1.8. "License"
|
||||||
|
means this document.
|
||||||
|
|
||||||
|
1.9. "Licensable"
|
||||||
|
means having the right to grant, to the maximum extent possible,
|
||||||
|
whether at the time of the initial grant or subsequently, any and
|
||||||
|
all of the rights conveyed by this License.
|
||||||
|
|
||||||
|
1.10. "Modifications"
|
||||||
|
means any of the following:
|
||||||
|
|
||||||
|
(a) any file in Source Code Form that results from an addition to,
|
||||||
|
deletion from, or modification of the contents of Covered
|
||||||
|
Software; or
|
||||||
|
|
||||||
|
(b) any new file in Source Code Form that contains any Covered
|
||||||
|
Software.
|
||||||
|
|
||||||
|
1.11. "Patent Claims" of a Contributor
|
||||||
|
means any patent claim(s), including without limitation, method,
|
||||||
|
process, and apparatus claims, in any patent Licensable by such
|
||||||
|
Contributor that would be infringed, but for the grant of the
|
||||||
|
License, by the making, using, selling, offering for sale, having
|
||||||
|
made, import, or transfer of either its Contributions or its
|
||||||
|
Contributor Version.
|
||||||
|
|
||||||
|
1.12. "Secondary License"
|
||||||
|
means either the GNU General Public License, Version 2.0, the GNU
|
||||||
|
Lesser General Public License, Version 2.1, the GNU Affero General
|
||||||
|
Public License, Version 3.0, or any later versions of those
|
||||||
|
licenses.
|
||||||
|
|
||||||
|
1.13. "Source Code Form"
|
||||||
|
means the form of the work preferred for making modifications.
|
||||||
|
|
||||||
|
1.14. "You" (or "Your")
|
||||||
|
means an individual or a legal entity exercising rights under this
|
||||||
|
License. For legal entities, "You" includes any entity that
|
||||||
|
controls, is controlled by, or is under common control with You. For
|
||||||
|
purposes of this definition, "control" means (a) the power, direct
|
||||||
|
or indirect, to cause the direction or management of such entity,
|
||||||
|
whether by contract or otherwise, or (b) ownership of more than
|
||||||
|
fifty percent (50%) of the outstanding shares or beneficial
|
||||||
|
ownership of such entity.
|
||||||
|
|
||||||
|
2. License Grants and Conditions
|
||||||
|
--------------------------------
|
||||||
|
|
||||||
|
2.1. Grants
|
||||||
|
|
||||||
|
Each Contributor hereby grants You a world-wide, royalty-free,
|
||||||
|
non-exclusive license:
|
||||||
|
|
||||||
|
(a) under intellectual property rights (other than patent or trademark)
|
||||||
|
Licensable by such Contributor to use, reproduce, make available,
|
||||||
|
modify, display, perform, distribute, and otherwise exploit its
|
||||||
|
Contributions, either on an unmodified basis, with Modifications, or
|
||||||
|
as part of a Larger Work; and
|
||||||
|
|
||||||
|
(b) under Patent Claims of such Contributor to make, use, sell, offer
|
||||||
|
for sale, have made, import, and otherwise transfer either its
|
||||||
|
Contributions or its Contributor Version.
|
||||||
|
|
||||||
|
2.2. Effective Date
|
||||||
|
|
||||||
|
The licenses granted in Section 2.1 with respect to any Contribution
|
||||||
|
become effective for each Contribution on the date the Contributor first
|
||||||
|
distributes such Contribution.
|
||||||
|
|
||||||
|
2.3. Limitations on Grant Scope
|
||||||
|
|
||||||
|
The licenses granted in this Section 2 are the only rights granted under
|
||||||
|
this License. No additional rights or licenses will be implied from the
|
||||||
|
distribution or licensing of Covered Software under this License.
|
||||||
|
Notwithstanding Section 2.1(b) above, no patent license is granted by a
|
||||||
|
Contributor:
|
||||||
|
|
||||||
|
(a) for any code that a Contributor has removed from Covered Software;
|
||||||
|
or
|
||||||
|
|
||||||
|
(b) for infringements caused by: (i) Your and any other third party's
|
||||||
|
modifications of Covered Software, or (ii) the combination of its
|
||||||
|
Contributions with other software (except as part of its Contributor
|
||||||
|
Version); or
|
||||||
|
|
||||||
|
(c) under Patent Claims infringed by Covered Software in the absence of
|
||||||
|
its Contributions.
|
||||||
|
|
||||||
|
This License does not grant any rights in the trademarks, service marks,
|
||||||
|
or logos of any Contributor (except as may be necessary to comply with
|
||||||
|
the notice requirements in Section 3.4).
|
||||||
|
|
||||||
|
2.4. Subsequent Licenses
|
||||||
|
|
||||||
|
No Contributor makes additional grants as a result of Your choice to
|
||||||
|
distribute the Covered Software under a subsequent version of this
|
||||||
|
License (see Section 10.2) or under the terms of a Secondary License (if
|
||||||
|
permitted under the terms of Section 3.3).
|
||||||
|
|
||||||
|
2.5. Representation
|
||||||
|
|
||||||
|
Each Contributor represents that the Contributor believes its
|
||||||
|
Contributions are its original creation(s) or it has sufficient rights
|
||||||
|
to grant the rights to its Contributions conveyed by this License.
|
||||||
|
|
||||||
|
2.6. Fair Use
|
||||||
|
|
||||||
|
This License is not intended to limit any rights You have under
|
||||||
|
applicable copyright doctrines of fair use, fair dealing, or other
|
||||||
|
equivalents.
|
||||||
|
|
||||||
|
2.7. Conditions
|
||||||
|
|
||||||
|
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
|
||||||
|
in Section 2.1.
|
||||||
|
|
||||||
|
3. Responsibilities
|
||||||
|
-------------------
|
||||||
|
|
||||||
|
3.1. Distribution of Source Form
|
||||||
|
|
||||||
|
All distribution of Covered Software in Source Code Form, including any
|
||||||
|
Modifications that You create or to which You contribute, must be under
|
||||||
|
the terms of this License. You must inform recipients that the Source
|
||||||
|
Code Form of the Covered Software is governed by the terms of this
|
||||||
|
License, and how they can obtain a copy of this License. You may not
|
||||||
|
attempt to alter or restrict the recipients' rights in the Source Code
|
||||||
|
Form.
|
||||||
|
|
||||||
|
3.2. Distribution of Executable Form
|
||||||
|
|
||||||
|
If You distribute Covered Software in Executable Form then:
|
||||||
|
|
||||||
|
(a) such Covered Software must also be made available in Source Code
|
||||||
|
Form, as described in Section 3.1, and You must inform recipients of
|
||||||
|
the Executable Form how they can obtain a copy of such Source Code
|
||||||
|
Form by reasonable means in a timely manner, at a charge no more
|
||||||
|
than the cost of distribution to the recipient; and
|
||||||
|
|
||||||
|
(b) You may distribute such Executable Form under the terms of this
|
||||||
|
License, or sublicense it under different terms, provided that the
|
||||||
|
license for the Executable Form does not attempt to limit or alter
|
||||||
|
the recipients' rights in the Source Code Form under this License.
|
||||||
|
|
||||||
|
3.3. Distribution of a Larger Work
|
||||||
|
|
||||||
|
You may create and distribute a Larger Work under terms of Your choice,
|
||||||
|
provided that You also comply with the requirements of this License for
|
||||||
|
the Covered Software. If the Larger Work is a combination of Covered
|
||||||
|
Software with a work governed by one or more Secondary Licenses, and the
|
||||||
|
Covered Software is not Incompatible With Secondary Licenses, this
|
||||||
|
License permits You to additionally distribute such Covered Software
|
||||||
|
under the terms of such Secondary License(s), so that the recipient of
|
||||||
|
the Larger Work may, at their option, further distribute the Covered
|
||||||
|
Software under the terms of either this License or such Secondary
|
||||||
|
License(s).
|
||||||
|
|
||||||
|
3.4. Notices
|
||||||
|
|
||||||
|
You may not remove or alter the substance of any license notices
|
||||||
|
(including copyright notices, patent notices, disclaimers of warranty,
|
||||||
|
or limitations of liability) contained within the Source Code Form of
|
||||||
|
the Covered Software, except that You may alter any license notices to
|
||||||
|
the extent required to remedy known factual inaccuracies.
|
||||||
|
|
||||||
|
3.5. Application of Additional Terms
|
||||||
|
|
||||||
|
You may choose to offer, and to charge a fee for, warranty, support,
|
||||||
|
indemnity or liability obligations to one or more recipients of Covered
|
||||||
|
Software. However, You may do so only on Your own behalf, and not on
|
||||||
|
behalf of any Contributor. You must make it absolutely clear that any
|
||||||
|
such warranty, support, indemnity, or liability obligation is offered by
|
||||||
|
You alone, and You hereby agree to indemnify every Contributor for any
|
||||||
|
liability incurred by such Contributor as a result of warranty, support,
|
||||||
|
indemnity or liability terms You offer. You may include additional
|
||||||
|
disclaimers of warranty and limitations of liability specific to any
|
||||||
|
jurisdiction.
|
||||||
|
|
||||||
|
4. Inability to Comply Due to Statute or Regulation
|
||||||
|
---------------------------------------------------
|
||||||
|
|
||||||
|
If it is impossible for You to comply with any of the terms of this
|
||||||
|
License with respect to some or all of the Covered Software due to
|
||||||
|
statute, judicial order, or regulation then You must: (a) comply with
|
||||||
|
the terms of this License to the maximum extent possible; and (b)
|
||||||
|
describe the limitations and the code they affect. Such description must
|
||||||
|
be placed in a text file included with all distributions of the Covered
|
||||||
|
Software under this License. Except to the extent prohibited by statute
|
||||||
|
or regulation, such description must be sufficiently detailed for a
|
||||||
|
recipient of ordinary skill to be able to understand it.
|
||||||
|
|
||||||
|
5. Termination
|
||||||
|
--------------
|
||||||
|
|
||||||
|
5.1. The rights granted under this License will terminate automatically
|
||||||
|
if You fail to comply with any of its terms. However, if You become
|
||||||
|
compliant, then the rights granted under this License from a particular
|
||||||
|
Contributor are reinstated (a) provisionally, unless and until such
|
||||||
|
Contributor explicitly and finally terminates Your grants, and (b) on an
|
||||||
|
ongoing basis, if such Contributor fails to notify You of the
|
||||||
|
non-compliance by some reasonable means prior to 60 days after You have
|
||||||
|
come back into compliance. Moreover, Your grants from a particular
|
||||||
|
Contributor are reinstated on an ongoing basis if such Contributor
|
||||||
|
notifies You of the non-compliance by some reasonable means, this is the
|
||||||
|
first time You have received notice of non-compliance with this License
|
||||||
|
from such Contributor, and You become compliant prior to 30 days after
|
||||||
|
Your receipt of the notice.
|
||||||
|
|
||||||
|
5.2. If You initiate litigation against any entity by asserting a patent
|
||||||
|
infringement claim (excluding declaratory judgment actions,
|
||||||
|
counter-claims, and cross-claims) alleging that a Contributor Version
|
||||||
|
directly or indirectly infringes any patent, then the rights granted to
|
||||||
|
You by any and all Contributors for the Covered Software under Section
|
||||||
|
2.1 of this License shall terminate.
|
||||||
|
|
||||||
|
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
|
||||||
|
end user license agreements (excluding distributors and resellers) which
|
||||||
|
have been validly granted by You or Your distributors under this License
|
||||||
|
prior to termination shall survive termination.
|
||||||
|
|
||||||
|
************************************************************************
|
||||||
|
* *
|
||||||
|
* 6. Disclaimer of Warranty *
|
||||||
|
* ------------------------- *
|
||||||
|
* *
|
||||||
|
* Covered Software is provided under this License on an "as is" *
|
||||||
|
* basis, without warranty of any kind, either expressed, implied, or *
|
||||||
|
* statutory, including, without limitation, warranties that the *
|
||||||
|
* Covered Software is free of defects, merchantable, fit for a *
|
||||||
|
* particular purpose or non-infringing. The entire risk as to the *
|
||||||
|
* quality and performance of the Covered Software is with You. *
|
||||||
|
* Should any Covered Software prove defective in any respect, You *
|
||||||
|
* (not any Contributor) assume the cost of any necessary servicing, *
|
||||||
|
* repair, or correction. This disclaimer of warranty constitutes an *
|
||||||
|
* essential part of this License. No use of any Covered Software is *
|
||||||
|
* authorized under this License except under this disclaimer. *
|
||||||
|
* *
|
||||||
|
************************************************************************
|
||||||
|
|
||||||
|
************************************************************************
|
||||||
|
* *
|
||||||
|
* 7. Limitation of Liability *
|
||||||
|
* -------------------------- *
|
||||||
|
* *
|
||||||
|
* Under no circumstances and under no legal theory, whether tort *
|
||||||
|
* (including negligence), contract, or otherwise, shall any *
|
||||||
|
* Contributor, or anyone who distributes Covered Software as *
|
||||||
|
* permitted above, be liable to You for any direct, indirect, *
|
||||||
|
* special, incidental, or consequential damages of any character *
|
||||||
|
* including, without limitation, damages for lost profits, loss of *
|
||||||
|
* goodwill, work stoppage, computer failure or malfunction, or any *
|
||||||
|
* and all other commercial damages or losses, even if such party *
|
||||||
|
* shall have been informed of the possibility of such damages. This *
|
||||||
|
* limitation of liability shall not apply to liability for death or *
|
||||||
|
* personal injury resulting from such party's negligence to the *
|
||||||
|
* extent applicable law prohibits such limitation. Some *
|
||||||
|
* jurisdictions do not allow the exclusion or limitation of *
|
||||||
|
* incidental or consequential damages, so this exclusion and *
|
||||||
|
* limitation may not apply to You. *
|
||||||
|
* *
|
||||||
|
************************************************************************
|
||||||
|
|
||||||
|
8. Litigation
|
||||||
|
-------------
|
||||||
|
|
||||||
|
Any litigation relating to this License may be brought only in the
|
||||||
|
courts of a jurisdiction where the defendant maintains its principal
|
||||||
|
place of business and such litigation shall be governed by laws of that
|
||||||
|
jurisdiction, without reference to its conflict-of-law provisions.
|
||||||
|
Nothing in this Section shall prevent a party's ability to bring
|
||||||
|
cross-claims or counter-claims.
|
||||||
|
|
||||||
|
9. Miscellaneous
|
||||||
|
----------------
|
||||||
|
|
||||||
|
This License represents the complete agreement concerning the subject
|
||||||
|
matter hereof. If any provision of this License is held to be
|
||||||
|
unenforceable, such provision shall be reformed only to the extent
|
||||||
|
necessary to make it enforceable. Any law or regulation which provides
|
||||||
|
that the language of a contract shall be construed against the drafter
|
||||||
|
shall not be used to construe this License against a Contributor.
|
||||||
|
|
||||||
|
10. Versions of the License
|
||||||
|
---------------------------
|
||||||
|
|
||||||
|
10.1. New Versions
|
||||||
|
|
||||||
|
Mozilla Foundation is the license steward. Except as provided in Section
|
||||||
|
10.3, no one other than the license steward has the right to modify or
|
||||||
|
publish new versions of this License. Each version will be given a
|
||||||
|
distinguishing version number.
|
||||||
|
|
||||||
|
10.2. Effect of New Versions
|
||||||
|
|
||||||
|
You may distribute the Covered Software under the terms of the version
|
||||||
|
of the License under which You originally received the Covered Software,
|
||||||
|
or under the terms of any subsequent version published by the license
|
||||||
|
steward.
|
||||||
|
|
||||||
|
10.3. Modified Versions
|
||||||
|
|
||||||
|
If you create software not governed by this License, and you want to
|
||||||
|
create a new license for such software, you may create and use a
|
||||||
|
modified version of this License if you rename the license and remove
|
||||||
|
any references to the name of the license steward (except to note that
|
||||||
|
such modified license differs from this License).
|
||||||
|
|
||||||
|
10.4. Distributing Source Code Form that is Incompatible With Secondary
|
||||||
|
Licenses
|
||||||
|
|
||||||
|
If You choose to distribute Source Code Form that is Incompatible With
|
||||||
|
Secondary Licenses under the terms of this version of the License, the
|
||||||
|
notice described in Exhibit B of this License must be attached.
|
||||||
|
|
||||||
|
Exhibit A - Source Code Form License Notice
|
||||||
|
-------------------------------------------
|
||||||
|
|
||||||
|
This Source Code Form is subject to the terms of the Mozilla Public
|
||||||
|
License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
|
file, You can obtain one at http://mozilla.org/MPL/2.0/.
|
||||||
|
|
||||||
|
If it is not possible or desirable to put the notice in a particular
|
||||||
|
file, then You may include the notice in a location (such as a LICENSE
|
||||||
|
file in a relevant directory) where a recipient would be likely to look
|
||||||
|
for such a notice.
|
||||||
|
|
||||||
|
You may add additional accurate notices of copyright ownership.
|
||||||
|
|
||||||
|
Exhibit B - "Incompatible With Secondary Licenses" Notice
|
||||||
|
---------------------------------------------------------
|
||||||
|
|
||||||
|
This Source Code Form is "Incompatible With Secondary Licenses", as
|
||||||
|
defined by the Mozilla Public License, v. 2.0.
|
35
README.md
Normal file
35
README.md
Normal file
@ -0,0 +1,35 @@
|
|||||||
|
# Setup back
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Contributing
|
||||||
|
|
||||||
|
### Getting started
|
||||||
|
|
||||||
|
Clone the project:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git clone git@github.com:FelixLgr/BUT-3-Dev.git
|
||||||
|
```
|
||||||
|
|
||||||
|
Add environment variables:
|
||||||
|
|
||||||
|
⚠️The MONGO_URL and MONGO_URL_TEST variables must be url encoded
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cp .env.example .env
|
||||||
|
```
|
||||||
|
|
||||||
|
Set up the project:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
yarn setup
|
||||||
|
```
|
||||||
|
|
||||||
|
### Development
|
||||||
|
|
||||||
|
To start the development server you need to run the following commands:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
yarn start:development
|
||||||
|
```
|
18
SECURITY.md
Normal file
18
SECURITY.md
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
# Security Policy
|
||||||
|
|
||||||
|
## Supported Versions
|
||||||
|
|
||||||
|
Use this section to tell people about which versions of your project are
|
||||||
|
currently being supported with security updates.
|
||||||
|
|
||||||
|
| Version | Supported |
|
||||||
|
| ------- | ------------------ |
|
||||||
|
| 0.0.x | :white_check_mark: |
|
||||||
|
|
||||||
|
## Reporting a Vulnerability
|
||||||
|
|
||||||
|
Use this section to tell people how to report a vulnerability.
|
||||||
|
|
||||||
|
Tell them where to go, how often they can expect to get an update on a
|
||||||
|
reported vulnerability, what to expect if the vulnerability is accepted or
|
||||||
|
declined, etc.
|
31
ecosystem.config.js
Normal file
31
ecosystem.config.js
Normal file
@ -0,0 +1,31 @@
|
|||||||
|
const dotenv = require('dotenv')
|
||||||
|
dotenv.config()
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
deploy: {
|
||||||
|
production: {
|
||||||
|
key: 'deploy.key',
|
||||||
|
user: process.env.HOST_USER,
|
||||||
|
host: [
|
||||||
|
{
|
||||||
|
host: process.env.HOST,
|
||||||
|
port: process.env.HOST_PORT,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
ssh_options: ['StrictHostKeyChecking=no'],
|
||||||
|
ref: 'origin/main',
|
||||||
|
path: process.env.HOST_PATH,
|
||||||
|
'post-deploy': 'yarn setup && yarn build && pm2 startOrRestart production.config.js && pm2 save',
|
||||||
|
env: {
|
||||||
|
NODE_ENV: process.env.NODE_ENV,
|
||||||
|
MONGO_URL: process.env.MONGO_URL,
|
||||||
|
PORT: process.env.PORT,
|
||||||
|
|
||||||
|
TZ: process.env.TZ,
|
||||||
|
JWT_SECRET: process.env.JWT_SECRET,
|
||||||
|
FILE_SECRET: process.env.FILE_SECRET,
|
||||||
|
COOKIE_DOMAIN: process.env.COOKIE_DOMAIN,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
28
jest.config.ts
Normal file
28
jest.config.ts
Normal file
@ -0,0 +1,28 @@
|
|||||||
|
import type { Config } from 'jest'
|
||||||
|
|
||||||
|
const config: Config = {
|
||||||
|
preset: 'ts-jest',
|
||||||
|
testEnvironment: 'node',
|
||||||
|
setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
|
||||||
|
moduleNameMapper: {
|
||||||
|
'@helpers': '<rootDir>/src/helpers',
|
||||||
|
'@constants': '<rootDir>/src/constants',
|
||||||
|
'@controllers': '<rootDir>/src/controllers',
|
||||||
|
'@models': '<rootDir>/src/models',
|
||||||
|
'@routes': '<rootDir>/src/routes',
|
||||||
|
'@types': '<rootDir>/src/types',
|
||||||
|
},
|
||||||
|
testTimeout: 10000,
|
||||||
|
coverageDirectory: 'coverage',
|
||||||
|
coverageReporters: ['json-summary', 'text'],
|
||||||
|
coveragePathIgnorePatterns: [
|
||||||
|
'<rootDir>/src/types/',
|
||||||
|
'<rootDir>/src/models/',
|
||||||
|
'<rootDir>/src/index.ts',
|
||||||
|
'databaseConnection.ts',
|
||||||
|
'getCorsOptions.ts',
|
||||||
|
'test.config.ts',
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
export default config
|
9
jest.setup.ts
Normal file
9
jest.setup.ts
Normal file
@ -0,0 +1,9 @@
|
|||||||
|
import mongoose from 'mongoose'
|
||||||
|
|
||||||
|
global.beforeEach(async () => {
|
||||||
|
await mongoose.connect(decodeURIComponent(process.env.MONGO_URL_TEST || ''))
|
||||||
|
})
|
||||||
|
|
||||||
|
global.afterEach(async () => {
|
||||||
|
await mongoose.connection.close()
|
||||||
|
})
|
7
nodemon.json
Normal file
7
nodemon.json
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
{
|
||||||
|
"watch": [
|
||||||
|
"src"
|
||||||
|
],
|
||||||
|
"exec": "ts-node src/index.ts",
|
||||||
|
"ext": "js,ts,json"
|
||||||
|
}
|
70
package.json
Normal file
70
package.json
Normal file
@ -0,0 +1,70 @@
|
|||||||
|
{
|
||||||
|
"name": "setup-back",
|
||||||
|
"version": "1.1.3",
|
||||||
|
"description": "Backend Setup",
|
||||||
|
"private": true,
|
||||||
|
"license": "UNLICENSED",
|
||||||
|
"main": "dist/index.js",
|
||||||
|
"repository": "git@github.com:FelixLgr/BUT-3-Dev.git",
|
||||||
|
"scripts": {
|
||||||
|
"build": "rimraf dist && tsc && tsc-alias",
|
||||||
|
"check-types": "tsc --noemit",
|
||||||
|
"deploy": "pm2 deploy ecosystem.config.js production",
|
||||||
|
"format": "prettier --write '**/*.{js,jsx,ts}'",
|
||||||
|
"lint": "eslint . && yarn check-types",
|
||||||
|
"setup": "yarn install",
|
||||||
|
"start:development": "nodemon",
|
||||||
|
"start:production": "node dist/index.js",
|
||||||
|
"test": "cross-env NODE_ENV=test jest",
|
||||||
|
"test:cov": "cross-env NODE_ENV=test jest --coverage"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@types/bcryptjs": "^2.4.2",
|
||||||
|
"@types/cookie-parser": "^1.4.3",
|
||||||
|
"@types/cors": "^2.8.12",
|
||||||
|
"@types/crypto-js": "^4.1.1",
|
||||||
|
"@types/express": "^4.17.14",
|
||||||
|
"@types/jest": "^29.1.2",
|
||||||
|
"@types/jsonwebtoken": "^9.0.1",
|
||||||
|
"@types/multer": "^1.4.7",
|
||||||
|
"@types/node": "^18.7.18",
|
||||||
|
"@types/supertest": "^2.0.12",
|
||||||
|
"axios": "^1.1.2",
|
||||||
|
"bcryptjs": "^2.4.3",
|
||||||
|
"cookie-parser": "^1.4.6",
|
||||||
|
"cors": "^2.8.5",
|
||||||
|
"crypto-js": "^4.1.1",
|
||||||
|
"date-fns": "^2.29.3",
|
||||||
|
"dotenv": "^16.0.2",
|
||||||
|
"express": "^4.18.1",
|
||||||
|
"jsonwebtoken": "^9.0.0",
|
||||||
|
"mongoose": "^6.6.0",
|
||||||
|
"multer": "^1.4.5-lts.1",
|
||||||
|
"path": "^0.12.7",
|
||||||
|
"rimraf": "^4.1.2",
|
||||||
|
"sharp": "^0.32.1",
|
||||||
|
"tsc-alias": "^1.8.2",
|
||||||
|
"typescript": "^4.8.3"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@babel/core": "^7.19.0",
|
||||||
|
"@babel/eslint-parser": "^7.18.9",
|
||||||
|
"@babel/preset-env": "^7.19.0",
|
||||||
|
"@swc/core": "^1.3.0",
|
||||||
|
"@trivago/prettier-plugin-sort-imports": "^4.0.0",
|
||||||
|
"commitlint": "^17.1.2",
|
||||||
|
"commitlint-plugin-gitmoji": "^2.2.4",
|
||||||
|
"cross-env": "^7.0.3",
|
||||||
|
"eslint": "^8.23.1",
|
||||||
|
"eslint-plugin-node": "^11.1.0",
|
||||||
|
"jest": "^29.1.2",
|
||||||
|
"lint-staged": "^13.0.3",
|
||||||
|
"nodemon": "^2.0.19",
|
||||||
|
"pm2": "^5.2.0",
|
||||||
|
"prettier": "^2.7.1",
|
||||||
|
"supertest": "^6.3.0",
|
||||||
|
"ts-jest": "^29.0.3",
|
||||||
|
"ts-node": "^10.9.1",
|
||||||
|
"tsconfig-paths": "^4.1.0"
|
||||||
|
}
|
||||||
|
}
|
9
production.config.js
Normal file
9
production.config.js
Normal file
@ -0,0 +1,9 @@
|
|||||||
|
module.exports = {
|
||||||
|
apps: [
|
||||||
|
{
|
||||||
|
name: 'Setup',
|
||||||
|
script: './dist/index.js',
|
||||||
|
autorestart: true,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}
|
37
src/app.ts
Normal file
37
src/app.ts
Normal file
@ -0,0 +1,37 @@
|
|||||||
|
import express from 'express'
|
||||||
|
|
||||||
|
import { getCorsOptions } from '@helpers'
|
||||||
|
import {
|
||||||
|
authenticationRouter,
|
||||||
|
categoryRouter,
|
||||||
|
fileRouter,
|
||||||
|
indexRouter,
|
||||||
|
itemRouter,
|
||||||
|
roomRouter,
|
||||||
|
userRouter,
|
||||||
|
} from '@routes'
|
||||||
|
import { Express } from '@types'
|
||||||
|
|
||||||
|
import cookieParser from 'cookie-parser'
|
||||||
|
import cors from 'cors'
|
||||||
|
import dotenv from 'dotenv'
|
||||||
|
|
||||||
|
dotenv.config()
|
||||||
|
|
||||||
|
const app: Express = express()
|
||||||
|
|
||||||
|
app.use(cors(getCorsOptions()))
|
||||||
|
|
||||||
|
app.use(express.json())
|
||||||
|
app.use(express.urlencoded({ extended: false }))
|
||||||
|
app.use(cookieParser())
|
||||||
|
|
||||||
|
app.use('/api', indexRouter)
|
||||||
|
app.use('/api/authenticate', authenticationRouter)
|
||||||
|
app.use('/api/user', userRouter)
|
||||||
|
app.use('/api/room', roomRouter)
|
||||||
|
app.use('/api/file', fileRouter)
|
||||||
|
app.use('/api/category', categoryRouter)
|
||||||
|
app.use('/api/item', itemRouter)
|
||||||
|
|
||||||
|
export default app
|
4
src/constants.ts
Normal file
4
src/constants.ts
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
export const IMAGE_RESIZE = {
|
||||||
|
width: 500,
|
||||||
|
height: 500,
|
||||||
|
}
|
19
src/controllers/category.ts
Normal file
19
src/controllers/category.ts
Normal file
@ -0,0 +1,19 @@
|
|||||||
|
import { CategoryModel } from '@models'
|
||||||
|
import { CategoryResponseType, ControllerResponseType, HttpStatus, ResponseType } from '@types'
|
||||||
|
|
||||||
|
export const getCategories = async (): ControllerResponseType<CategoryResponseType[]> => {
|
||||||
|
let response: ResponseType<CategoryResponseType[]> = {
|
||||||
|
status: HttpStatus.OK,
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
response.data = await CategoryModel.find().sort('name').exec()
|
||||||
|
} catch (e) {
|
||||||
|
return {
|
||||||
|
status: HttpStatus.INTERNAL_SERVER_ERROR,
|
||||||
|
error: 'Internal server error',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return response
|
||||||
|
}
|
120
src/controllers/file.ts
Normal file
120
src/controllers/file.ts
Normal file
@ -0,0 +1,120 @@
|
|||||||
|
import { invoiceFileFilter } from '@helpers'
|
||||||
|
import { FileModel } from '@models'
|
||||||
|
import { HttpStatus, ICreateFileInput, IFile, IUser, ResponseType } from '@types'
|
||||||
|
|
||||||
|
import CryptoJS from 'crypto-js'
|
||||||
|
|
||||||
|
export const getFile = async (_id: IFile['_id'], loggedUser: IUser) => {
|
||||||
|
let response: ResponseType<IFile> = {
|
||||||
|
status: HttpStatus.OK,
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const file = await FileModel.findById(_id).exec()
|
||||||
|
|
||||||
|
if (file === null) {
|
||||||
|
return {
|
||||||
|
status: HttpStatus.NOT_FOUND,
|
||||||
|
error: 'File not found',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (loggedUser._id !== file.user.toString() && loggedUser.permission < 10) {
|
||||||
|
return {
|
||||||
|
status: HttpStatus.FORBIDDEN,
|
||||||
|
error: 'Forbidden',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const key = `${process.env.FILE_SECRET}${loggedUser._id}`
|
||||||
|
|
||||||
|
file.data = CryptoJS.AES.decrypt(file.data, key).toString(CryptoJS.enc.Utf8)
|
||||||
|
response.data = file
|
||||||
|
} catch (error) {
|
||||||
|
return {
|
||||||
|
status: HttpStatus.INTERNAL_SERVER_ERROR,
|
||||||
|
error: 'Internal server error',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return response
|
||||||
|
}
|
||||||
|
|
||||||
|
export const uploadFile = async (file: ICreateFileInput, loggedUser: IUser) => {
|
||||||
|
let response: ResponseType<IFile> = {
|
||||||
|
status: HttpStatus.OK,
|
||||||
|
}
|
||||||
|
|
||||||
|
if (file === undefined) {
|
||||||
|
return {
|
||||||
|
status: HttpStatus.NOT_FOUND,
|
||||||
|
error: 'No file was found',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let validation = invoiceFileFilter(file)
|
||||||
|
if (validation.error) {
|
||||||
|
return {
|
||||||
|
status: HttpStatus.BAD_REQUEST,
|
||||||
|
error: validation.error,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = file.buffer.toString('base64')
|
||||||
|
|
||||||
|
const key = `${process.env.FILE_SECRET}${loggedUser._id}`
|
||||||
|
|
||||||
|
const file_encoded = CryptoJS.AES.encrypt(data, key).toString()
|
||||||
|
|
||||||
|
const currentFile = new FileModel({
|
||||||
|
name: file.originalname,
|
||||||
|
mimetype: file.mimetype,
|
||||||
|
data: file_encoded,
|
||||||
|
size: file.size,
|
||||||
|
user: loggedUser._id,
|
||||||
|
})
|
||||||
|
|
||||||
|
try {
|
||||||
|
response.data = await currentFile.save()
|
||||||
|
} catch (e) {
|
||||||
|
return {
|
||||||
|
status: HttpStatus.INTERNAL_SERVER_ERROR,
|
||||||
|
error: 'Internal server error',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return response
|
||||||
|
}
|
||||||
|
|
||||||
|
export const deleteFile = async (_id: IFile['_id'], loggedUser: IUser) => {
|
||||||
|
let response: ResponseType = {
|
||||||
|
status: HttpStatus.OK,
|
||||||
|
}
|
||||||
|
|
||||||
|
const oldFile = await FileModel.findById<IFile>(_id).exec()
|
||||||
|
|
||||||
|
if (oldFile === null) {
|
||||||
|
return {
|
||||||
|
status: HttpStatus.NOT_FOUND,
|
||||||
|
error: 'File not found',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (loggedUser._id !== oldFile.user.toString() && loggedUser.permission < 10) {
|
||||||
|
return {
|
||||||
|
status: HttpStatus.FORBIDDEN,
|
||||||
|
error: 'You are not allowed to delete this file',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await FileModel.findByIdAndDelete(_id).exec()
|
||||||
|
} catch (e) {
|
||||||
|
return {
|
||||||
|
status: HttpStatus.INTERNAL_SERVER_ERROR,
|
||||||
|
error: 'Internal server error',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return response
|
||||||
|
}
|
5
src/controllers/index.ts
Normal file
5
src/controllers/index.ts
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
export * from './user'
|
||||||
|
export * from './room'
|
||||||
|
export * from './file'
|
||||||
|
export * from './item'
|
||||||
|
export * from './category'
|
370
src/controllers/item.ts
Normal file
370
src/controllers/item.ts
Normal file
@ -0,0 +1,370 @@
|
|||||||
|
import { IMAGE_RESIZE } from '@constants'
|
||||||
|
import { deleteFile, uploadFile } from '@controllers'
|
||||||
|
import { imageToWebP, resizeImage } from '@helpers'
|
||||||
|
import { FileModel, ItemModel } from '@models'
|
||||||
|
import {
|
||||||
|
ControllerResponseType,
|
||||||
|
HttpStatus,
|
||||||
|
ICreateItemInput,
|
||||||
|
IFile,
|
||||||
|
IItem,
|
||||||
|
IUpdateItemInput,
|
||||||
|
IUploadFile,
|
||||||
|
IUser,
|
||||||
|
ItemReponseType,
|
||||||
|
ResponseType,
|
||||||
|
} from '@types'
|
||||||
|
|
||||||
|
import { isValid } from 'date-fns'
|
||||||
|
import { Types, sanitizeFilter } from 'mongoose'
|
||||||
|
|
||||||
|
export const createItem = async (
|
||||||
|
item: ICreateItemInput,
|
||||||
|
loggedUser: IUser,
|
||||||
|
files?: IUploadFile,
|
||||||
|
): ControllerResponseType<ItemReponseType> => {
|
||||||
|
let response: ResponseType<ItemReponseType> = {
|
||||||
|
status: HttpStatus.OK,
|
||||||
|
}
|
||||||
|
|
||||||
|
item.user = loggedUser._id
|
||||||
|
|
||||||
|
let invoice: IItem['invoice']
|
||||||
|
let image: IItem['image']
|
||||||
|
let categories: IItem['categories']
|
||||||
|
let purchaseDate: Date | undefined
|
||||||
|
|
||||||
|
if (files) {
|
||||||
|
if (files.invoice) {
|
||||||
|
const result = await uploadFile(files.invoice[0], loggedUser)
|
||||||
|
if (result.error) {
|
||||||
|
return {
|
||||||
|
status: HttpStatus.BAD_REQUEST,
|
||||||
|
error: result.error,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
invoice = result?.data?._id
|
||||||
|
}
|
||||||
|
|
||||||
|
if (files.image) {
|
||||||
|
const imageCompressed = files.image[0]
|
||||||
|
imageCompressed.buffer = await imageToWebP(
|
||||||
|
await resizeImage(imageCompressed.buffer, IMAGE_RESIZE.width, IMAGE_RESIZE.height),
|
||||||
|
)
|
||||||
|
imageCompressed.mimetype = 'image/webp'
|
||||||
|
imageCompressed.originalname = imageCompressed.originalname.replace(/\.[^/.]+$/, '.webp')
|
||||||
|
const result = await uploadFile(imageCompressed, loggedUser)
|
||||||
|
if (result.error) {
|
||||||
|
return {
|
||||||
|
status: HttpStatus.BAD_REQUEST,
|
||||||
|
error: result.error,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
image = result?.data?._id
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (item.purchaseDate) {
|
||||||
|
try {
|
||||||
|
if (!isValid(new Date(item.purchaseDate))) {
|
||||||
|
return {
|
||||||
|
status: HttpStatus.BAD_REQUEST,
|
||||||
|
error: 'Invalid date',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
purchaseDate = new Date(item.purchaseDate)
|
||||||
|
} catch (error) {
|
||||||
|
return {
|
||||||
|
status: HttpStatus.BAD_REQUEST,
|
||||||
|
error: 'Invalid date',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (item.price && item.price < 0) {
|
||||||
|
return {
|
||||||
|
status: HttpStatus.BAD_REQUEST,
|
||||||
|
error: 'Price cannot be negative',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (item.categories) {
|
||||||
|
categories = JSON.parse(item.categories)
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const currentItem = new ItemModel({
|
||||||
|
...item,
|
||||||
|
invoice,
|
||||||
|
image,
|
||||||
|
categories,
|
||||||
|
purchaseDate,
|
||||||
|
})
|
||||||
|
response.data = (await currentItem.save()) as ItemReponseType
|
||||||
|
} catch (e) {
|
||||||
|
return {
|
||||||
|
status: HttpStatus.INTERNAL_SERVER_ERROR,
|
||||||
|
error: 'Internal server error',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return response
|
||||||
|
}
|
||||||
|
|
||||||
|
export const getItems = async (loggedUser: IUser): ControllerResponseType<ItemReponseType[]> => {
|
||||||
|
let response: ResponseType<ItemReponseType[]> = {
|
||||||
|
status: HttpStatus.OK,
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
response.data = await ItemModel.find<ItemReponseType>(sanitizeFilter({ user: loggedUser._id }))
|
||||||
|
.populate('categories')
|
||||||
|
.exec()
|
||||||
|
} catch (e) {
|
||||||
|
return {
|
||||||
|
status: HttpStatus.INTERNAL_SERVER_ERROR,
|
||||||
|
error: 'Internal server error',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return response
|
||||||
|
}
|
||||||
|
|
||||||
|
export const getItem = async (_id: IItem['_id'], loggedUser: IUser) => {
|
||||||
|
let response: ResponseType<ItemReponseType> = {
|
||||||
|
status: HttpStatus.OK,
|
||||||
|
}
|
||||||
|
|
||||||
|
const item = await ItemModel.findById<ItemReponseType>(_id).populate('categories').exec()
|
||||||
|
|
||||||
|
if (item === null) {
|
||||||
|
return {
|
||||||
|
status: HttpStatus.NOT_FOUND,
|
||||||
|
error: 'Item not found',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (loggedUser._id !== item.user.toString() && loggedUser.permission < 10) {
|
||||||
|
return {
|
||||||
|
status: HttpStatus.FORBIDDEN,
|
||||||
|
error: 'Forbidden',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
response.data = item
|
||||||
|
|
||||||
|
return response
|
||||||
|
}
|
||||||
|
|
||||||
|
export const getBrandsName = async (loggedUser: IUser): ControllerResponseType<string[]> => {
|
||||||
|
let response: ResponseType<string[]> = {
|
||||||
|
status: HttpStatus.OK,
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const data = await ItemModel.aggregate([
|
||||||
|
{
|
||||||
|
$match: sanitizeFilter({
|
||||||
|
user: new Types.ObjectId(loggedUser._id),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
$group: {
|
||||||
|
_id: {
|
||||||
|
brand: '$brand',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
$sort: {
|
||||||
|
'_id.brand': 1,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
]).exec()
|
||||||
|
|
||||||
|
response.data = data.map((brand) => brand?._id?.brand)
|
||||||
|
} catch (error) {
|
||||||
|
return {
|
||||||
|
status: HttpStatus.INTERNAL_SERVER_ERROR,
|
||||||
|
error: 'Internal server error',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return response
|
||||||
|
}
|
||||||
|
|
||||||
|
export const updateItem = async (
|
||||||
|
_id: IItem['_id'],
|
||||||
|
item: IUpdateItemInput,
|
||||||
|
loggedUser: IUser,
|
||||||
|
files?: IUploadFile,
|
||||||
|
): ControllerResponseType<ItemReponseType> => {
|
||||||
|
let response: ResponseType<ItemReponseType> = {
|
||||||
|
status: HttpStatus.OK,
|
||||||
|
}
|
||||||
|
|
||||||
|
const oldItem = await ItemModel.findById(_id).exec()
|
||||||
|
|
||||||
|
if (oldItem === null) {
|
||||||
|
return {
|
||||||
|
status: HttpStatus.NOT_FOUND,
|
||||||
|
error: 'Item not found',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (item.purchaseDate) {
|
||||||
|
if (!isValid(new Date(item.purchaseDate))) {
|
||||||
|
return {
|
||||||
|
status: HttpStatus.BAD_REQUEST,
|
||||||
|
error: 'Invalid date',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (item.price && item.price < 0) {
|
||||||
|
return {
|
||||||
|
status: HttpStatus.BAD_REQUEST,
|
||||||
|
error: 'Price cannot be negative',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (loggedUser._id !== oldItem.user.toString() && loggedUser.permission < 10) {
|
||||||
|
return {
|
||||||
|
status: HttpStatus.FORBIDDEN,
|
||||||
|
error: 'Unauthorized',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let invoice: IItem['invoice']
|
||||||
|
let image: IItem['image']
|
||||||
|
let categories: IItem['categories']
|
||||||
|
let $unset: any = {}
|
||||||
|
|
||||||
|
if (files) {
|
||||||
|
if (files.invoice) {
|
||||||
|
if (oldItem.invoice) {
|
||||||
|
await deleteFile(oldItem.invoice, loggedUser)
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await uploadFile(files.invoice[0], loggedUser)
|
||||||
|
if (result.error) {
|
||||||
|
return {
|
||||||
|
status: HttpStatus.BAD_REQUEST,
|
||||||
|
error: result.error,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
invoice = result?.data?._id
|
||||||
|
}
|
||||||
|
|
||||||
|
if (files.image) {
|
||||||
|
try {
|
||||||
|
if (oldItem.image) {
|
||||||
|
await deleteFile(oldItem.image, loggedUser)
|
||||||
|
}
|
||||||
|
const imageCompressed = files.image[0]
|
||||||
|
imageCompressed.buffer = await imageToWebP(await resizeImage(imageCompressed.buffer, 350, 350))
|
||||||
|
imageCompressed.mimetype = 'image/webp'
|
||||||
|
imageCompressed.originalname = imageCompressed.originalname.replace(/\.[^/.]+$/, '.webp')
|
||||||
|
const result = await uploadFile(imageCompressed, loggedUser)
|
||||||
|
if (result.error) {
|
||||||
|
return {
|
||||||
|
status: HttpStatus.BAD_REQUEST,
|
||||||
|
error: result.error,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
image = result?.data?._id
|
||||||
|
} catch (error) {
|
||||||
|
return {
|
||||||
|
status: HttpStatus.INTERNAL_SERVER_ERROR,
|
||||||
|
error: 'Internal server error',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (oldItem.invoice && item?.invoice === 'null') {
|
||||||
|
$unset.invoice = ''
|
||||||
|
await deleteFile(oldItem.invoice, loggedUser)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (oldItem.image && item?.image === 'null') {
|
||||||
|
$unset.image = ''
|
||||||
|
await deleteFile(oldItem.image, loggedUser)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (item.categories) {
|
||||||
|
categories = JSON.parse(item.categories)
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const updatedItem = await ItemModel.findByIdAndUpdate<ItemReponseType>(
|
||||||
|
_id,
|
||||||
|
{
|
||||||
|
$set: {
|
||||||
|
...item,
|
||||||
|
categories,
|
||||||
|
invoice,
|
||||||
|
image,
|
||||||
|
purchaseDate: item.purchaseDate ? new Date(item.purchaseDate) : undefined,
|
||||||
|
},
|
||||||
|
$unset,
|
||||||
|
},
|
||||||
|
{ new: true },
|
||||||
|
).exec()
|
||||||
|
|
||||||
|
if (updatedItem === null) {
|
||||||
|
return {
|
||||||
|
status: HttpStatus.NOT_FOUND,
|
||||||
|
error: 'Item not found',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
response.data = updatedItem
|
||||||
|
} catch (e) {
|
||||||
|
return {
|
||||||
|
status: HttpStatus.INTERNAL_SERVER_ERROR,
|
||||||
|
error: 'Internal server error',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return response
|
||||||
|
}
|
||||||
|
|
||||||
|
export const deleteItem = async (_id: IItem['_id'], loggedUser: IUser) => {
|
||||||
|
let response: ResponseType = {
|
||||||
|
status: HttpStatus.OK,
|
||||||
|
}
|
||||||
|
|
||||||
|
const oldItem = await ItemModel.findById<IItem | null>(_id).exec()
|
||||||
|
|
||||||
|
if (oldItem === null) {
|
||||||
|
return {
|
||||||
|
status: HttpStatus.NOT_FOUND,
|
||||||
|
error: 'Item not found',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (loggedUser._id !== oldItem.user.toString() && loggedUser.permission < 10) {
|
||||||
|
return {
|
||||||
|
status: HttpStatus.FORBIDDEN,
|
||||||
|
error: 'Unauthorized',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const deletedItem = await ItemModel.findByIdAndDelete<IItem>(_id).exec()
|
||||||
|
if (deletedItem?.invoice) {
|
||||||
|
await FileModel.findByIdAndDelete<IFile>(deletedItem.invoice.toString()).exec()
|
||||||
|
}
|
||||||
|
if (deletedItem?.image) {
|
||||||
|
await FileModel.findByIdAndDelete<IFile>(deletedItem.image.toString()).exec()
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
return {
|
||||||
|
status: HttpStatus.INTERNAL_SERVER_ERROR,
|
||||||
|
error: 'Internal server error',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return response
|
||||||
|
}
|
293
src/controllers/room.ts
Normal file
293
src/controllers/room.ts
Normal file
@ -0,0 +1,293 @@
|
|||||||
|
import { FileModel, ItemModel, RoomModel } from '@models'
|
||||||
|
import {
|
||||||
|
ControllerResponseType,
|
||||||
|
HttpStatus,
|
||||||
|
IFile,
|
||||||
|
IItem,
|
||||||
|
IRoom,
|
||||||
|
IUpdateItemInput,
|
||||||
|
IUser,
|
||||||
|
ItemReponseType,
|
||||||
|
PopulatedRoomResponseType,
|
||||||
|
ResponseType,
|
||||||
|
RoomObjectType,
|
||||||
|
RoomResponseType,
|
||||||
|
RoomStatsResponseType,
|
||||||
|
} from '@types'
|
||||||
|
|
||||||
|
import { sanitizeFilter } from 'mongoose'
|
||||||
|
|
||||||
|
export const createRoom = async (name: string, loggedUser: IUser): ControllerResponseType<RoomResponseType> => {
|
||||||
|
let response: ResponseType<RoomResponseType> = {
|
||||||
|
status: HttpStatus.OK,
|
||||||
|
}
|
||||||
|
|
||||||
|
if (name === undefined || name.length <= 0) {
|
||||||
|
return {
|
||||||
|
status: HttpStatus.BAD_REQUEST,
|
||||||
|
error: 'Room name is missing',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const room = new RoomModel({
|
||||||
|
name,
|
||||||
|
user: loggedUser._id,
|
||||||
|
})
|
||||||
|
|
||||||
|
try {
|
||||||
|
response.data = await room.save()
|
||||||
|
} catch (e) {
|
||||||
|
return {
|
||||||
|
status: HttpStatus.INTERNAL_SERVER_ERROR,
|
||||||
|
error: 'Internal server error',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return response
|
||||||
|
}
|
||||||
|
|
||||||
|
export const getRooms = async (loggedUser: IUser): ControllerResponseType<RoomResponseType[]> => {
|
||||||
|
let response: ResponseType<RoomResponseType[]> = {
|
||||||
|
status: HttpStatus.OK,
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
response.data = await RoomModel.find<RoomResponseType>(sanitizeFilter({ user: loggedUser._id })).exec()
|
||||||
|
} catch (e) {
|
||||||
|
return {
|
||||||
|
status: HttpStatus.INTERNAL_SERVER_ERROR,
|
||||||
|
error: 'Internal server error',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return response
|
||||||
|
}
|
||||||
|
|
||||||
|
export const getRoom = async (
|
||||||
|
_id: IRoom['_id'],
|
||||||
|
loggedUser: IUser,
|
||||||
|
): ControllerResponseType<PopulatedRoomResponseType> => {
|
||||||
|
let response: ResponseType<PopulatedRoomResponseType> = {
|
||||||
|
status: HttpStatus.OK,
|
||||||
|
}
|
||||||
|
|
||||||
|
const room = await RoomModel.findById(_id).exec()
|
||||||
|
|
||||||
|
const items = await ItemModel.find(sanitizeFilter({ room: _id }))
|
||||||
|
.populate('categories')
|
||||||
|
.populate({ path: 'image', select: 'name' })
|
||||||
|
.populate({ path: 'invoice', select: 'name' })
|
||||||
|
.exec()
|
||||||
|
|
||||||
|
if (room === null) {
|
||||||
|
return {
|
||||||
|
status: HttpStatus.NOT_FOUND,
|
||||||
|
error: 'Room not found',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (loggedUser._id !== room.user.toString() && loggedUser.permission < 10) {
|
||||||
|
return {
|
||||||
|
status: HttpStatus.FORBIDDEN,
|
||||||
|
error: 'You are not allowed to access this room',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
response.data = { ...room.toObject(), items: items as ItemReponseType[] }
|
||||||
|
|
||||||
|
return response
|
||||||
|
}
|
||||||
|
|
||||||
|
export const updateRoom = async (
|
||||||
|
_id: IRoom['_id'],
|
||||||
|
room: IUpdateItemInput,
|
||||||
|
loggedUser: IUser,
|
||||||
|
): ControllerResponseType<RoomResponseType> => {
|
||||||
|
let response: ResponseType<RoomResponseType> = {
|
||||||
|
status: HttpStatus.OK,
|
||||||
|
}
|
||||||
|
|
||||||
|
const oldRoom = await RoomModel.findById<IRoom | null>(_id).exec()
|
||||||
|
|
||||||
|
if (oldRoom === null) {
|
||||||
|
return {
|
||||||
|
status: HttpStatus.NOT_FOUND,
|
||||||
|
error: 'Room not found',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (loggedUser._id !== oldRoom.user.toString() && loggedUser.permission < 10) {
|
||||||
|
return {
|
||||||
|
status: HttpStatus.FORBIDDEN,
|
||||||
|
error: 'You are not allowed to update this room',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const updatedRoom = await RoomModel.findByIdAndUpdate<RoomResponseType>(_id, { $set: room }, { new: true }).exec()
|
||||||
|
|
||||||
|
if (updatedRoom === null) {
|
||||||
|
return {
|
||||||
|
status: HttpStatus.INTERNAL_SERVER_ERROR,
|
||||||
|
error: 'Internal server error',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
response.data = updatedRoom
|
||||||
|
} catch (e) {
|
||||||
|
return {
|
||||||
|
status: HttpStatus.INTERNAL_SERVER_ERROR,
|
||||||
|
error: 'Internal server error',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return response
|
||||||
|
}
|
||||||
|
|
||||||
|
export const deleteRoom = async (_id: IRoom['_id'], loggedUser: IUser): ControllerResponseType<RoomResponseType> => {
|
||||||
|
let response: ResponseType<RoomResponseType> = {
|
||||||
|
status: HttpStatus.OK,
|
||||||
|
}
|
||||||
|
|
||||||
|
const oldRoom = await RoomModel.findById(_id).exec()
|
||||||
|
|
||||||
|
if (oldRoom === null) {
|
||||||
|
return {
|
||||||
|
status: HttpStatus.NOT_FOUND,
|
||||||
|
error: 'Room not found',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (loggedUser._id !== oldRoom.user.toString() && loggedUser.permission < 10) {
|
||||||
|
return {
|
||||||
|
status: HttpStatus.FORBIDDEN,
|
||||||
|
error: 'You are not allowed to delete this room',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await RoomModel.findByIdAndDelete(_id).exec()
|
||||||
|
|
||||||
|
let files: IFile['_id'][] = []
|
||||||
|
|
||||||
|
const items = await ItemModel.find({ room: _id }).exec()
|
||||||
|
|
||||||
|
items.forEach((item: IItem) => {
|
||||||
|
if (item?.invoice) {
|
||||||
|
files.push(item.invoice)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (item?.image) {
|
||||||
|
files.push(item.image)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
await ItemModel.deleteMany(sanitizeFilter({ room: _id })).exec()
|
||||||
|
await FileModel.deleteMany({ _id: { $in: files } }).exec()
|
||||||
|
} catch (e) {
|
||||||
|
return {
|
||||||
|
status: HttpStatus.INTERNAL_SERVER_ERROR,
|
||||||
|
error: 'Internal server error',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return response
|
||||||
|
}
|
||||||
|
|
||||||
|
export const getRoomStats = async (loggedUser: IUser): ControllerResponseType<RoomStatsResponseType> => {
|
||||||
|
let response: ResponseType<RoomStatsResponseType> = {
|
||||||
|
status: HttpStatus.OK,
|
||||||
|
}
|
||||||
|
|
||||||
|
const rooms = [...(await RoomModel.find<IRoom>(sanitizeFilter({ user: loggedUser })).exec())]
|
||||||
|
const items = [...(await ItemModel.find<IItem>(sanitizeFilter({ user: loggedUser })).exec())]
|
||||||
|
|
||||||
|
let rooms_object: RoomObjectType = {}
|
||||||
|
rooms.forEach((room: IRoom) => {
|
||||||
|
const room_items = items.filter((item) => item.room.toString() === room._id.toString())
|
||||||
|
rooms_object[room.name] = {
|
||||||
|
_id: room._id.toString(),
|
||||||
|
name: room.name,
|
||||||
|
items_count: room_items.length,
|
||||||
|
room_price: Math.round(room_items.reduce((sum, item) => sum + (item.price || 0), 0) * 100) / 100,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
const rooms_count = rooms.length
|
||||||
|
const items_count = items.length
|
||||||
|
|
||||||
|
const total_price = Math.round(items.reduce((sum, item) => sum + (item.price || 0), 0) * 100) / 100
|
||||||
|
|
||||||
|
const average_price = Math.round((items_count > 0 ? total_price / items_count : 0) * 100) / 100
|
||||||
|
|
||||||
|
const [most_item_room, most_expensive_room] = Object.keys(rooms_object).reduce(
|
||||||
|
([tmp_most_item_room, tmp_most_expensive_room], roomId: IRoom['_id']) => {
|
||||||
|
const room = rooms_object[roomId]
|
||||||
|
|
||||||
|
if (tmp_most_item_room.count < room.items_count) {
|
||||||
|
tmp_most_item_room = {
|
||||||
|
name: room.name,
|
||||||
|
count: room.items_count,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (tmp_most_expensive_room.count < room.room_price) {
|
||||||
|
tmp_most_expensive_room = {
|
||||||
|
name: room.name,
|
||||||
|
count: room.room_price,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return [tmp_most_item_room, tmp_most_expensive_room]
|
||||||
|
},
|
||||||
|
[
|
||||||
|
{ name: '', count: 0 },
|
||||||
|
{ name: '', count: 0 },
|
||||||
|
],
|
||||||
|
)
|
||||||
|
|
||||||
|
const first_year = new Date().getFullYear()
|
||||||
|
|
||||||
|
const [min_year, max_year] = items.reduce(
|
||||||
|
([min, max], item: IItem) => {
|
||||||
|
if (item.purchaseDate) {
|
||||||
|
const currentYear = item.purchaseDate.getFullYear()
|
||||||
|
|
||||||
|
if (min > currentYear) {
|
||||||
|
min = currentYear
|
||||||
|
}
|
||||||
|
if (max < currentYear) {
|
||||||
|
max = currentYear
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return [min, max]
|
||||||
|
},
|
||||||
|
[first_year, first_year],
|
||||||
|
)
|
||||||
|
|
||||||
|
let tmp_years: any = {}
|
||||||
|
for (let i = min_year; i <= max_year; i++) {
|
||||||
|
tmp_years[i] = items
|
||||||
|
.filter((item: IItem) => i === item.purchaseDate?.getFullYear())
|
||||||
|
.reduce((sum: number, item: IItem) => {
|
||||||
|
const price = item.price ? item.price : 0
|
||||||
|
return sum + price
|
||||||
|
}, 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
response.data = {
|
||||||
|
global: {
|
||||||
|
rooms_count,
|
||||||
|
items_count,
|
||||||
|
total_price,
|
||||||
|
average_price,
|
||||||
|
most_item_room,
|
||||||
|
most_expensive_room,
|
||||||
|
},
|
||||||
|
rooms: rooms_object,
|
||||||
|
years: tmp_years,
|
||||||
|
}
|
||||||
|
|
||||||
|
return response
|
||||||
|
}
|
275
src/controllers/user.ts
Normal file
275
src/controllers/user.ts
Normal file
@ -0,0 +1,275 @@
|
|||||||
|
import { confirmationValidators, passwordValidators } from '@helpers'
|
||||||
|
import { UserModel } from '@models'
|
||||||
|
import {
|
||||||
|
ControllerResponseType,
|
||||||
|
HttpStatus,
|
||||||
|
ICreateUserInput,
|
||||||
|
IGetUserInput,
|
||||||
|
IUpdateUserInput,
|
||||||
|
IUser,
|
||||||
|
ResponseType,
|
||||||
|
UserResponseType,
|
||||||
|
} from '@types'
|
||||||
|
|
||||||
|
import bcrypt from 'bcryptjs'
|
||||||
|
import jwt from 'jsonwebtoken'
|
||||||
|
import { sanitizeFilter } from 'mongoose'
|
||||||
|
|
||||||
|
export const getUsers = async (query: IGetUserInput, loggedUser: IUser): ControllerResponseType<UserResponseType[]> => {
|
||||||
|
let response: ResponseType<UserResponseType[]> = {
|
||||||
|
status: HttpStatus.OK,
|
||||||
|
}
|
||||||
|
|
||||||
|
if (loggedUser.permission < 10) {
|
||||||
|
query._id = loggedUser._id
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const tmp = await UserModel.find(sanitizeFilter(query)).exec()
|
||||||
|
|
||||||
|
if (tmp !== null) {
|
||||||
|
const users = tmp.map((user) => {
|
||||||
|
const { password, ...rest } = user.toObject()
|
||||||
|
return rest
|
||||||
|
})
|
||||||
|
|
||||||
|
response.data = users as UserResponseType[]
|
||||||
|
} else {
|
||||||
|
return {
|
||||||
|
status: HttpStatus.NOT_FOUND,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
return {
|
||||||
|
status: HttpStatus.INTERNAL_SERVER_ERROR,
|
||||||
|
error: 'Internal server error',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return response
|
||||||
|
}
|
||||||
|
|
||||||
|
export const createUser = async (
|
||||||
|
userData: ICreateUserInput,
|
||||||
|
): ControllerResponseType<{ user: UserResponseType; token: string }> => {
|
||||||
|
let response: ResponseType<{ user: UserResponseType; token: string }> = {
|
||||||
|
status: HttpStatus.OK,
|
||||||
|
}
|
||||||
|
|
||||||
|
const user = new UserModel({
|
||||||
|
username: userData.username,
|
||||||
|
password: userData.password,
|
||||||
|
permission: 1,
|
||||||
|
})
|
||||||
|
|
||||||
|
//Validation des données
|
||||||
|
const validations = [
|
||||||
|
{
|
||||||
|
validator: userData.username !== undefined && userData.password !== undefined,
|
||||||
|
message: 'Some data is missing',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
validator: userData.username?.length >= 3,
|
||||||
|
message: 'Username must be at least 3 characters long',
|
||||||
|
},
|
||||||
|
...passwordValidators(userData.password),
|
||||||
|
...confirmationValidators(userData.password, userData.confirmation),
|
||||||
|
]
|
||||||
|
// On vérifie chacun des tests
|
||||||
|
for (const validation of validations) {
|
||||||
|
if (!validation.validator) {
|
||||||
|
return {
|
||||||
|
status: HttpStatus.BAD_REQUEST,
|
||||||
|
error: validation.message,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//Hash du mot de passe
|
||||||
|
if (!response.error) {
|
||||||
|
const salt = bcrypt.genSaltSync(10)
|
||||||
|
user.password = bcrypt.hashSync(user.password, salt)
|
||||||
|
}
|
||||||
|
|
||||||
|
//Insertion dans la base de donnée
|
||||||
|
try {
|
||||||
|
const tmp = await user.save()
|
||||||
|
|
||||||
|
const {
|
||||||
|
password, // eslint-disable-line no-unused-vars
|
||||||
|
...tmpUser
|
||||||
|
} = tmp.toObject()
|
||||||
|
|
||||||
|
const token = jwt.sign(tmpUser, process.env.JWT_SECRET || '')
|
||||||
|
|
||||||
|
response.data = { user: tmpUser as UserResponseType, token }
|
||||||
|
} catch (error) {
|
||||||
|
return {
|
||||||
|
status: HttpStatus.INTERNAL_SERVER_ERROR,
|
||||||
|
error: 'Internal server error',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return response
|
||||||
|
}
|
||||||
|
|
||||||
|
export const updateUser = async (
|
||||||
|
_id: string,
|
||||||
|
userData: IUpdateUserInput,
|
||||||
|
loggedUser: IUser,
|
||||||
|
): ControllerResponseType<{ user: UserResponseType; token: string }> => {
|
||||||
|
let response: ResponseType<{ user: UserResponseType; token: string }> = {
|
||||||
|
status: HttpStatus.OK,
|
||||||
|
}
|
||||||
|
|
||||||
|
let hashPassword
|
||||||
|
const { old_password, password: _password, confirmation, permission, ...newUserFilter } = userData
|
||||||
|
let newUser: IUpdateUserInput = newUserFilter
|
||||||
|
|
||||||
|
if (loggedUser.permission < 10) {
|
||||||
|
newUser.permission = userData.permission
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verification des authorisation
|
||||||
|
if (loggedUser._id !== _id && loggedUser.permission < 10) {
|
||||||
|
console.log('ici', loggedUser._id, _id, loggedUser.permission)
|
||||||
|
return {
|
||||||
|
status: HttpStatus.FORBIDDEN,
|
||||||
|
error: 'You are not allowed to do this',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let oldUser = await UserModel.findOne<IUser | null>({ _id }).exec()
|
||||||
|
if (oldUser === null) {
|
||||||
|
return {
|
||||||
|
status: HttpStatus.NOT_FOUND,
|
||||||
|
error: 'User not found',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
oldUser = oldUser.toObject()
|
||||||
|
|
||||||
|
if (userData.password && !userData.confirmation) {
|
||||||
|
return {
|
||||||
|
status: HttpStatus.BAD_REQUEST,
|
||||||
|
error: 'Password confirmation is required',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (userData.password && userData.password !== userData.confirmation) {
|
||||||
|
return {
|
||||||
|
status: HttpStatus.BAD_REQUEST,
|
||||||
|
error: 'Password and confirmation must be the same',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let validations = []
|
||||||
|
|
||||||
|
if (userData.username) {
|
||||||
|
validations.push({
|
||||||
|
validator: userData?.username?.length >= 3,
|
||||||
|
message: 'Username must be at least 3 characters long',
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
//Hash du mot de passe
|
||||||
|
if (userData.password) {
|
||||||
|
if (!userData.old_password) {
|
||||||
|
return {
|
||||||
|
status: HttpStatus.BAD_REQUEST,
|
||||||
|
error: 'Old password is required',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const oldPassword = userData.old_password || ''
|
||||||
|
|
||||||
|
validations.push(
|
||||||
|
...passwordValidators(userData.password),
|
||||||
|
...confirmationValidators(userData.password, userData.confirmation || ''),
|
||||||
|
)
|
||||||
|
|
||||||
|
const { password: oldPasswordDb } = oldUser
|
||||||
|
|
||||||
|
const validPass = await bcrypt.compare(oldPassword, oldPasswordDb)
|
||||||
|
if (!validPass) {
|
||||||
|
return {
|
||||||
|
status: HttpStatus.BAD_REQUEST,
|
||||||
|
error: 'Old password is incorrect',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const salt = await bcrypt.genSalt(10)
|
||||||
|
hashPassword = await bcrypt.hash(userData.password, salt)
|
||||||
|
newUser = { ...newUser, password: hashPassword }
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const validation of validations) {
|
||||||
|
if (!validation.validator) {
|
||||||
|
return {
|
||||||
|
status: HttpStatus.BAD_REQUEST,
|
||||||
|
error: validation.message,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let tmpUser
|
||||||
|
|
||||||
|
//Insertion dans la base de donnée
|
||||||
|
try {
|
||||||
|
const tmp = await UserModel.findByIdAndUpdate<IUser | null>(_id, { $set: newUser }, { new: true }).exec()
|
||||||
|
|
||||||
|
if (tmp === null) {
|
||||||
|
return {
|
||||||
|
status: HttpStatus.NOT_FOUND,
|
||||||
|
error: 'User not found',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const { password: _deleted_password, ...temp } = tmp.toObject()
|
||||||
|
tmpUser = temp
|
||||||
|
} catch (error) {
|
||||||
|
return {
|
||||||
|
status: HttpStatus.INTERNAL_SERVER_ERROR,
|
||||||
|
error: 'Internal server error',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const { password, ...tokenContent } = tmpUser
|
||||||
|
|
||||||
|
const token = jwt.sign(tokenContent, process.env.JWT_SECRET || '')
|
||||||
|
response.data = { user: tmpUser as UserResponseType, token }
|
||||||
|
|
||||||
|
return response
|
||||||
|
}
|
||||||
|
|
||||||
|
export const deleteUser = async (_id: IUser['_id'], loggedUser: IUser): ControllerResponseType<UserResponseType> => {
|
||||||
|
let response: ResponseType<UserResponseType> = {
|
||||||
|
status: HttpStatus.OK,
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const userData = await UserModel.findById(_id).exec()
|
||||||
|
|
||||||
|
if (userData === null) {
|
||||||
|
// Check authorization
|
||||||
|
return {
|
||||||
|
status: HttpStatus.NOT_FOUND,
|
||||||
|
error: 'User not found',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (loggedUser.permission < 10 && loggedUser._id !== _id) {
|
||||||
|
return {
|
||||||
|
status: HttpStatus.FORBIDDEN,
|
||||||
|
error: 'You are not allowed to do this',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await UserModel.deleteOne(sanitizeFilter({ _id })).exec()
|
||||||
|
} catch (error) {
|
||||||
|
return {
|
||||||
|
status: HttpStatus.INTERNAL_SERVER_ERROR,
|
||||||
|
error: 'Internal server error',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return response
|
||||||
|
}
|
25
src/helpers/authenticated.ts
Normal file
25
src/helpers/authenticated.ts
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
import { NextFunction, Response } from 'express'
|
||||||
|
|
||||||
|
import { AuthenticatedRequest, HttpStatus, IUser } from '@types'
|
||||||
|
|
||||||
|
import jwt from 'jsonwebtoken'
|
||||||
|
|
||||||
|
export const authenticated = async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
|
||||||
|
let token = req.cookies['auth-token']
|
||||||
|
|
||||||
|
if (!token) {
|
||||||
|
token = req.headers['bearer']
|
||||||
|
|
||||||
|
if (token === undefined) {
|
||||||
|
return res.status(HttpStatus.UNAUTHORIZED).send('Unauthorized')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
req.user = jwt.verify(token, process.env.JWT_SECRET || '') as IUser
|
||||||
|
|
||||||
|
next()
|
||||||
|
} catch (err) {
|
||||||
|
return res.status(HttpStatus.UNAUTHORIZED).send('Unauthorized')
|
||||||
|
}
|
||||||
|
}
|
15
src/helpers/databaseConnection.ts
Normal file
15
src/helpers/databaseConnection.ts
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
import mongoose from 'mongoose'
|
||||||
|
|
||||||
|
export const databaseConnection = async () => {
|
||||||
|
const mongoUrl: string = decodeURIComponent(process.env.MONGO_URL || '')
|
||||||
|
|
||||||
|
if (mongoUrl === '') {
|
||||||
|
throw new Error('MONGO_URL has not been set')
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await mongoose.connect(mongoUrl)
|
||||||
|
} catch (err: any) {
|
||||||
|
console.error(err.message)
|
||||||
|
}
|
||||||
|
}
|
33
src/helpers/getCorsOptions.ts
Normal file
33
src/helpers/getCorsOptions.ts
Normal file
@ -0,0 +1,33 @@
|
|||||||
|
import { CorsOptions } from 'cors'
|
||||||
|
import { networkInterfaces } from 'os'
|
||||||
|
|
||||||
|
export const getCorsOptions = (): CorsOptions => {
|
||||||
|
if (process.env.NODE_ENV === 'development') {
|
||||||
|
let whitelist = ['http://localhost:3000']
|
||||||
|
|
||||||
|
const nets = networkInterfaces()
|
||||||
|
|
||||||
|
whitelist = Object.keys(nets).reduce((tab, name) => {
|
||||||
|
// @ts-ignore
|
||||||
|
for (const net of nets[name]) {
|
||||||
|
if (net && net?.family === 'IPv4') {
|
||||||
|
tab.push(`http://${net.address}:3000`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return tab
|
||||||
|
}, whitelist)
|
||||||
|
|
||||||
|
return {
|
||||||
|
origin: function (origin: any, callback: (arg0: Error | null, arg1: boolean) => void) {
|
||||||
|
if (!origin || whitelist.indexOf(origin) !== -1) {
|
||||||
|
callback(null, true)
|
||||||
|
} else {
|
||||||
|
callback(new Error('Not allowed by CORS'), false)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
credentials: true,
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return {}
|
||||||
|
}
|
||||||
|
}
|
9
src/helpers/image.ts
Normal file
9
src/helpers/image.ts
Normal file
@ -0,0 +1,9 @@
|
|||||||
|
import sharp from 'sharp'
|
||||||
|
|
||||||
|
export const imageToWebP = async (buffer: Buffer) => {
|
||||||
|
return await sharp(buffer).webp().toBuffer()
|
||||||
|
}
|
||||||
|
|
||||||
|
export const resizeImage = async (buffer: Buffer, width: number, height: number) => {
|
||||||
|
return await sharp(buffer).resize({ width, height, fit: 'inside' }).toBuffer()
|
||||||
|
}
|
5
src/helpers/index.ts
Normal file
5
src/helpers/index.ts
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
export * from './authenticated'
|
||||||
|
export * from './databaseConnection'
|
||||||
|
export * from './getCorsOptions'
|
||||||
|
export * from './image'
|
||||||
|
export * from './validators'
|
56
src/helpers/validators.ts
Normal file
56
src/helpers/validators.ts
Normal file
@ -0,0 +1,56 @@
|
|||||||
|
import { HttpStatus, ICreateFileInput, ResponseType } from '@types'
|
||||||
|
|
||||||
|
export const passwordValidators = (password: string) => [
|
||||||
|
{
|
||||||
|
validator: password !== undefined,
|
||||||
|
message: 'Password is required',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
validator: password?.length >= 8,
|
||||||
|
message: 'Password must be at least 8 characters long',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
validator: /[a-z]/g.test(password),
|
||||||
|
message: 'Password must contain at least one lowercase letter',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
validator: /[A-Z]/g.test(password),
|
||||||
|
message: 'Password must contain at least one uppercase letter',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
validator: /[0-9]/g.test(password),
|
||||||
|
message: 'Password must contain at least one number',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
validator: /[!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?]/g.test(password),
|
||||||
|
message: 'Password must contain at least one special character',
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
export const confirmationValidators = (password: string, confirmation: string) => [
|
||||||
|
{
|
||||||
|
validator: confirmation !== undefined,
|
||||||
|
message: 'Confirmation is required',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
validator: confirmation === password,
|
||||||
|
message: 'Password and confirmation are not the same',
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
export const invoiceFileFilter = (file: ICreateFileInput) => {
|
||||||
|
let response: ResponseType = {
|
||||||
|
status: HttpStatus.OK,
|
||||||
|
}
|
||||||
|
|
||||||
|
const authorizedFileType = ['application/pdf', 'image/png', 'image/jpeg', 'image/webp']
|
||||||
|
|
||||||
|
if (!authorizedFileType.includes(file.mimetype)) {
|
||||||
|
return {
|
||||||
|
status: HttpStatus.BAD_REQUEST,
|
||||||
|
error: 'Invalid file type',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return response
|
||||||
|
}
|
58
src/index.ts
Normal file
58
src/index.ts
Normal file
@ -0,0 +1,58 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
import { databaseConnection } from '@helpers'
|
||||||
|
|
||||||
|
import app from './app'
|
||||||
|
|
||||||
|
const normalizePort = (port: number) => {
|
||||||
|
if (port >= 0) {
|
||||||
|
// port number
|
||||||
|
return port
|
||||||
|
}
|
||||||
|
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
const onError = (error: { syscall: string; code: string }) => {
|
||||||
|
if (error.syscall !== 'listen') {
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
|
||||||
|
const bind = 'Port ' + port
|
||||||
|
|
||||||
|
// handle specific listen errors with friendly messages
|
||||||
|
switch (error.code) {
|
||||||
|
case 'EACCES':
|
||||||
|
console.error(`${bind} requires elevated privileges`)
|
||||||
|
process.exit(1)
|
||||||
|
break
|
||||||
|
case 'EADDRINUSE':
|
||||||
|
console.error(`${bind} is already in use`)
|
||||||
|
process.exit(1)
|
||||||
|
break
|
||||||
|
default:
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const onListening = () => {
|
||||||
|
let addr = server.address()
|
||||||
|
let bind = typeof addr === 'string' ? 'pipe ' + addr : 'port ' + addr.port
|
||||||
|
console.info('[starting] Listening on ' + bind)
|
||||||
|
}
|
||||||
|
|
||||||
|
const port = normalizePort(parseInt(process.env.PORT || '2011'))
|
||||||
|
app.set('port', port)
|
||||||
|
|
||||||
|
const server = require('http').createServer(app)
|
||||||
|
|
||||||
|
server.listen(port)
|
||||||
|
server.on('error', onError)
|
||||||
|
server.on('listening', onListening)
|
||||||
|
|
||||||
|
databaseConnection()
|
||||||
|
.then(() => {
|
||||||
|
console.info('[starting] Connected to database')
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
|
console.info('[starting] Could not connect to database')
|
||||||
|
})
|
19
src/models/category.ts
Normal file
19
src/models/category.ts
Normal file
@ -0,0 +1,19 @@
|
|||||||
|
import { ICategory } from '@types'
|
||||||
|
|
||||||
|
import mongoose, { Schema } from 'mongoose'
|
||||||
|
|
||||||
|
const CategorySchema: Schema = new mongoose.Schema({
|
||||||
|
en: {
|
||||||
|
type: String,
|
||||||
|
required: true,
|
||||||
|
unique: true,
|
||||||
|
},
|
||||||
|
fr: {
|
||||||
|
type: String,
|
||||||
|
required: true,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
CategorySchema.set('timestamps', true)
|
||||||
|
|
||||||
|
export const CategoryModel = mongoose.model<ICategory>('Category', CategorySchema)
|
27
src/models/file.ts
Normal file
27
src/models/file.ts
Normal file
@ -0,0 +1,27 @@
|
|||||||
|
import { IFile } from '@types'
|
||||||
|
|
||||||
|
import mongoose, { Schema } from 'mongoose'
|
||||||
|
|
||||||
|
const FileSchema: Schema = new Schema({
|
||||||
|
name: {
|
||||||
|
type: String,
|
||||||
|
required: true,
|
||||||
|
},
|
||||||
|
mimetype: {
|
||||||
|
type: String,
|
||||||
|
required: true,
|
||||||
|
},
|
||||||
|
data: {
|
||||||
|
type: String,
|
||||||
|
required: true,
|
||||||
|
},
|
||||||
|
user: {
|
||||||
|
type: Schema.Types.ObjectId,
|
||||||
|
ref: 'User',
|
||||||
|
required: true,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
FileSchema.set('timestamps', true)
|
||||||
|
|
||||||
|
export const FileModel = mongoose.model<IFile>('File', FileSchema)
|
5
src/models/index.ts
Normal file
5
src/models/index.ts
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
export * from './user'
|
||||||
|
export * from './room'
|
||||||
|
export * from './item'
|
||||||
|
export * from './file'
|
||||||
|
export * from './category'
|
51
src/models/item.ts
Normal file
51
src/models/item.ts
Normal file
@ -0,0 +1,51 @@
|
|||||||
|
import { IItem } from '@types'
|
||||||
|
|
||||||
|
import mongoose, { Schema } from 'mongoose'
|
||||||
|
|
||||||
|
const ItemSchema: Schema = new Schema({
|
||||||
|
brand: {
|
||||||
|
type: String,
|
||||||
|
required: true,
|
||||||
|
},
|
||||||
|
model: {
|
||||||
|
type: String,
|
||||||
|
},
|
||||||
|
user: {
|
||||||
|
type: Schema.Types.ObjectId,
|
||||||
|
ref: 'User',
|
||||||
|
required: true,
|
||||||
|
},
|
||||||
|
room: {
|
||||||
|
type: Schema.Types.ObjectId,
|
||||||
|
ref: 'Room',
|
||||||
|
required: true,
|
||||||
|
},
|
||||||
|
price: {
|
||||||
|
type: Number,
|
||||||
|
},
|
||||||
|
purchaseDate: {
|
||||||
|
type: Schema.Types.Date,
|
||||||
|
},
|
||||||
|
description: {
|
||||||
|
type: String,
|
||||||
|
},
|
||||||
|
link: {
|
||||||
|
type: String,
|
||||||
|
},
|
||||||
|
categories: {
|
||||||
|
type: [Schema.Types.ObjectId],
|
||||||
|
ref: 'Category',
|
||||||
|
},
|
||||||
|
image: {
|
||||||
|
type: Schema.Types.ObjectId,
|
||||||
|
ref: 'File',
|
||||||
|
},
|
||||||
|
invoice: {
|
||||||
|
type: Schema.Types.ObjectId,
|
||||||
|
ref: 'File',
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
ItemSchema.set('timestamps', true)
|
||||||
|
|
||||||
|
export const ItemModel = mongoose.model<IItem>('Item', ItemSchema)
|
12
src/models/room.ts
Normal file
12
src/models/room.ts
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
import { IRoom } from '@types'
|
||||||
|
|
||||||
|
import mongoose, { Schema } from 'mongoose'
|
||||||
|
|
||||||
|
const RoomSchema: Schema = new Schema({
|
||||||
|
name: { type: String, required: true },
|
||||||
|
user: { type: Schema.Types.ObjectId, ref: 'User', required: true },
|
||||||
|
})
|
||||||
|
|
||||||
|
RoomSchema.set('timestamps', true)
|
||||||
|
|
||||||
|
export const RoomModel = mongoose.model<IRoom>('Room', RoomSchema)
|
13
src/models/user.ts
Normal file
13
src/models/user.ts
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
import { IUser } from '@types'
|
||||||
|
|
||||||
|
import mongoose, { Schema } from 'mongoose'
|
||||||
|
|
||||||
|
const UserSchema: Schema = new Schema({
|
||||||
|
username: { type: String, required: true, unique: true },
|
||||||
|
password: { type: String, required: true },
|
||||||
|
permission: { type: Number, required: true },
|
||||||
|
})
|
||||||
|
|
||||||
|
UserSchema.set('timestamps', true)
|
||||||
|
|
||||||
|
export const UserModel = mongoose.model<IUser>('User', UserSchema)
|
98
src/routes/authentication.ts
Normal file
98
src/routes/authentication.ts
Normal file
@ -0,0 +1,98 @@
|
|||||||
|
import express, { Request, Response } from 'express'
|
||||||
|
|
||||||
|
import { authenticated } from '@helpers'
|
||||||
|
import { UserModel } from '@models'
|
||||||
|
import { AuthenticatedRequest, HttpStatus, IUser, ResponseType, UserResponseType } from '@types'
|
||||||
|
|
||||||
|
import bcrypt from 'bcryptjs'
|
||||||
|
import jwt from 'jsonwebtoken'
|
||||||
|
|
||||||
|
const router = express.Router()
|
||||||
|
|
||||||
|
// LoggedIn
|
||||||
|
router.get('/', authenticated, (req: AuthenticatedRequest, res: Response) => {
|
||||||
|
let response: ResponseType<{ user: UserResponseType; token: string }> = {
|
||||||
|
status: HttpStatus.OK,
|
||||||
|
}
|
||||||
|
|
||||||
|
const useSecureAuth = process.env.NODE_ENV !== 'development'
|
||||||
|
|
||||||
|
if (req.cookies['auth-token']) {
|
||||||
|
res.cookie('auth-token', req.cookies['auth-token'], {
|
||||||
|
maxAge: 31 * 24 * 3600 * 1000, // 1 mois
|
||||||
|
httpOnly: useSecureAuth,
|
||||||
|
secure: useSecureAuth,
|
||||||
|
domain: process.env.COOKIE_DOMAIN,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
response.data = { user: req.user as UserResponseType, token: req.cookies['auth-token'] }
|
||||||
|
|
||||||
|
return res.status(response.status).send(response.data || response.error)
|
||||||
|
})
|
||||||
|
|
||||||
|
// Login
|
||||||
|
router.post('/', async (req: Request, res: Response) => {
|
||||||
|
let response: ResponseType<{ user?: UserResponseType; token: string }> = {
|
||||||
|
status: HttpStatus.OK,
|
||||||
|
}
|
||||||
|
|
||||||
|
const useSecureAuth = process.env.NODE_ENV !== 'development'
|
||||||
|
|
||||||
|
//Validation des données
|
||||||
|
const validation = req.body.username !== undefined && req.body.password !== undefined
|
||||||
|
if (!validation) {
|
||||||
|
return res.status(HttpStatus.BAD_REQUEST).send('Username and password are required')
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const user = await UserModel.findOne<IUser | null>({ username: req.body.username }).exec()
|
||||||
|
|
||||||
|
// If the user doesn't exist
|
||||||
|
if (user === null) {
|
||||||
|
return res.status(HttpStatus.UNAUTHORIZED).send('Username or password incorrect')
|
||||||
|
}
|
||||||
|
|
||||||
|
const validPass = await bcrypt.compare(req.body.password, user.password)
|
||||||
|
if (!validPass) {
|
||||||
|
return res.status(HttpStatus.UNAUTHORIZED).send('Username or password incorrect')
|
||||||
|
}
|
||||||
|
|
||||||
|
// Token generation
|
||||||
|
const {
|
||||||
|
password, // eslint-disable-line no-unused-vars
|
||||||
|
...tokenContent
|
||||||
|
} = user.toObject()
|
||||||
|
|
||||||
|
const token = jwt.sign(tokenContent, process.env.JWT_SECRET || '')
|
||||||
|
|
||||||
|
res.cookie('auth-token', token, {
|
||||||
|
maxAge: 31 * 24 * 3600 * 1000 * parseInt(process.env.JWT_EXPIRES_IN || '1'), // in months
|
||||||
|
httpOnly: useSecureAuth,
|
||||||
|
secure: useSecureAuth,
|
||||||
|
domain: process.env.COOKIE_DOMAIN,
|
||||||
|
})
|
||||||
|
|
||||||
|
response.data = { user: tokenContent as UserResponseType, token }
|
||||||
|
} catch (error) {
|
||||||
|
return res.status(HttpStatus.INTERNAL_SERVER_ERROR).send('Internal server error')
|
||||||
|
}
|
||||||
|
|
||||||
|
return res.status(response.status).send(response.data || response.error)
|
||||||
|
})
|
||||||
|
|
||||||
|
// Logout
|
||||||
|
router.delete('/', authenticated, (_req: AuthenticatedRequest, res: Response) => {
|
||||||
|
let response: ResponseType = {
|
||||||
|
status: HttpStatus.OK,
|
||||||
|
}
|
||||||
|
|
||||||
|
res.cookie('auth-token', '', {
|
||||||
|
maxAge: -100,
|
||||||
|
domain: process.env.COOKIE_DOMAIN,
|
||||||
|
})
|
||||||
|
|
||||||
|
return res.status(response.status).send('Ok')
|
||||||
|
})
|
||||||
|
|
||||||
|
export { router as authenticationRouter }
|
14
src/routes/category.ts
Normal file
14
src/routes/category.ts
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
import express, { Request, Response } from 'express'
|
||||||
|
|
||||||
|
import { getCategories } from '@controllers'
|
||||||
|
|
||||||
|
const router = express.Router()
|
||||||
|
|
||||||
|
// Get categories
|
||||||
|
router.get('/', async (req: Request, res: Response) => {
|
||||||
|
const response = await getCategories()
|
||||||
|
|
||||||
|
return res.status(response.status).send(response.data || response.error)
|
||||||
|
})
|
||||||
|
|
||||||
|
export { router as categoryRouter }
|
31
src/routes/file.ts
Normal file
31
src/routes/file.ts
Normal file
@ -0,0 +1,31 @@
|
|||||||
|
import express, { Response } from 'express'
|
||||||
|
|
||||||
|
import { getFile } from '@controllers'
|
||||||
|
import { authenticated } from '@helpers'
|
||||||
|
import { AuthenticatedRequest, IFile, IUser } from '@types'
|
||||||
|
|
||||||
|
import path from 'path'
|
||||||
|
|
||||||
|
const router = express.Router()
|
||||||
|
|
||||||
|
router.get('/:_id', authenticated, async (req: AuthenticatedRequest, res: Response) => {
|
||||||
|
const { _id } = req.params
|
||||||
|
|
||||||
|
const response = await getFile(<IFile['_id']>_id, <IUser>req.user)
|
||||||
|
|
||||||
|
if (!response.data) {
|
||||||
|
return res.status(response.status).send(response.error)
|
||||||
|
}
|
||||||
|
|
||||||
|
const file = Buffer.from(response.data.data, 'base64')
|
||||||
|
|
||||||
|
res.writeHead(response.status, {
|
||||||
|
'Content-Type': response.data.mimetype,
|
||||||
|
'Content-Length': file.length,
|
||||||
|
'Content-Disposition': `inline; filename="${response.data.name}`,
|
||||||
|
})
|
||||||
|
|
||||||
|
res.end(file)
|
||||||
|
})
|
||||||
|
|
||||||
|
export { router as fileRouter }
|
16
src/routes/index.ts
Normal file
16
src/routes/index.ts
Normal file
@ -0,0 +1,16 @@
|
|||||||
|
import express, { Request, Response } from 'express'
|
||||||
|
|
||||||
|
const router = express.Router()
|
||||||
|
|
||||||
|
router.get('/', (_req: Request, res: Response) => {
|
||||||
|
return res.status(200).send('Ok')
|
||||||
|
})
|
||||||
|
|
||||||
|
export { router as indexRouter }
|
||||||
|
export * from './authentication'
|
||||||
|
export * from './user'
|
||||||
|
export * from './room'
|
||||||
|
export * from './file'
|
||||||
|
export * from './category'
|
||||||
|
export * from './item'
|
||||||
|
export * from './room'
|
72
src/routes/item.ts
Normal file
72
src/routes/item.ts
Normal file
@ -0,0 +1,72 @@
|
|||||||
|
import express, { Response } from 'express'
|
||||||
|
|
||||||
|
import { createItem, deleteItem, getBrandsName, getItem, getItems, updateItem } from '@controllers'
|
||||||
|
import { authenticated } from '@helpers'
|
||||||
|
import { AuthenticatedRequest, ICreateItemInput, IItem, IUpdateItemInput, IUploadFile, IUser } from '@types'
|
||||||
|
|
||||||
|
import multer from 'multer'
|
||||||
|
|
||||||
|
const router = express.Router()
|
||||||
|
const upload = multer({})
|
||||||
|
|
||||||
|
router.use(
|
||||||
|
upload.fields([
|
||||||
|
{ name: 'invoice', maxCount: 1 },
|
||||||
|
{ name: 'image', maxCount: 1 },
|
||||||
|
]),
|
||||||
|
)
|
||||||
|
|
||||||
|
// Get all items from user
|
||||||
|
router.get('/', authenticated, async (req: AuthenticatedRequest, res: Response) => {
|
||||||
|
const response = await getItems(<IUser>req.user)
|
||||||
|
|
||||||
|
return res.status(response.status).send(response.data || response.error)
|
||||||
|
})
|
||||||
|
|
||||||
|
// Get brands name
|
||||||
|
router.get('/brands', authenticated, async (req: AuthenticatedRequest, res: Response) => {
|
||||||
|
const response = await getBrandsName(<IUser>req.user)
|
||||||
|
|
||||||
|
return res.status(response.status).send(response.data || response.error)
|
||||||
|
})
|
||||||
|
|
||||||
|
// Get item details
|
||||||
|
router.get('/:_id', authenticated, async (req: AuthenticatedRequest, res: Response) => {
|
||||||
|
const { _id } = req.params
|
||||||
|
|
||||||
|
const response = await getItem(<IItem['_id']>_id, <IUser>req.user)
|
||||||
|
|
||||||
|
return res.status(response.status).send(response.data || response.error)
|
||||||
|
})
|
||||||
|
|
||||||
|
// Create item
|
||||||
|
router.post('/', authenticated, async (req: AuthenticatedRequest, res: Response) => {
|
||||||
|
const response = await createItem(<ICreateItemInput>req.body, <IUser>req.user, <IUploadFile>req.files)
|
||||||
|
|
||||||
|
return res.status(response.status).send(response.data || response.error)
|
||||||
|
})
|
||||||
|
|
||||||
|
// Update item
|
||||||
|
router.put('/:_id', authenticated, async (req: AuthenticatedRequest, res: Response) => {
|
||||||
|
const { _id } = req.params
|
||||||
|
|
||||||
|
const response = await updateItem(
|
||||||
|
<IItem['_id']>_id,
|
||||||
|
<IUpdateItemInput>req.body,
|
||||||
|
<IUser>req.user,
|
||||||
|
<IUploadFile>req.files,
|
||||||
|
)
|
||||||
|
|
||||||
|
return res.status(response.status).send(response.data || response.error)
|
||||||
|
})
|
||||||
|
|
||||||
|
// Delete item
|
||||||
|
router.delete('/:_id', authenticated, async (req: AuthenticatedRequest, res: Response) => {
|
||||||
|
const { _id } = req.params
|
||||||
|
|
||||||
|
const response = await deleteItem(<IItem['_id']>_id, <IUser>req.user)
|
||||||
|
|
||||||
|
return res.status(response.status).send(response.data || response.error)
|
||||||
|
})
|
||||||
|
|
||||||
|
export { router as itemRouter }
|
59
src/routes/room.ts
Normal file
59
src/routes/room.ts
Normal file
@ -0,0 +1,59 @@
|
|||||||
|
import express, { Response } from 'express'
|
||||||
|
|
||||||
|
import { createRoom, deleteRoom, getRoom, getRoomStats, getRooms, updateRoom } from '@controllers'
|
||||||
|
import { authenticated } from '@helpers'
|
||||||
|
import { AuthenticatedRequest, IRoom, IUpdateItemInput, IUser } from '@types'
|
||||||
|
|
||||||
|
const router = express.Router()
|
||||||
|
|
||||||
|
// Get all rooms from user
|
||||||
|
router.get('/', authenticated, async (req: AuthenticatedRequest, res: Response) => {
|
||||||
|
const response = await getRooms(<IUser>req.user)
|
||||||
|
|
||||||
|
return res.status(response.status).send(response.data || response.error)
|
||||||
|
})
|
||||||
|
|
||||||
|
// Get room details
|
||||||
|
router.get('/stats', authenticated, async (req: AuthenticatedRequest, res: Response) => {
|
||||||
|
const response = await getRoomStats(<IUser>req.user)
|
||||||
|
|
||||||
|
return res.status(response.status).send(response.data || response.error)
|
||||||
|
})
|
||||||
|
|
||||||
|
// Get room details
|
||||||
|
router.get('/:_id', authenticated, async (req: AuthenticatedRequest, res: Response) => {
|
||||||
|
const { _id } = req.params
|
||||||
|
|
||||||
|
const response = await getRoom(<IRoom['_id']>_id, <IUser>req.user)
|
||||||
|
|
||||||
|
return res.status(response.status).send(response.data || response.error)
|
||||||
|
})
|
||||||
|
|
||||||
|
// Create room
|
||||||
|
router.post('/', authenticated, async (req: AuthenticatedRequest, res: Response) => {
|
||||||
|
const { name } = req.body
|
||||||
|
|
||||||
|
const response = await createRoom(<IRoom['name']>name, <IUser>req.user)
|
||||||
|
|
||||||
|
return res.status(response.status).send(response.data || response.error)
|
||||||
|
})
|
||||||
|
|
||||||
|
// Update room
|
||||||
|
router.put('/:_id', authenticated, async (req: AuthenticatedRequest, res: Response) => {
|
||||||
|
const { _id } = req.params
|
||||||
|
|
||||||
|
const response = await updateRoom(<IRoom['_id']>_id, <IUpdateItemInput>req.body, <IUser>req.user)
|
||||||
|
|
||||||
|
return res.status(response.status).send(response.data || response.error)
|
||||||
|
})
|
||||||
|
|
||||||
|
// Delete room
|
||||||
|
router.delete('/:_id', authenticated, async (req: AuthenticatedRequest, res: Response) => {
|
||||||
|
const { _id } = req.params
|
||||||
|
|
||||||
|
const response = await deleteRoom(<IRoom['_id']>_id, <IUser>req.user)
|
||||||
|
|
||||||
|
return res.status(response.status).send(response.data || response.error)
|
||||||
|
})
|
||||||
|
|
||||||
|
export { router as roomRouter }
|
51
src/routes/user.ts
Normal file
51
src/routes/user.ts
Normal file
@ -0,0 +1,51 @@
|
|||||||
|
import express, { Request, Response } from 'express'
|
||||||
|
|
||||||
|
import { createUser, deleteUser, getUsers, updateUser } from '@controllers'
|
||||||
|
import { authenticated } from '@helpers'
|
||||||
|
import { AuthenticatedRequest, ICreateUserInput, IGetUserInput, IUpdateUserInput, IUser } from '@types'
|
||||||
|
|
||||||
|
const router = express.Router()
|
||||||
|
|
||||||
|
router.get('/', authenticated, async (req: AuthenticatedRequest, res: Response) => {
|
||||||
|
const response = await getUsers(<IGetUserInput>req.query, <IUser>req.user)
|
||||||
|
|
||||||
|
return res.status(response.status).send(response.data || response.error)
|
||||||
|
})
|
||||||
|
|
||||||
|
router.post('/', async (req: Request, res: Response) => {
|
||||||
|
const response = await createUser(<ICreateUserInput>req.body)
|
||||||
|
|
||||||
|
const useSecureAuth = process.env.NODE_ENV !== 'development'
|
||||||
|
|
||||||
|
res.cookie('auth-token', response?.data?.token, {
|
||||||
|
maxAge: 31 * 24 * 3600 * 1000 * parseInt(process.env.JWT_EXPIRES_IN || '1'), // in months
|
||||||
|
httpOnly: useSecureAuth,
|
||||||
|
secure: useSecureAuth,
|
||||||
|
domain: process.env.COOKIE_DOMAIN,
|
||||||
|
})
|
||||||
|
|
||||||
|
return res.status(response.status).send(response.data || response.error)
|
||||||
|
})
|
||||||
|
|
||||||
|
router.put('/:_id', authenticated, async (req: AuthenticatedRequest, res: Response) => {
|
||||||
|
const response = await updateUser(<IUser['_id']>req.params._id, <IUpdateUserInput>req.body, <IUser>req.user)
|
||||||
|
|
||||||
|
const useSecureAuth = process.env.NODE_ENV !== 'development'
|
||||||
|
|
||||||
|
res.cookie('auth-token', response?.data?.token, {
|
||||||
|
maxAge: 31 * 24 * 3600 * 1000 * parseInt(process.env.JWT_EXPIRES_IN || '1'), // in months
|
||||||
|
httpOnly: useSecureAuth,
|
||||||
|
secure: useSecureAuth,
|
||||||
|
domain: process.env.COOKIE_DOMAIN,
|
||||||
|
})
|
||||||
|
|
||||||
|
return res.status(response.status).send(response.data || response.error)
|
||||||
|
})
|
||||||
|
|
||||||
|
router.delete('/:_id', authenticated, async (req: AuthenticatedRequest, res: Response) => {
|
||||||
|
const response = await deleteUser(<IUser['_id']>req.params._id, <IUser>req.user)
|
||||||
|
|
||||||
|
return res.status(response.status).send(response.data || response.error)
|
||||||
|
})
|
||||||
|
|
||||||
|
export { router as userRouter }
|
12
src/types/category.ts
Normal file
12
src/types/category.ts
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
import { Document } from 'mongoose'
|
||||||
|
|
||||||
|
export interface ICategory extends Document {
|
||||||
|
en: string
|
||||||
|
fr: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export type CategoryResponseType = {
|
||||||
|
_id: string
|
||||||
|
en: string
|
||||||
|
fr: string
|
||||||
|
}
|
20
src/types/file.ts
Normal file
20
src/types/file.ts
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
import { IUser } from '@types'
|
||||||
|
|
||||||
|
import { Document } from 'mongoose'
|
||||||
|
|
||||||
|
export interface IFile extends Document {
|
||||||
|
name: string
|
||||||
|
mimetype: string
|
||||||
|
data: string
|
||||||
|
filename: string
|
||||||
|
user: IUser['_id']
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ICreateFileInput {
|
||||||
|
fieldname: string
|
||||||
|
originalname: string
|
||||||
|
encoding: string
|
||||||
|
mimetype: string
|
||||||
|
buffer: Buffer
|
||||||
|
size: number
|
||||||
|
}
|
32
src/types/global.ts
Normal file
32
src/types/global.ts
Normal file
@ -0,0 +1,32 @@
|
|||||||
|
import { Express as ExpressType, Request } from 'express'
|
||||||
|
|
||||||
|
import { IUser } from '@types'
|
||||||
|
|
||||||
|
export enum HttpStatus {
|
||||||
|
OK = 200,
|
||||||
|
CREATED = 201,
|
||||||
|
NO_CONTENT = 204,
|
||||||
|
BAD_REQUEST = 400,
|
||||||
|
UNAUTHORIZED = 401,
|
||||||
|
FORBIDDEN = 403,
|
||||||
|
NOT_FOUND = 404,
|
||||||
|
CONFLICT = 409,
|
||||||
|
TEA_POT = 418,
|
||||||
|
INTERNAL_SERVER_ERROR = 500,
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ResponseType<Type = null> = {
|
||||||
|
status: HttpStatus
|
||||||
|
data?: Type
|
||||||
|
error?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ControllerResponseType<Type = null> = Promise<ResponseType<Type>>
|
||||||
|
|
||||||
|
export interface AuthenticatedRequest extends Request {
|
||||||
|
user?: IUser
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Express extends ExpressType {
|
||||||
|
isDbConnected?: boolean
|
||||||
|
}
|
6
src/types/index.ts
Normal file
6
src/types/index.ts
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
export * from './global'
|
||||||
|
export * from './user'
|
||||||
|
export * from './room'
|
||||||
|
export * from './item'
|
||||||
|
export * from './file'
|
||||||
|
export * from './category'
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user