initial commit

This commit is contained in:
Alex Holliday committed 2025-11-13 13:47:26 -08:00
1 parent 7cb985116e
commit 75acf7b38f
955 files changed
+37333 -87054

No files matched your search

-1
View File
@@ -1 +0,0 @@
./docker
-25
View File
@@ -1,25 +0,0 @@
**(Please remove this line only before submitting your PR. Ensure that all relevant items are checked before submission.)**
## Describe your changes
Briefly describe the changes you made and their purpose.
## Write your issue number after "Fixes "
Fixes #123
## Please ensure all items are checked off before requesting a review. "Checked off" means you need to add an "x" character between brackets so they turn into checkmarks.
- [ ] (Do not skip this or your PR will be closed) I deployed the application locally.
- [ ] (Do not skip this or your PR will be closed) I have performed a self-review and testing of my code.
- [ ] I have included the issue # in the PR.
- [ ] I have added i18n support to visible strings (instead of `<div>Add</div>`, use):
```Javascript
const { t } = useTranslation();
<div>{t('add')}</div>
```
- [ ] The issue I am working on is assigned to me.
- [ ] I didn't use any hardcoded values (otherwise it will not scale, and will make it difficult to maintain consistency across the application).
- [ ] My PR is granular and targeted to one specific feature.
-68
View File
@@ -1,68 +0,0 @@
name: Staging deploy
on:
push:
branches: ["develop"]
jobs:
docker-build-and-push:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Log in to GitHub Container Registry
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Build Server Docker image
run: |
docker build \
-t ghcr.io/bluewave-labs/checkmate-backend:staging \
-f ./docker/staging/server.Dockerfile \
--label org.opencontainers.image.source=https://github.com/bluewave-labs/checkmate-backend \
.
- name: Push Server Docker image
run: docker push ghcr.io/bluewave-labs/checkmate-backend:staging
- name: Build Mongo Docker image
run: |
docker build \
-t ghcr.io/bluewave-labs/checkmate-mongo:staging \
-f ./docker/staging/mongoDB.Dockerfile \
--label org.opencontainers.image.source=https://github.com/bluewave-labs/checkmate-backend \
.
- name: Push MongoDB Docker image
run: docker push ghcr.io/bluewave-labs/checkmate-mongo:staging
- name: Build Redis Docker image
run: |
docker build \
-t ghcr.io/bluewave-labs/checkmate-redis:staging \
-f ./docker/staging/redis.Dockerfile \
--label org.opencontainers.image.source=https://github.com/bluewave-labs/checkmate-backend \
.
- name: Push Redis Docker image
run: docker push ghcr.io/bluewave-labs/checkmate-redis:staging
deploy-to-staging:
needs: docker-build-and-push
runs-on: ubuntu-latest
steps:
- name: SSH into server and restart container using Docker Compose
uses: appleboy/ssh-action@v1.0.0
with:
host: ${{ secrets.STAGING_SERVER_HOST }}
username: ${{ secrets.STAGING_SERVER_USER }}
key: ${{ secrets.STAGING_SERVER_SSH_KEY }}
script: |
cd checkmate/server/docker/staging
docker compose down
docker compose pull
docker compose up -d
Executable → Regular
+14 -11
View File
@@ -1,12 +1,15 @@
node_modules
# Node.js
node_modules/
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnp/
.pnp.js
.env
*.log
*.sh
!scripts/inject-vars.sh
.nyc_output
coverage
.clinic
node_modules
.vscode/*
public
dist
.DS_Store
/logs/
# TypeScript
/dist/
/build/
*.tsbuildinfo
-8
View File
@@ -1,8 +0,0 @@
module.exports = {
require: ["esm", "chai/register-expect.js"], // Include Chai's "expect" interface globally
spec: "tests/**/*.test.js", // Specify test files
timeout: 5000, // Set test-case timeout in milliseconds
recursive: true, // Include subdirectories
reporter: "spec", // Use the "spec" reporter
exit: true, // Force Mocha to quit after tests complete
};
-8
View File
@@ -1,8 +0,0 @@
{
"all": true,
"include": ["controllers/*.js", "utils/*.js", "service/*.js", "db/mongo/modules/*.js"],
"exclude": ["**/*.test.js"],
"reporter": ["html", "text", "lcov"],
"sourceMap": false,
"instrument": true
}
-16
View File
@@ -1,16 +0,0 @@
{
"printWidth": 150,
"useTabs": true,
"tabWidth": 2,
"singleQuote": false,
"bracketSpacing": true,
"proseWrap": "preserve",
"bracketSameLine": false,
"singleAttributePerLine": true,
"semi": true,
"jsxSingleQuote": false,
"quoteProps": "as-needed",
"arrowParens": "always",
"trailingComma": "es5",
"htmlWhitespaceSensitivity": "css"
}
+8
View File
@@ -0,0 +1,8 @@
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
EXPOSE 52345
CMD ["node", "dist/index.js"]
-661
View File
@@ -1,661 +0,0 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) 2025 BlueWave Labs
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.
-15
View File
@@ -1,15 +0,0 @@
<h1 align="center"><a href="https://bluewavelabs.ca" target="_blank">Checkmate backend</a></h1>
<p align="center"><strong>The backend service for Checkmate, an open source uptime and infrastructure monitoring application</strong></p>
This directory contains the **backend** of Checkmate, which handles data processing, storage, and API services for the Checkmate monitoring tool. The backend is responsible for managing uptime checks, handling real-time alerts, and storing historical monitoring data.
Checkmate's backend is designed to be lightweight and scalable, ensuring reliable performance even with a high number of active monitors.
## Installation & documentation
For setup instructions, configuration details, and deployment guidelines, please visit our official documentation at [docs.checkmate.so](https://docs.checkmate.so).
## Related repositories
- [Capture Agent](https://github.com/bluewave-labs/capture) (Optional, provides additional server insights)
-30
View File
@@ -1,30 +0,0 @@
import globals from "globals";
import pluginJs from "@eslint/js";
import mochaPlugin from "eslint-plugin-mocha";
/*
Please do not forget to look at the latest eslint configurations and rules.
ESlint v9 configuration is different than v8.
"https://eslint.org/docs/latest/use/configure/"
*/
/** @type {import('eslint').Linter.Config[]} */
export default [
{
languageOptions: {
globals: {
...globals.node, // Add Node.js globals
...globals.chai, // Add Chai globals
},
ecmaVersion: 2023,
sourceType: "module",
},
},
pluginJs.configs.recommended, // Core JS rules
mochaPlugin.configs.flat.recommended, // Mocha rules
{
rules: {
"mocha/max-top-level-suites": "warn", // Warn if there are too many top-level suites instead of failing
},
},
];
Executable → Regular
+3 -3
View File
@@ -1,5 +1,5 @@
{
"ignore": ["src/locales/*", "*.log", "node_modules/*"],
"watch": ["src/**/*.ts", "src/**/*.js", "*.json"],
"ext": "ts,js,json"
"ignore": ["node_modules/*"],
"watch": ["src/**/*.ts", "src/**/*.js", "*.json"],
"ext": "ts,js,json"
}
-3381
View File
File diff suppressed because it is too large. Load diff
+4604 -11507
View File
File diff suppressed because it is too large. Load diff
Executable → Regular
+40 -75
View File
@@ -1,77 +1,42 @@
{
"name": "server",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type": "module",
"scripts": {
"test": "c8 mocha",
"dev": "tsx watch src/index.js",
"start": "node --watch ./dist/index.js",
"build": "tsc",
"lint": "eslint .",
"lint-fix": "eslint --fix .",
"format": "prettier --write .",
"format-check": "prettier --check ."
},
"keywords": [],
"author": "",
"license": "ISC",
"engines": {
"node": ">=20"
},
"dependencies": {
"@pulsecron/pulse": "1.6.8",
"axios": "^1.7.2",
"bcryptjs": "3.0.2",
"bullmq": "5.41.2",
"cacheable-lookup": "7.0.0",
"compression": "1.8.1",
"cookie-parser": "^1.4.7",
"cors": "^2.8.5",
"dockerode": "4.0.6",
"dotenv": "^16.4.5",
"express": "^4.19.2",
"express-rate-limit": "8.0.1",
"gamedig": "^5.3.1",
"got": "14.4.7",
"handlebars": "^4.7.8",
"helmet": "^8.0.0",
"ioredis": "^5.4.2",
"isomorphic-dompurify": "^2.26.0",
"jmespath": "^0.16.0",
"joi": "^17.13.1",
"jsdom": "^26.1.0",
"jsonwebtoken": "9.0.2",
"mailersend": "^2.2.0",
"mjml": "^5.0.0-alpha.4",
"mongoose": "^8.3.3",
"multer": "^1.4.5-lts.1",
"nodemailer": "^6.9.14",
"papaparse": "^5.5.2",
"ping": "0.4.4",
"sharp": "0.33.5",
"ssl-checker": "2.0.10",
"super-simple-scheduler": "1.4.5",
"swagger-ui-express": "5.0.1",
"winston": "^3.13.0"
},
"devDependencies": {
"@eslint/js": "^9.17.0",
"@types/express": "5.0.3",
"@types/jsonwebtoken": "9.0.10",
"@types/nodemailer": "7.0.1",
"@types/ping": "0.4.4",
"c8": "10.1.3",
"chai": "5.2.0",
"eslint": "^9.17.0",
"eslint-plugin-mocha": "^10.5.0",
"esm": "3.2.25",
"globals": "^15.14.0",
"mocha": "11.1.0",
"prettier": "^3.3.3",
"sinon": "19.0.2",
"tsx": "4.20.5",
"typescript": "5.9.2"
}
"name": "server",
"version": "1.0.0",
"main": "index.js",
"type": "module",
"scripts": {
"dev": "nodemon --exec tsx src/index.js",
"build": "tsc && tsc-alias",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": "",
"devDependencies": {
"@types/cookie-parser": "1.4.9",
"@types/cors": "2.8.19",
"@types/jsonwebtoken": "9.0.10",
"@types/node": "24.7.1",
"@types/nodemailer": "7.0.2",
"nodemon": "3.1.10",
"tsc-alias": "1.8.16",
"tsx": "4.20.6",
"typescript": "5.9.3"
},
"dependencies": {
"bcryptjs": "3.0.2",
"cacheable-lookup": "7.0.0",
"cookie-parser": "1.4.7",
"cors": "2.8.5",
"dotenv": "17.2.3",
"express": "5.1.0",
"got": "14.5.0",
"jsonwebtoken": "9.0.2",
"mongoose": "8.19.1",
"nodemailer": "7.0.9",
"ping": "1.0.0",
"super-simple-scheduler": "1.4.6",
"winston": "3.18.3",
"zod": "4.1.12"
}
}
-7
View File
@@ -1,7 +0,0 @@
for i in $(env | grep UPTIME_APP_)
do
key=$(echo $i | cut -d '=' -f 1)
value=$(echo $i | cut -d '=' -f 2-)
echo $key=$value
find ./public/assets -type f \( -name '*.js' -o -name '*.css' \) -exec sed -i "s|${key}|${value}|g" '{}' +
done
-85
View File
@@ -1,85 +0,0 @@
import express from "express";
import path from "path";
import { responseHandler } from "./middleware/v1/responseHandler.js";
import cors from "cors";
import helmet from "helmet";
import compression from "compression";
import cookieParser from "cookie-parser";
import languageMiddleware from "./middleware/v1/languageMiddleware.js";
import swaggerUi from "swagger-ui-express";
import { handleErrors } from "./middleware/v1/handleErrors.js";
import { setupRoutes } from "./config/routes.js";
import { generalApiLimiter } from "./middleware/v1/rateLimiter.js";
import { sanitizeBody, sanitizeQuery } from "./middleware/v1/sanitization.js";
export const createApp = ({ services, controllers, envSettings, frontendPath, openApiSpec }) => {
const allowedOrigin = envSettings.clientHost;
const app = express();
app.use(generalApiLimiter);
// Static files
app.use(express.static(frontendPath));
// Response handler
app.use(responseHandler);
app.use(
cors({
origin: allowedOrigin,
methods: "GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS",
allowedHeaders: ["Content-Type", "Authorization"],
credentials: true,
})
);
app.use(express.json());
app.use(cookieParser());
app.use(sanitizeBody());
app.use(sanitizeQuery());
app.use(
helmet({
hsts: false,
contentSecurityPolicy: {
useDefaults: true,
directives: {
upgradeInsecureRequests: null,
"script-src": ["'self'", "'unsafe-inline'", "'unsafe-eval'"],
"object-src": ["'none'"],
"base-uri": ["'self'"],
},
},
})
);
app.use(
compression({
level: 6,
threshold: 1024,
filter: (req, res) => {
if (req.headers["x-no-compression"]) {
return false;
}
return compression.filter(req, res);
},
})
);
app.use(languageMiddleware(services.stringService, services.translationService, services.settingsService));
// Swagger UI
app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(openApiSpec));
app.use("/api/v1/health", (req, res) => {
res.json({
status: "OK",
});
});
// Main app routes
setupRoutes(app, controllers);
// FE routes
app.get("*", (req, res) => {
res.sendFile(path.join(frontendPath, "index.html"));
});
app.use(handleErrors);
return app;
};
-82
View File
@@ -1,82 +0,0 @@
import { createCommonDependencies } from "../controllers/v1/baseController.js";
// Services
// V1 Controllers
import MonitorController from "../controllers/v1/monitorController.js";
import AuthController from "../controllers/v1/authController.js";
import SettingsController from "../controllers/v1/settingsController.js";
import CheckController from "../controllers/v1/checkController.js";
import InviteController from "../controllers/v1/inviteController.js";
import MaintenanceWindowController from "../controllers/v1/maintenanceWindowController.js";
import QueueController from "../controllers/v1/queueController.js";
import LogController from "../controllers/v1/logController.js";
import StatusPageController from "../controllers/v1/statusPageController.js";
import NotificationController from "../controllers/v1/notificationController.js";
import DiagnosticController from "../controllers/v1/diagnosticController.js";
// V2 Controllers
import AuthControllerV2 from "../controllers/v2/AuthController.js";
import InviteControllerV2 from "../controllers/v2/InviteController.js";
import MaintenanceControllerV2 from "../controllers/v2/MaintenanceController.js";
import MonitorControllerV2 from "../controllers/v2/MonitorController.js";
import NotificationChannelControllerV2 from "../controllers/v2/NotificationChannelController.js";
import QueueControllerV2 from "../controllers/v2/QueueController.js";
export const initializeControllers = (services) => {
const controllers = {};
const commonDependencies = createCommonDependencies(services.db, services.errorService, services.logger, services.stringService);
// V1
controllers.authController = new AuthController(commonDependencies, {
settingsService: services.settingsService,
emailService: services.emailService,
jobQueue: services.jobQueue,
userService: services.userService,
});
controllers.monitorController = new MonitorController(commonDependencies, {
settingsService: services.settingsService,
jobQueue: services.jobQueue,
emailService: services.emailService,
monitorService: services.monitorService,
});
controllers.settingsController = new SettingsController(commonDependencies, {
settingsService: services.settingsService,
emailService: services.emailService,
});
controllers.checkController = new CheckController(commonDependencies, {
settingsService: services.settingsService,
checkService: services.checkService,
});
controllers.inviteController = new InviteController(commonDependencies, {
inviteService: services.inviteService,
});
controllers.maintenanceWindowController = new MaintenanceWindowController(commonDependencies, {
settingsService: services.settingsService,
maintenanceWindowService: services.maintenanceWindowService,
});
controllers.queueController = new QueueController(commonDependencies, {
jobQueue: services.jobQueue,
});
controllers.logController = new LogController(commonDependencies);
controllers.statusPageController = new StatusPageController(commonDependencies);
controllers.notificationController = new NotificationController(commonDependencies, {
notificationService: services.notificationService,
statusService: services.statusService,
});
controllers.diagnosticController = new DiagnosticController(commonDependencies, {
diagnosticService: services.diagnosticService,
});
//V2
controllers.authControllerV2 = new AuthControllerV2(services.authServiceV2, services.inviteServiceV2);
controllers.inviteControllerV2 = new InviteControllerV2(services.inviteServiceV2);
controllers.maintenanceControllerV2 = new MaintenanceControllerV2(services.maintenanceServiceV2);
controllers.monitorControllerV2 = new MonitorControllerV2(services.monitorServiceV2, services.checkServiceV2);
controllers.notificationChannelControllerV2 = new NotificationChannelControllerV2(services.notificationChannelServiceV2);
controllers.queueControllerV2 = new QueueControllerV2(services.jobQueueV2);
return controllers;
};
View File
Whitespace-only changes.
+22 -18
View File
@@ -1,25 +1,29 @@
import dotenv from "dotenv";
export interface IEevConfig {
NODE_ENV: string;
JWT_SECRET: string;
PORT: number;
PAGESPEED_API_KEY: string;
SMTP_HOST: string;
SMTP_PORT: number;
SMTP_USER: string;
SMTP_PASS: string;
export interface IEnvConfig {
NODE_ENV: string;
LOG_LEVEL: string;
ORIGIN: string;
JWT_SECRET: string;
PORT: number;
PAGESPEED_API_KEY: string;
SMTP_HOST: string;
SMTP_PORT: number;
SMTP_USER: string;
SMTP_PASS: string;
}
dotenv.config();
export const config: IEevConfig = {
NODE_ENV: process.env.NODE_ENV || "development",
JWT_SECRET: process.env.JWT_SECRET || "your_jwt_secret",
PORT: process.env.PORT ? parseInt(process.env.PORT, 10) : 3000,
PAGESPEED_API_KEY: process.env.PAGESPEED_API_KEY || "",
SMTP_HOST: process.env.SMTP_HOST || "smtp.example.com",
SMTP_PORT: process.env.SMTP_PORT ? parseInt(process.env.SMTP_PORT, 10) : 587,
SMTP_USER: process.env.SMTP_USER || "user@example.com",
SMTP_PASS: process.env.SMTP_PASS || "your_smtp_password",
export const config: IEnvConfig = {
NODE_ENV: process.env.NODE_ENV || "development",
LOG_LEVEL: process.env.LOG_LEVEL || "info",
ORIGIN: process.env.ORIGIN || "http://localhost:5173",
JWT_SECRET: process.env.JWT_SECRET || "your_jwt_secret",
PORT: process.env.PORT ? parseInt(process.env.PORT, 10) : 3000,
PAGESPEED_API_KEY: process.env.PAGESPEED_API_KEY || "",
SMTP_HOST: process.env.SMTP_HOST || "smtp.example.com",
SMTP_PORT: process.env.SMTP_PORT ? parseInt(process.env.SMTP_PORT, 10) : 587,
SMTP_USER: process.env.SMTP_USER || "user@example.com",
SMTP_PASS: process.env.SMTP_PASS || "your_smtp_password",
};
-64
View File
@@ -1,64 +0,0 @@
import { verifyJWT } from "../middleware/v1/verifyJWT.js";
import { authApiLimiter } from "../middleware/v1/rateLimiter.js";
import AuthRoutes from "../routes/v1/authRoute.js";
import InviteRoutes from "../routes/v1//inviteRoute.js";
import MonitorRoutes from "../routes/v1/monitorRoute.js";
import CheckRoutes from "../routes/v1/checkRoute.js";
import SettingsRoutes from "../routes/v1/settingsRoute.js";
import MaintenanceWindowRoutes from "../routes/v1/maintenanceWindowRoute.js";
import StatusPageRoutes from "../routes/v1/statusPageRoute.js";
import QueueRoutes from "../routes/v1/queueRoute.js";
import LogRoutes from "../routes/v1/logRoutes.js";
import DiagnosticRoutes from "../routes/v1//diagnosticRoute.js";
import NotificationRoutes from "../routes/v1/notificationRoute.js";
//V2
import AuthRoutesV2 from "../routes/v2/auth.js";
import InviteRoutesV2 from "../routes/v2/invite.js";
import MaintenanceRoutesV2 from "../routes/v2/maintenance.js";
import MonitorRoutesV2 from "../routes/v2/monitors.js";
import NotificationChannelRoutesV2 from "../routes/v2/notificationChannels.js";
import QueueRoutesV2 from "../routes/v2/queue.js";
export const setupRoutes = (app, controllers) => {
// V1
const authRoutes = new AuthRoutes(controllers.authController);
const monitorRoutes = new MonitorRoutes(controllers.monitorController);
const settingsRoutes = new SettingsRoutes(controllers.settingsController);
const checkRoutes = new CheckRoutes(controllers.checkController);
const inviteRoutes = new InviteRoutes(controllers.inviteController);
const maintenanceWindowRoutes = new MaintenanceWindowRoutes(controllers.maintenanceWindowController);
const queueRoutes = new QueueRoutes(controllers.queueController);
const logRoutes = new LogRoutes(controllers.logController);
const statusPageRoutes = new StatusPageRoutes(controllers.statusPageController);
const notificationRoutes = new NotificationRoutes(controllers.notificationController);
const diagnosticRoutes = new DiagnosticRoutes(controllers.diagnosticController);
app.use("/api/v1/auth", authApiLimiter, authRoutes.getRouter());
app.use("/api/v1/monitors", verifyJWT, monitorRoutes.getRouter());
app.use("/api/v1/settings", verifyJWT, settingsRoutes.getRouter());
app.use("/api/v1/checks", verifyJWT, checkRoutes.getRouter());
app.use("/api/v1/invite", inviteRoutes.getRouter());
app.use("/api/v1/maintenance-window", verifyJWT, maintenanceWindowRoutes.getRouter());
app.use("/api/v1/queue", verifyJWT, queueRoutes.getRouter());
app.use("/api/v1/logs", verifyJWT, logRoutes.getRouter());
app.use("/api/v1/status-page", statusPageRoutes.getRouter());
app.use("/api/v1/notifications", verifyJWT, notificationRoutes.getRouter());
app.use("/api/v1/diagnostic", verifyJWT, diagnosticRoutes.getRouter());
// V2
const authRoutesV2 = new AuthRoutesV2(controllers.authControllerV2);
const inviteRoutesV2 = new InviteRoutesV2(controllers.inviteControllerV2);
const maintenanceRoutesV2 = new MaintenanceRoutesV2(controllers.maintenanceControllerV2);
const monitorRoutesV2 = new MonitorRoutesV2(controllers.monitorControllerV2);
const notificationChannelRoutesV2 = new NotificationChannelRoutesV2(controllers.notificationChannelControllerV2);
const queueRoutesV2 = new QueueRoutesV2(controllers.queueControllerV2);
app.use("/api/v2/auth", authApiLimiter, authRoutesV2.getRouter());
app.use("/api/v2/invite", inviteRoutesV2.getRouter());
app.use("/api/v2/maintenance", maintenanceRoutesV2.getRouter());
app.use("/api/v2/monitors", monitorRoutesV2.getRouter());
app.use("/api/v2/notification-channels", notificationChannelRoutesV2.getRouter());
app.use("/api/v2/queue", queueRoutesV2.getRouter());
};
-306
View File
@@ -1,306 +0,0 @@
import ServiceRegistry from "../service/v1/system/serviceRegistry.js";
import TranslationService from "../service/v1/system/translationService.js";
import StringService from "../service/v1/system/stringService.js";
import MongoDB from "../db/v1/MongoDB.js";
import NetworkService from "../service/v1/infrastructure/networkService.js";
import EmailService from "../service/v1/infrastructure/emailService.js";
import BufferService from "../service/v1/infrastructure/bufferService.js";
import StatusService from "../service/v1/infrastructure/statusService.js";
import NotificationUtils from "../service/v1/infrastructure/notificationUtils.js";
import NotificationService from "../service/v1/infrastructure/notificationService.js";
import ErrorService from "../service/v1/infrastructure/errorService.js";
import SuperSimpleQueueHelper from "../service/v1/infrastructure/SuperSimpleQueue/SuperSimpleQueueHelper.js";
import SuperSimpleQueue from "../service/v1/infrastructure/SuperSimpleQueue/SuperSimpleQueue.js";
import UserService from "../service/v1/business/userService.js";
import CheckService from "../service/v1/business/checkService.js";
import DiagnosticService from "../service/v1/business/diagnosticService.js";
import InviteService from "../service/v1/business/inviteService.js";
import MaintenanceWindowService from "../service/v1/business/maintenanceWindowService.js";
import MonitorService from "../service/v1/business/monitorService.js";
import papaparse from "papaparse";
import axios from "axios";
import got from "got";
import ping from "ping";
import http from "http";
import https from "https";
import Docker from "dockerode";
import net from "net";
import fs from "fs";
import path from "path";
import nodemailer from "nodemailer";
import pkg from "handlebars";
const { compile } = pkg;
import mjml2html from "mjml";
import jwt from "jsonwebtoken";
import crypto from "crypto";
import { games } from "gamedig";
import jmespath from "jmespath";
import { GameDig } from "gamedig";
import { fileURLToPath } from "url";
import { ObjectId } from "mongodb";
// DB Modules
import { NormalizeData, NormalizeDataUptimeDetails } from "../utils/dataUtils.js";
import { GenerateAvatarImage } from "../utils/imageProcessing.js";
import { ParseBoolean } from "../utils/utils.js";
// Models
import Check from "../db/v1/models/Check.js";
import Monitor from "../db/v1/models/Monitor.js";
import User from "../db/v1/models/User.js";
import InviteToken from "../db/v1/models/InviteToken.js";
import StatusPage from "../db/v1/models/StatusPage.js";
import Team from "../db/v1/models/Team.js";
import MaintenanceWindow from "../db/v1/models/MaintenanceWindow.js";
import MonitorStats from "../db/v1/models/MonitorStats.js";
import Notification from "../db/v1/models/Notification.js";
import RecoveryToken from "../db/v1/models/RecoveryToken.js";
import AppSettings from "../db/v1/models/AppSettings.js";
import InviteModule from "../db/v1/modules/inviteModule.js";
import CheckModule from "../db/v1/modules/checkModule.js";
import StatusPageModule from "../db/v1/modules/statusPageModule.js";
import UserModule from "../db/v1/modules/userModule.js";
import MaintenanceWindowModule from "../db/v1/modules/maintenanceWindowModule.js";
import MonitorModule from "../db/v1/modules/monitorModule.js";
import NotificationModule from "../db/v1/modules/notificationModule.js";
import RecoveryModule from "../db/v1/modules/recoveryModule.js";
import SettingsModule from "../db/v1/modules/settingsModule.js";
// V2 Business
import AuthServiceV2 from "../service/v2/business/AuthService.js";
import CheckServiceV2 from "../service/v2/business/CheckService.js";
import InviteServiceV2 from "../service/v2/business/InviteService.js";
import MaintenanceServiceV2 from "../service/v2/business/MaintenanceService.js";
import MonitorServiceV2 from "../service/v2/business/MonitorService.js";
import MonitorStatsServiceV2 from "../service/v2/business/MonitorStatsService.js";
import NotificationChannelServiceV2 from "../service/v2/business/NotificationChannelService.js";
import QueueServiceV2 from "../service/v2/business/QueueService.js";
import UserServiceV2 from "../service/v2/business/UserService.js";
// V2 Infra
import DiscordServiceV2 from "../service/v2/infrastructure/NotificationServices/Discord.js";
import EmailServiceV2 from "../service/v2/infrastructure/NotificationServices/Email.js";
import SlackServiceV2 from "../service/v2/infrastructure/NotificationServices/Slack.js";
import WebhookServiceV2 from "../service/v2/infrastructure/NotificationServices/Webhook.js";
import JobGeneratorV2 from "../service/v2/infrastructure/JobGenerator.js";
import JobQueueV2 from "../service/v2/infrastructure/JobQueue.js";
import NetworkServiceV2 from "../service/v2/infrastructure/NetworkService.js";
import NotificationServiceV2 from "../service/v2/infrastructure/NotificationService.js";
import StatusServiceV2 from "../service/v2/infrastructure/StatusService.js";
export const initializeServices = async ({ logger, envSettings, settingsService }) => {
const serviceRegistry = new ServiceRegistry({ logger });
ServiceRegistry.instance = serviceRegistry;
const translationService = new TranslationService(logger);
await translationService.initialize();
const stringService = new StringService(translationService);
// Create DB
const checkModule = new CheckModule({ logger, Check, Monitor, User });
const inviteModule = new InviteModule({ InviteToken, crypto, stringService });
const statusPageModule = new StatusPageModule({ StatusPage, NormalizeData, stringService });
const userModule = new UserModule({ User, Team, GenerateAvatarImage, ParseBoolean, stringService });
const maintenanceWindowModule = new MaintenanceWindowModule({ MaintenanceWindow });
const monitorModule = new MonitorModule({
Monitor,
MonitorStats,
Check,
stringService,
fs,
path,
fileURLToPath,
ObjectId,
NormalizeData,
NormalizeDataUptimeDetails,
});
const notificationModule = new NotificationModule({ Notification, Monitor });
const recoveryModule = new RecoveryModule({ User, RecoveryToken, crypto, stringService });
const settingsModule = new SettingsModule({ AppSettings });
const db = new MongoDB({
logger,
envSettings,
checkModule,
inviteModule,
statusPageModule,
userModule,
maintenanceWindowModule,
monitorModule,
notificationModule,
recoveryModule,
settingsModule,
});
await db.connect();
const networkService = new NetworkService({
axios,
got,
https,
jmespath,
GameDig,
ping,
logger,
http,
Docker,
net,
stringService,
settingsService,
});
const emailService = new EmailService(settingsService, fs, path, compile, mjml2html, nodemailer, logger);
const bufferService = new BufferService({ db, logger, envSettings });
const statusService = new StatusService({ db, logger, buffer: bufferService });
const notificationUtils = new NotificationUtils({
stringService,
emailService,
});
const notificationService = new NotificationService({
emailService,
db,
logger,
networkService,
stringService,
notificationUtils,
});
const errorService = new ErrorService();
const superSimpleQueueHelper = new SuperSimpleQueueHelper({
db,
logger,
networkService,
statusService,
notificationService,
});
const superSimpleQueue = await SuperSimpleQueue.create({
envSettings,
db,
logger,
helper: superSimpleQueueHelper,
});
// Business services
const userService = new UserService({
crypto,
db,
emailService,
settingsService,
logger,
stringService,
jwt,
errorService,
jobQueue: superSimpleQueue,
});
const checkService = new CheckService({
db,
settingsService,
stringService,
errorService,
});
const diagnosticService = new DiagnosticService();
const inviteService = new InviteService({
db,
settingsService,
emailService,
stringService,
errorService,
});
const maintenanceWindowService = new MaintenanceWindowService({
db,
settingsService,
stringService,
errorService,
});
const monitorService = new MonitorService({
db,
settingsService,
jobQueue: superSimpleQueue,
stringService,
emailService,
papaparse,
logger,
errorService,
games,
});
// V2 Services
const checkServiceV2 = new CheckServiceV2();
const inviteServiceV2 = new InviteServiceV2();
const maintenanceServiceV2 = new MaintenanceServiceV2();
const monitorStatsServiceV2 = new MonitorStatsServiceV2();
const notificationChannelServiceV2 = new NotificationChannelServiceV2();
const userServiceV2 = new UserServiceV2();
const discordServiceV2 = new DiscordServiceV2();
const emailServiceV2 = new EmailServiceV2(userServiceV2);
const slackServiceV2 = new SlackServiceV2();
const webhookServiceV2 = new WebhookServiceV2();
const networkServiceV2 = new NetworkServiceV2();
const statusServiceV2 = new StatusServiceV2();
const notificationServiceV2 = new NotificationServiceV2(userServiceV2);
const jobGeneratorV2 = new JobGeneratorV2(
networkServiceV2,
checkServiceV2,
monitorStatsServiceV2,
statusServiceV2,
notificationServiceV2,
maintenanceServiceV2
);
const jobQueueV2 = await JobQueueV2.create(jobGeneratorV2);
const authServiceV2 = new AuthServiceV2(jobQueueV2);
const monitorServiceV2 = new MonitorServiceV2(jobQueueV2);
const queueServiceV2 = new QueueServiceV2(jobQueueV2);
const services = {
//v1
settingsService,
translationService,
stringService,
db,
networkService,
emailService,
bufferService,
statusService,
notificationService,
jobQueue: superSimpleQueue,
userService,
checkService,
diagnosticService,
inviteService,
maintenanceWindowService,
monitorService,
errorService,
logger,
//v2
jobQueueV2,
authServiceV2,
checkServiceV2,
inviteServiceV2,
maintenanceServiceV2,
monitorServiceV2,
monitorStatsServiceV2,
notificationChannelServiceV2,
queueServiceV2,
userServiceV2,
discordServiceV2,
emailServiceV2,
slackServiceV2,
webhookServiceV2,
networkServiceV2,
statusServiceV2,
notificationServiceV2,
jobGeneratorV2,
};
Object.values(services).forEach((service) => {
ServiceRegistry.register(service.serviceName, service);
});
return services;
};
+165
View File
@@ -0,0 +1,165 @@
import { Request, Response, NextFunction } from "express";
import { encode, decode } from "@/utils/JWTUtils.js";
import AuthService from "@/services/business/AuthService.js";
import ApiError from "@/utils/ApiError.js";
import InviteService from "@/services/business/InviteService.js";
import { registerSchema } from "@/validation/index.js";
class AuthController {
private authService: AuthService;
private inviteService: InviteService;
constructor(authService: AuthService, inviteService: InviteService) {
this.authService = authService;
this.inviteService = inviteService;
}
register = async (req: Request, res: Response, next: NextFunction) => {
try {
const { email, firstName, lastName, password } = req.body;
if (!email || !firstName || !lastName || !password) {
throw new Error(
"Email, firstName, lastName, and password are required"
);
}
const { tokenizedUser, returnableUser } = await this.authService.register(
{
email,
firstName,
lastName,
password,
}
);
if (!returnableUser || !tokenizedUser) {
throw new ApiError("Registration failed");
}
const token = encode(tokenizedUser);
res.cookie("token", token, {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "strict",
maxAge: 7 * 24 * 60 * 60 * 1000, // 1 week
});
res.status(201).json({
message: "User created successfully",
data: returnableUser,
});
} catch (error) {
next(error);
}
};
registerWithInvite = async (
req: Request,
res: Response,
next: NextFunction
) => {
try {
const token = req.params.token;
if (!token) {
throw new ApiError("Invite token is required", 400);
}
const { invite } = await this.inviteService.get(token);
const { tokenizedUser, returnableUser } =
await this.authService.registerWithInvite(invite, req.body);
if (!tokenizedUser || !returnableUser) {
throw new Error("Registration failed");
}
await this.inviteService.delete(invite._id.toString());
const jwt = encode(tokenizedUser);
res.cookie("token", jwt, {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "strict",
maxAge: 7 * 24 * 60 * 60 * 1000, // 1 week
});
res.status(201).json({
message: "User registered successfully",
data: returnableUser,
});
} catch (error) {
next(error);
}
};
login = async (req: Request, res: Response, next: NextFunction) => {
try {
const { email, password } = req.body;
// Validation
if (!email || !password) {
return res
.status(400)
.json({ message: "Email and password are required" });
}
const { tokenizedUser, returnableUser } = await this.authService.login({
email,
password,
});
const token = encode(tokenizedUser);
res.cookie("token", token, {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "strict",
maxAge: 7 * 24 * 60 * 60 * 1000, // 1 week
});
res.status(200).json({
message: "Login successful",
data: returnableUser,
});
} catch (error) {
next(error);
}
};
logout = (req: Request, res: Response) => {
res.clearCookie("token", {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "strict",
});
res.status(200).json({ message: "Logout successful" });
};
me = async (req: Request, res: Response, next: NextFunction) => {
const user = req.user;
if (!user) {
throw new ApiError("Unauthorized", 401);
}
const returnableUser = await this.authService.me(user.sub);
res
.status(200)
.json({ message: "User retrieved successfully", data: returnableUser });
};
cleanup = async (req: Request, res: Response) => {
try {
await this.authService.cleanup();
res.status(200).json({ message: "Cleanup successful" });
} catch (error) {}
};
cleanMonitors = async (req: Request, res: Response) => {
try {
await this.authService.cleanMonitors();
res.status(200).json({ message: "Monitors cleanup successful" });
} catch (error) {
res.status(500).json({ message: "Internal server error" });
}
};
}
export default AuthController;
@@ -0,0 +1,58 @@
import { Request, Response, NextFunction } from "express";
import ApiError from "@/utils/ApiError.js";
import { CheckService } from "@/services/index.js";
export interface IChecksController {
getChecksByStatus: (req: Request, res: Response, next: NextFunction) => void;
}
class ChecksController implements IChecksController {
private checkService: CheckService;
constructor(checksService: CheckService) {
this.checkService = checksService;
}
getChecksByStatus = async (
req: Request,
res: Response,
next: NextFunction
) => {
try {
const {
status,
monitorId,
page = 0,
rowsPerPage = 10,
range,
} = req.validatedQuery;
const userContext = req.user;
if (!userContext) {
return res.status(401).json({ message: "Unauthorized" });
}
const teamId = userContext.currentTeamId;
if (!teamId) {
throw new ApiError("No team ID", 400);
}
const checks = await this.checkService.getChecksByStatus(
status,
teamId,
monitorId,
page,
rowsPerPage,
range
);
return res.status(200).json({
message: "Checks retrieved successfully",
data: checks,
});
} catch (error) {
next(error);
}
};
}
export default ChecksController;
@@ -0,0 +1,35 @@
import { Request, Response, NextFunction } from "express";
import type { IDiagnosticService } from "@/services/business/DiagnosticService.js";
import type { IJobData } from "@/services/infrastructure/JobQueue.js";
export interface IDiagnosticController {
getLogs: (req: Request, res: Response, next: NextFunction) => void;
getJobs(req: Request, res: Response, next: NextFunction): Promise<void>;
}
class DiagnosticController implements IDiagnosticController {
private diagnosticService: IDiagnosticService;
constructor(diagnosticService: IDiagnosticService) {
this.diagnosticService = diagnosticService;
}
getLogs = (req: Request, res: Response, next: NextFunction) => {
try {
const logs = this.diagnosticService.getLogs();
res.status(200).json({ message: "OK", data: logs });
} catch (error) {
next(error);
}
};
getJobs = async (req: Request, res: Response, next: NextFunction) => {
try {
const jobs = await this.diagnosticService.getJobs();
res.status(200).json({ message: "OK", data: jobs });
} catch (error) {
next(error);
}
};
}
export default DiagnosticController;
@@ -0,0 +1,112 @@
import { Request, Response, NextFunction } from "express";
import ApiError from "@/utils/ApiError.js";
import {
IncidentService,
NotificationService,
MonitorService,
} from "@/services/index.js";
import { getChildLogger } from "@/logger/Logger.js";
const logger = getChildLogger("IncidentController");
export interface IIncidentsController {
getIncidents: (req: Request, res: Response, next: NextFunction) => void;
resolveIncident: (req: Request, res: Response, next: NextFunction) => void;
}
class IncidentsController implements IIncidentsController {
private incidentService: IncidentService;
private notificationService: NotificationService;
private monitorService: MonitorService;
constructor(
incidentService: IncidentService,
notificationService: NotificationService,
monitorService: MonitorService
) {
this.incidentService = incidentService;
this.notificationService = notificationService;
this.monitorService = monitorService;
}
getIncidents = async (req: Request, res: Response, next: NextFunction) => {
try {
const userContext = req.user;
if (!userContext) {
return res.status(401).json({ message: "Unauthorized" });
}
const teamId = userContext.currentTeamId;
if (!teamId) {
throw new ApiError("No team ID", 400);
}
const { resolved, resolutionType, page, rowsPerPage, range, monitorId } =
req.validatedQuery;
const incidents = await this.incidentService.getAll(
teamId,
monitorId,
page,
rowsPerPage,
range,
resolved,
resolutionType
);
res.status(200).json({ message: "OK", data: incidents });
} catch (error) {
next(error);
}
};
resolveIncident = async (req: Request, res: Response, next: NextFunction) => {
try {
const userContext = req.user;
if (!userContext) {
return res.status(401).json({ message: "Unauthorized" });
}
const teamId = userContext.currentTeamId;
if (!teamId) {
throw new ApiError("No team ID", 400);
}
const { id } = req.params;
if (!id) {
throw new ApiError("No incident ID", 400);
}
const { resolutionNote } = req.body;
const resolved = await this.incidentService.resolve(
teamId,
id,
"manual",
undefined,
userContext.sub,
resolutionNote
);
if (!resolved) {
throw new ApiError("Incident not found or could not be resolved", 500);
}
// This should be best effort only, don't wait and don't fail
this.monitorService
.get(teamId, resolved.monitorId.toString())
.then((monitor) => {
this.notificationService.handleNotifications(monitor, resolved);
})
.catch((error) => {
logger.warn(error);
});
return res
.status(200)
.json({ message: "Incident resolved", data: resolved });
} catch (error) {
next(error);
}
};
}
export default IncidentsController;
@@ -0,0 +1,84 @@
import { Request, Response, NextFunction } from "express";
import InviteService from "@/services/business/InviteService.js";
import ApiError from "@/utils/ApiError.js";
class InviteController {
private inviteService: InviteService;
constructor(inviteService: InviteService) {
this.inviteService = inviteService;
}
create = async (req: Request, res: Response, next: NextFunction) => {
try {
const userContext = req.user;
if (!userContext) {
throw new ApiError("Unauthorized", 401);
}
const userId = userContext.sub;
if (!userId) {
throw new ApiError("No user ID in context", 400);
}
const orgId = userContext.orgId;
if (!orgId) {
throw new ApiError("No organization ID", 400);
}
const { email, orgRoleId, teamId, teamRoleId } = req.body;
const invite = await this.inviteService.create(
userId,
email,
orgId,
orgRoleId,
teamId,
teamRoleId
);
res.status(201).json({ message: "OK", data: invite });
} catch (error: any) {
next(error);
}
};
getAll = async (req: Request, res: Response, next: NextFunction) => {
try {
const invites = await this.inviteService.getAll();
res.status(200).json({
message: "OK",
data: invites,
});
} catch (error) {
next(error);
}
};
get = async (req: Request, res: Response, next: NextFunction) => {
try {
const token = req.params.id;
if (!token) {
return res.status(400).json({ message: "Token parameter is required" });
}
const result = await this.inviteService.get(token);
res.status(200).json({ message: "OK", data: result });
} catch (error) {
next(error);
}
};
delete = async (req: Request, res: Response, next: NextFunction) => {
try {
const id = req.params.id;
if (!id) {
return res.status(400).json({ message: "ID parameter is required" });
}
await this.inviteService.delete(id);
res.status(200).json({ message: "OK" });
} catch (error: any) {
next(error);
}
};
}
export default InviteController;
@@ -0,0 +1,150 @@
import { Request, Response, NextFunction } from "express";
import MaintenanceService from "@/services/business/MaintenanceService.js";
import ApiError from "@/utils/ApiError.js";
class MaintenanceController {
private maintenanceService: MaintenanceService;
constructor(maintenanceService: MaintenanceService) {
this.maintenanceService = maintenanceService;
}
create = async (req: Request, res: Response, next: NextFunction) => {
try {
const tokenizedUser = req.user;
if (!tokenizedUser) {
return res.status(401).json({ message: "Unauthorized" });
}
const maintenance = await this.maintenanceService.create(
tokenizedUser,
req.body
);
res.status(201).json({ message: "OK", data: maintenance });
} catch (error) {
next(error);
}
};
getAll = async (req: Request, res: Response, next: NextFunction) => {
try {
const tokenizedUser = req.user;
if (!tokenizedUser) {
return res.status(401).json({ message: "Unauthorized" });
}
const teamId = tokenizedUser.currentTeamId;
if (!teamId) {
throw new ApiError("No team ID", 400);
}
const maintenances = await this.maintenanceService.getAll(teamId);
res.status(200).json({
message: "OK",
data: maintenances,
});
} catch (error) {
next(error);
}
};
toggleActive = async (req: Request, res: Response, next: NextFunction) => {
try {
const tokenizedUser = req.user;
if (!tokenizedUser) {
return res.status(401).json({ message: "Unauthorized" });
}
const teamId = tokenizedUser.currentTeamId;
if (!teamId) {
throw new ApiError("No team ID", 400);
}
const id = req.params.id;
if (!id) {
return res.status(400).json({ message: "ID parameter is required" });
}
const maintenance = await this.maintenanceService.toggleActive(
teamId,
tokenizedUser,
id
);
res.status(200).json({ message: "OK", data: maintenance });
} catch (error) {
next(error);
}
};
update = async (req: Request, res: Response, next: NextFunction) => {
try {
const tokenizedUser = req.user;
if (!tokenizedUser) {
return res.status(401).json({ message: "Unauthorized" });
}
const teamId = tokenizedUser.currentTeamId;
if (!teamId) {
throw new ApiError("No team ID", 400);
}
const id = req.params.id;
if (!id) {
return res.status(400).json({ message: "ID parameter is required" });
}
const updatedMaintenance = await this.maintenanceService.update(
teamId,
tokenizedUser,
id,
req.body
);
res.status(200).json({ message: "OK", data: updatedMaintenance });
} catch (error) {
next(error);
}
};
get = async (req: Request, res: Response, next: NextFunction) => {
try {
const tokenizedUser = req.user;
if (!tokenizedUser) {
return res.status(401).json({ message: "Unauthorized" });
}
const teamId = tokenizedUser.currentTeamId;
if (!teamId) {
throw new ApiError("No team ID", 400);
}
const id = req.params.id;
if (!id) {
return res.status(400).json({ message: "ID parameter is required" });
}
const maintenance = await this.maintenanceService.get(teamId, id);
res.status(200).json({ message: "OK", data: maintenance });
} catch (error) {
next(error);
}
};
delete = async (req: Request, res: Response, next: NextFunction) => {
try {
const tokenizedUser = req.user;
if (!tokenizedUser) {
return res.status(401).json({ message: "Unauthorized" });
}
const teamId = tokenizedUser.currentTeamId;
if (!teamId) {
throw new ApiError("No team ID", 400);
}
const id = req.params.id;
if (!id) {
return res.status(400).json({ message: "ID parameter is required" });
}
await this.maintenanceService.delete(teamId, id);
res.status(200).json({ message: "OK" });
} catch (error) {
next(error);
}
};
}
export default MaintenanceController;
+315
View File
@@ -0,0 +1,315 @@
import { Request, Response, NextFunction } from "express";
import ApiError from "@/utils/ApiError.js";
import { MonitorType } from "@/db/models/monitors/Monitor.js";
import {
MonitorService,
CheckService,
NotificationService,
} from "@/services/index.js";
export interface IMonitorController {
create(req: Request, res: Response, next: NextFunction): Promise<void>;
getAll(req: Request, res: Response, next: NextFunction): Promise<void>;
getChecks(req: Request, res: Response, next: NextFunction): Promise<void>;
toggleActive(req: Request, res: Response, next: NextFunction): Promise<void>;
get(req: Request, res: Response, next: NextFunction): Promise<void>;
update(req: Request, res: Response, next: NextFunction): Promise<void>;
delete(req: Request, res: Response, next: NextFunction): Promise<void>;
testNotifications(
req: Request,
res: Response,
next: NextFunction
): Promise<void>;
}
class MonitorController {
private monitorService: MonitorService;
private checkService: CheckService;
private notificationService: NotificationService;
constructor(
monitorService: MonitorService,
checkService: CheckService,
notificationService: NotificationService
) {
this.monitorService = monitorService;
this.checkService = checkService;
this.notificationService = notificationService;
}
create = async (req: Request, res: Response, next: NextFunction) => {
try {
const userContext = req.user;
if (!userContext) {
return res.status(401).json({ message: "Unauthorized" });
}
if (!userContext.currentTeamId) {
throw new ApiError("No team ID", 400);
}
const monitor = await this.monitorService.create(
userContext.orgId,
userContext.sub,
userContext.currentTeamId,
req.body
);
res.status(201).json({
message: "Monitor created successfully",
data: monitor,
});
} catch (error) {
next(error);
}
};
getAll = async (req: Request, res: Response, next: NextFunction) => {
try {
const userContext = req.user;
if (!userContext) {
return res.status(401).json({ message: "Unauthorized" });
}
const teamId = userContext.currentTeamId;
if (!teamId) {
throw new ApiError("No team ID", 400);
}
let result;
if (req.validatedQuery.embedChecks === true) {
const page = req.validatedQuery.page || 0;
const rowsPerPage = req.validatedQuery.rowsPerPage || 10;
const type = req.validatedQuery.type;
result = await this.monitorService.getAllEmbedChecks(
teamId,
page,
rowsPerPage,
type
);
} else {
result = await this.monitorService.getAll(teamId);
}
res.status(200).json({
message: "Monitors retrieved successfully",
data: result,
});
} catch (error) {
next(error);
}
};
getChecks = async (req: Request, res: Response, next: NextFunction) => {
try {
const userContext = req.user;
if (!userContext) {
return res.status(401).json({ message: "Unauthorized" });
}
const teamId = userContext.currentTeamId;
if (!teamId) {
throw new ApiError("No team ID", 400);
}
const monitorId = req.params.id;
if (!monitorId) {
throw new ApiError("Monitor ID is required", 400);
}
const monitor = await this.monitorService.get(teamId, monitorId);
if (!monitor) {
throw new ApiError("Monitor not found", 404);
}
const page = Number(req.validatedQuery.page);
const rowsPerPage = Number(req.validatedQuery.rowsPerPage);
const { count, checks } = await this.checkService.getMonitorChecks(
monitorId,
page,
rowsPerPage
);
res.status(200).json({
message: "Checks retrieved successfully",
data: { count, checks },
});
} catch (error) {
next(error);
}
};
toggleActive = async (req: Request, res: Response, next: NextFunction) => {
try {
const userContext = req.user;
if (!userContext) {
return res.status(401).json({ message: "Unauthorized" });
}
const teamId = userContext.currentTeamId;
if (!teamId) {
throw new ApiError("No team ID", 400);
}
const monitorId = req.params.id;
if (!monitorId) {
throw new ApiError("Monitor ID is required", 400);
}
const monitor = await this.monitorService.toggleActive(
userContext.sub,
teamId,
monitorId
);
const paused = monitor.isActive ? "resumed" : "paused";
res.status(200).json({
message: `Monitor ${paused} successfully`,
data: monitor,
});
} catch (error) {
next(error);
}
};
get = async (req: Request, res: Response, next: NextFunction) => {
try {
const userContext = req.user;
if (!userContext) {
return res.status(401).json({ message: "Unauthorized" });
}
const teamId = userContext.currentTeamId;
if (!teamId) {
throw new ApiError("No team ID", 400);
}
const monitorId = req.params.id;
if (!monitorId) {
throw new ApiError("Monitor ID is required", 400);
}
let monitor;
const status = req.query.status;
if (status && typeof status !== "string") {
throw new ApiError("Status query parameter must be a string", 400);
}
if (req.query.embedChecks === "true") {
const range = req.query.range;
if (!range || typeof range !== "string")
throw new ApiError("Range query parameter is required", 400);
monitor = await this.monitorService.getEmbedChecks(
teamId,
monitorId,
range,
status
);
} else {
monitor = await this.monitorService.get(teamId, monitorId);
}
res.status(200).json({
message: "Monitor retrieved successfully",
data: monitor,
});
} catch (error) {
next(error);
}
};
update = async (req: Request, res: Response, next: NextFunction) => {
try {
const userContext = req.user;
if (!userContext) {
return res.status(401).json({ message: "Unauthorized" });
}
const teamId = userContext.currentTeamId;
if (!teamId) {
throw new ApiError("No team ID", 400);
}
const monitorId = req.params.id;
if (!monitorId) {
throw new ApiError("Monitor ID is required", 400);
}
const monitor = await this.monitorService.update(
userContext.sub,
teamId,
monitorId,
req.body
);
res.status(200).json({
message: "Monitor updated successfully",
data: monitor,
});
} catch (error) {
next(error);
}
};
delete = async (req: Request, res: Response, next: NextFunction) => {
try {
const tokenizedUser = req.user;
if (!tokenizedUser) {
return res.status(401).json({ message: "Unauthorized" });
}
const teamId = tokenizedUser.currentTeamId;
if (!teamId) {
throw new ApiError("No team ID", 400);
}
const id = req.params.id;
if (!id) {
throw new ApiError("Monitor ID is required", 400);
}
await this.monitorService.delete(teamId, id);
res.status(200).json({
message: "Monitor deleted successfully",
});
} catch (error) {
next(error);
}
};
testNotifications = async (
req: Request,
res: Response,
next: NextFunction
) => {
try {
const tokenizedUser = req.user;
if (!tokenizedUser) {
return res.status(401).json({ message: "Unauthorized" });
}
const teamId = tokenizedUser.currentTeamId;
if (!teamId) {
throw new ApiError("No team ID", 400);
}
const monitorId = req.params.id;
if (!monitorId) {
throw new ApiError("Monitor ID is required", 400);
}
const results = await this.notificationService.testNotificationChannels(
monitorId,
teamId
);
return res.status(200).json({
message: "Notification test sent successfully",
data: results,
});
} catch (error) {
next(error);
}
};
}
export default MonitorController;
@@ -0,0 +1,178 @@
import { Request, Response, NextFunction } from "express";
import NotificationChannelService from "@/services/business/NotificationChannelService.js";
import { NotificationService } from "@/services/index.js";
import ApiError from "@/utils/ApiError.js";
class NotificationChannelController {
private notificationChannelService: NotificationChannelService;
private notificationService: NotificationService;
constructor(
notificationChannelService: NotificationChannelService,
notificationService: NotificationService
) {
this.notificationChannelService = notificationChannelService;
this.notificationService = notificationService;
}
create = async (req: Request, res: Response, next: NextFunction) => {
try {
const tokenizedUser = req.user;
if (!tokenizedUser) {
return res.status(401).json({ message: "Unauthorized" });
}
const channel = await this.notificationChannelService.create(
tokenizedUser,
req.body
);
res.status(201).json({ message: "OK", data: channel });
} catch (error) {
next(error);
}
};
getAll = async (req: Request, res: Response, next: NextFunction) => {
try {
const tokenizedUser = req.user;
if (!tokenizedUser) {
return res.status(401).json({ message: "Unauthorized" });
}
const teamId = tokenizedUser.currentTeamId;
if (!teamId) {
throw new ApiError("No team ID", 400);
}
const notificationChannels = await this.notificationChannelService.getAll(
teamId
);
res.status(200).json({
message: "OK",
data: notificationChannels,
});
} catch (error) {
next(error);
}
};
toggleActive = async (req: Request, res: Response, next: NextFunction) => {
try {
const tokenizedUser = req.user;
if (!tokenizedUser) {
return res.status(401).json({ message: "Unauthorized" });
}
const teamId = tokenizedUser.currentTeamId;
if (!teamId) {
throw new ApiError("No team ID", 400);
}
const id = req.params.id;
if (!id) {
return res.status(400).json({ message: "ID parameter is required" });
}
const notificationChannel =
await this.notificationChannelService.toggleActive(
teamId,
tokenizedUser,
id
);
res.status(200).json({ message: "OK", data: notificationChannel });
} catch (error) {
next(error);
}
};
update = async (req: Request, res: Response, next: NextFunction) => {
try {
const tokenizedUser = req.user;
if (!tokenizedUser) {
return res.status(401).json({ message: "Unauthorized" });
}
const teamId = tokenizedUser.currentTeamId;
if (!teamId) {
throw new ApiError("No team ID", 400);
}
const id = req.params.id;
if (!id) {
return res.status(400).json({ message: "ID parameter is required" });
}
const updatedChannel = await this.notificationChannelService.update(
teamId,
tokenizedUser,
id,
req.body
);
res.status(200).json({ message: "OK", data: updatedChannel });
} catch (error) {
next(error);
}
};
get = async (req: Request, res: Response, next: NextFunction) => {
try {
const tokenizedUser = req.user;
if (!tokenizedUser) {
return res.status(401).json({ message: "Unauthorized" });
}
const teamId = tokenizedUser.currentTeamId;
if (!teamId) {
throw new ApiError("No team ID", 400);
}
const id = req.params.id;
if (!id) {
return res.status(400).json({ message: "ID parameter is required" });
}
const notificationChannel = await this.notificationChannelService.get(
teamId,
id
);
res.status(200).json({ message: "OK", data: notificationChannel });
} catch (error) {
next(error);
}
};
delete = async (req: Request, res: Response, next: NextFunction) => {
try {
const tokenizedUser = req.user;
if (!tokenizedUser) {
return res.status(401).json({ message: "Unauthorized" });
}
const teamId = tokenizedUser.currentTeamId;
if (!teamId) {
throw new ApiError("No team ID", 400);
}
const id = req.params.id;
if (!id) {
return res.status(400).json({ message: "ID parameter is required" });
}
await this.notificationChannelService.delete(teamId, id);
res.status(200).json({ message: "OK" });
} catch (error) {
next(error);
}
};
test = async (req: Request, res: Response, next: NextFunction) => {
try {
const notificationChannel = req.body;
const success = await this.notificationService.testNotificationChannel(
notificationChannel
);
if (success) {
res.status(200).json({ message: "OK" });
} else {
throw new ApiError("Failed to send", 500);
}
} catch (error) {
next(error);
}
};
}
export default NotificationChannelController;
@@ -0,0 +1,69 @@
import { Request, Response, NextFunction } from "express";
import type { IUser } from "@/db/models/index.js";
import { UserService } from "@/services/index.js";
import ApiError from "@/utils/ApiError.js";
export interface IProfileController {
get(req: Request, res: Response, next: NextFunction): Promise<void>;
update(req: Request, res: Response, next: NextFunction): Promise<void>;
}
class ProfileController {
private userService: UserService;
constructor(userService: UserService) {
this.userService = userService;
}
private parseUser(user: IUser): Partial<IUser> {
return {
email: user.email,
firstName: user.firstName,
lastName: user.lastName,
};
}
get = async (req: Request, res: Response, next: NextFunction) => {
try {
const userContext = req.user;
if (!userContext) {
return res.status(401).json({ message: "Unauthorized" });
}
// TODO convert to get by id
const user = await this.userService.get(userContext.email);
if (!user) {
throw new ApiError("User not found", 404);
}
res.status(200).json({
message: "OK",
data: this.parseUser(user),
});
} catch (error) {
next(error);
}
};
update = async (req: Request, res: Response, next: NextFunction) => {
try {
const userContext = req.user;
if (!userContext) {
return res.status(401).json({ message: "Unauthorized" });
}
const updateData = req.body;
const updatedUser = await this.userService.update(
userContext.sub,
updateData
);
res
.status(200)
.json({ message: "OK", data: this.parseUser(updatedUser) });
} catch (error: any) {
next(error);
}
};
}
export default ProfileController;
+29
View File
@@ -0,0 +1,29 @@
import { Request, Response, NextFunction } from "express";
import QueueService from "@/services/business/QueueService.js";
class QueueController {
private queueService: QueueService;
constructor(queueService: QueueService) {
this.queueService = queueService;
}
getJobs = async (req: Request, res: Response, next: NextFunction) => {
try {
const jobs = await this.queueService.getJobs();
res.status(200).json({ message: "ok", data: jobs });
} catch (error) {
next(error);
}
};
getMetrics = async (req: Request, res: Response, next: NextFunction) => {
const metrics = await this.queueService.getMetrics();
res.status(200).json({ message: "ok", data: metrics });
};
flush = async (req: Request, res: Response, next: NextFunction) => {
const result = await this.queueService.flush();
res.status(200).json({ message: "ok", flushed: result });
};
}
export default QueueController;
@@ -0,0 +1,109 @@
import { Request, Response, NextFunction } from "express";
import {
AuthService,
RecoveryService,
EmailService,
} from "@/services/index.js";
import ApiError from "@/utils/ApiError.js";
import { User } from "@/db/models/index.js";
import { config } from "@/config/index.js";
import { encode } from "@/utils/JWTUtils.js";
import { getChildLogger } from "@/logger/Logger.js";
const logger = getChildLogger("RecoveryController");
export interface IRecoveryController {
requestRecovery: (
req: Request,
res: Response,
next: NextFunction
) => Promise<void>;
resetPassword: (
req: Request,
res: Response,
next: NextFunction
) => Promise<void>;
}
class RecoveryController implements IRecoveryController {
private recoveryService: RecoveryService;
private authService: AuthService;
private emailService: EmailService;
constructor(
recoveryService: RecoveryService,
authService: AuthService,
emailService: EmailService
) {
this.recoveryService = recoveryService;
this.authService = authService;
this.emailService = emailService;
}
requestRecovery = async (req: Request, res: Response, next: NextFunction) => {
try {
const { email } = req.body;
const user = await User.findOne({ email }).lean();
if (user) {
try {
const recoveryToken = await this.recoveryService.create(user._id);
// Don't wait for email to be sent
this.emailService
.sendGeneric(
user.email,
"Password Recovery",
`Your recovery link is: ${config.ORIGIN}/recovery/${recoveryToken}`
)
.catch((error) => {
logger.error(error);
});
} catch (error) {
// These should not be propagated to the user
logger.error(error);
}
}
res.status(200).json({ message: "OK" });
} catch (error: any) {
next(error);
}
};
resetPassword = async (req: Request, res: Response, next: NextFunction) => {
try {
const { token, password } = req.body;
const recoveryToken = await this.recoveryService.get(token);
if (!recoveryToken) {
throw new ApiError("Invalid recovery token", 400);
}
await this.authService.changePassword(recoveryToken.userId, password);
await this.recoveryService.delete(recoveryToken._id);
const user = await User.findById(recoveryToken.userId);
if (!user) {
throw new ApiError("User not found", 404);
}
const { tokenizedUser, returnableUser } = await this.authService.login({
email: user.email,
password,
});
const userToken = encode(tokenizedUser);
res.cookie("token", userToken, {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "strict",
maxAge: 7 * 24 * 60 * 60 * 1000, // 1 week
});
res.status(200).json({
message: "Reset successful",
data: returnableUser,
});
} catch (error: any) {
next(error);
}
};
}
export default RecoveryController;
+80
View File
@@ -0,0 +1,80 @@
import { Request, Response, NextFunction } from "express";
import ApiError from "@/utils/ApiError.js";
import RoleService from "@/services/business/RoleService.js";
export interface IRoleController {
getAll: (req: Request, res: Response, next: NextFunction) => void;
getTeam: (req: Request, res: Response, next: NextFunction) => void;
get: (req: Request, res: Response, next: NextFunction) => void;
}
class RoleController implements IRoleController {
private roleService: RoleService;
constructor(roleService: RoleService) {
this.roleService = roleService;
}
getAll = async (req: Request, res: Response, next: NextFunction) => {
try {
const tokenizedUser = req.user;
if (!tokenizedUser) {
return res.status(401).json({ message: "Unauthorized" });
}
if (!tokenizedUser.orgId) {
throw new ApiError("No organization ID", 400);
}
const type = req.query.type;
const roles = await this.roleService.getAll(
tokenizedUser.orgId,
type as string
);
return res.status(200).json({
message: "Roles retrieved successfully",
data: roles,
});
} catch (error) {
next(error);
}
};
getTeam = async (req: Request, res: Response, next: NextFunction) => {
try {
const userContext = req.user;
if (!userContext) {
throw new ApiError("Unauthorized", 401);
}
const orgId = userContext.orgId;
if (!orgId) {
throw new ApiError("No organization ID", 400);
}
const teamId = req.params.id;
if (!teamId) {
throw new ApiError("No team ID", 400);
}
const roles = await this.roleService.getTeam(orgId, teamId);
return res.status(200).json({
message: "Roles retrieved successfully",
data: roles,
});
} catch (error) {
next(error);
}
};
get = async (req: Request, res: Response, next: NextFunction) => {
try {
} catch (error) {
next(error);
}
};
}
export default RoleController;
@@ -0,0 +1,137 @@
import { Request, Response, NextFunction } from "express";
import StatusPageService from "@/services/business/StatusPageService.js";
import ApiError from "@/utils/ApiError.js";
class StatusPageController {
private statusPageService: StatusPageService;
constructor(statusPageService: StatusPageService) {
this.statusPageService = statusPageService;
}
create = async (req: Request, res: Response, next: NextFunction) => {
try {
const userContext = req.user;
if (!userContext) {
return res.status(401).json({ message: "Unauthorized" });
}
const statusPage = await this.statusPageService.create(
userContext,
req.body
);
res.status(201).json({ message: "OK", data: statusPage });
} catch (error) {
next(error);
}
};
getAll = async (req: Request, res: Response, next: NextFunction) => {
try {
const userContext = req.user;
if (!userContext) {
return res.status(401).json({ message: "Unauthorized" });
}
const teamId = userContext.currentTeamId;
if (!teamId) {
throw new ApiError("No team ID", 400);
}
const statusPages = await this.statusPageService.getAll(teamId);
res.status(200).json({
message: "OK",
data: statusPages,
});
} catch (error) {
next(error);
}
};
update = async (req: Request, res: Response, next: NextFunction) => {
try {
const userContext = req.user;
if (!userContext) {
return res.status(401).json({ message: "Unauthorized" });
}
const teamId = userContext.currentTeamId;
if (!teamId) {
throw new ApiError("No team ID", 400);
}
const id = req.params.id;
if (!id) {
return res.status(400).json({ message: "ID parameter is required" });
}
const updatedChannel = await this.statusPageService.update(
teamId,
userContext,
id,
req.body
);
res.status(200).json({ message: "OK", data: updatedChannel });
} catch (error) {
next(error);
}
};
get = async (req: Request, res: Response, next: NextFunction) => {
try {
const userContext = req.user;
if (!userContext) {
return res.status(401).json({ message: "Unauthorized" });
}
const teamId = userContext.currentTeamId;
if (!teamId) {
throw new ApiError("No team ID", 400);
}
const id = req.params.id;
if (!id) {
return res.status(400).json({ message: "ID parameter is required" });
}
const statusPage = await this.statusPageService.get(teamId, id);
res.status(200).json({ message: "OK", data: statusPage });
} catch (error) {
next(error);
}
};
getPublic = async (req: Request, res: Response, next: NextFunction) => {
try {
const url = req.params.url;
if (!url) {
throw new ApiError("No URL parameter", 400);
}
const statusPage = await this.statusPageService.getPublic(url);
res.status(200).json({ message: "OK", data: statusPage });
} catch (error) {
next(error);
}
};
delete = async (req: Request, res: Response, next: NextFunction) => {
try {
const userContext = req.user;
if (!userContext) {
return res.status(401).json({ message: "Unauthorized" });
}
const teamId = userContext.currentTeamId;
if (!teamId) {
throw new ApiError("No team ID", 400);
}
const id = req.params.id;
if (!id) {
return res.status(400).json({ message: "ID parameter is required" });
}
await this.statusPageService.delete(teamId, id);
res.status(200).json({ message: "OK" });
} catch (error) {
next(error);
}
};
}
export default StatusPageController;
+178
View File
@@ -0,0 +1,178 @@
import { Request, Response, NextFunction } from "express";
import ApiError from "@/utils/ApiError.js";
import TeamService from "@/services/business/TeamService.js";
export interface ITeamController {
create: (req: Request, res: Response, next: NextFunction) => void;
getOrg: (req: Request, res: Response, next: NextFunction) => void;
getJoined: (req: Request, res: Response, next: NextFunction) => void;
get: (req: Request, res: Response, next: NextFunction) => void;
update: (req: Request, res: Response, next: NextFunction) => void;
delete: (req: Request, res: Response, next: NextFunction) => void;
}
class TeamController implements ITeamController {
private teamService: TeamService;
constructor(teamService: TeamService) {
this.teamService = teamService;
}
create = async (req: Request, res: Response, next: NextFunction) => {
try {
const userContext = req.user;
if (!userContext) {
return res.status(401).json({ message: "Unauthorized" });
}
const orgId = userContext.orgId;
if (!orgId) {
throw new ApiError("No organization ID", 400);
}
const userId = userContext.sub;
if (!userId) {
throw new ApiError("No user ID", 400);
}
const roleId = req.body.roleId;
if (!roleId) {
throw new ApiError("No role ID", 400);
}
await this.teamService.create(orgId, userId, req.body, roleId);
return res.status(201).json({
message: "Team created successfully",
});
} catch (error) {
next(error);
}
};
getOrg = async (req: Request, res: Response, next: NextFunction) => {
try {
const userContext = req.user;
if (!userContext) {
return res.status(401).json({ message: "Unauthorized" });
}
const userId = userContext.sub;
if (!userId) {
throw new ApiError("No user ID", 400);
}
const orgId = userContext.orgId;
if (!orgId) {
throw new ApiError("No organization ID", 400);
}
const teams = await this.teamService.getOrg(orgId);
return res
.status(200)
.json({ message: "Teams retrieved successfully", data: teams });
} catch (error) {
next(error);
}
};
getJoined = async (req: Request, res: Response, next: NextFunction) => {
try {
const userContext = req.user;
if (!userContext) {
return res.status(401).json({ message: "Unauthorized" });
}
const userId = userContext.sub;
if (!userId) {
throw new ApiError("No user ID", 400);
}
const orgId = userContext.orgId;
if (!orgId) {
throw new ApiError("No organization ID", 400);
}
const teams = await this.teamService.getJoined(orgId, userId);
return res
.status(200)
.json({ message: "Teams retrieved successfully", data: teams });
} catch (error) {
next(error);
}
};
get = async (req: Request, res: Response, next: NextFunction) => {
try {
const userContext = req.user;
if (!userContext) {
return res.status(401).json({ message: "Unauthorized" });
}
const teamId = req.params.id;
if (!teamId) {
throw new ApiError("No team ID", 400);
}
const orgId = userContext.orgId;
if (!orgId) {
throw new ApiError("No organization ID", 400);
}
const team = await this.teamService.get(teamId, orgId);
return res
.status(200)
.json({ message: "Team retrieved successfully", data: team });
} catch (error) {
next(error);
}
};
update = async (req: Request, res: Response, next: NextFunction) => {
try {
const userContext = req.user;
if (!userContext) {
return res.status(401).json({ message: "Unauthorized" });
}
const id = req.params.id;
if (!id) {
throw new ApiError("Monitor ID is required", 400);
}
const result = await this.teamService.update(userContext, id, req.body);
return res.status(200).json({
message: "Team updated successfully",
data: result,
});
} catch (error) {
next(error);
}
};
delete = async (req: Request, res: Response, next: NextFunction) => {
try {
const teamId = req.params.id;
if (!teamId) {
throw new ApiError("No team ID", 400);
}
const userContext = req.user;
if (!userContext) {
return res.status(401).json({ message: "Unauthorized" });
}
const success = await this.teamService.delete(userContext.orgId, teamId);
if (!success) {
throw new ApiError("Failed to delete team", 500);
}
return res.status(200).json({
message: "Team deleted successfully",
});
} catch (error) {
next(error);
}
};
}
export default TeamController;
@@ -0,0 +1,165 @@
import { Request, Response, NextFunction } from "express";
import ApiError from "@/utils/ApiError.js";
import { TeamMemberService } from "@/services/index.js";
import { invalidateCachesForUser } from "@/middleware/AddUserContext.js";
export interface ITeamMemberController {
create: (req: Request, res: Response, next: NextFunction) => void;
getAll: (req: Request, res: Response, next: NextFunction) => void;
get: (req: Request, res: Response, next: NextFunction) => void;
update: (req: Request, res: Response, next: NextFunction) => void;
delete: (req: Request, res: Response, next: NextFunction) => void;
}
class TeamMemberController implements ITeamMemberController {
private teamMemberService: TeamMemberService;
constructor(teamMemberService: TeamMemberService) {
this.teamMemberService = teamMemberService;
}
create = async (req: Request, res: Response, next: NextFunction) => {
try {
const userContext = req.user;
if (!userContext) {
throw new ApiError("Unauthorized", 401);
}
const orgId = userContext.orgId;
if (!orgId) {
throw new ApiError("No organization ID", 400);
}
const tm = await this.teamMemberService.create(orgId, req.body);
return res.status(201).json({
message: "Team member created successfully",
data: tm,
});
} catch (error) {
next(error);
}
};
getAll = async (req: Request, res: Response, next: NextFunction) => {
try {
const userContext = req.user;
if (!userContext) {
throw new ApiError("Unauthorized", 401);
}
const orgId = userContext.orgId;
if (!orgId) {
throw new ApiError("No organization ID", 400);
}
const teamId = req.query.teamId as string | undefined;
const type = req.query.type as string;
const teamMembers = await this.teamMemberService.getAll(
orgId,
teamId,
type
);
return res.status(200).json({
message: "Team members retrieved successfully",
data: teamMembers,
});
} catch (error) {
next(error);
}
};
get = async (req: Request, res: Response, next: NextFunction) => {
try {
const userContext = req.user;
if (!userContext) {
throw new ApiError("Unauthorized", 401);
}
const orgId = userContext.orgId;
if (!orgId) {
throw new ApiError("No organization ID", 400);
}
const teamMemberId = req.params.id;
if (!teamMemberId) {
throw new ApiError("No team member ID", 400);
}
const teamMember = await this.teamMemberService.get(orgId, teamMemberId);
return res
.status(200)
.json({ message: "Team retrieved successfully", data: teamMember });
} catch (error) {
next(error);
}
};
update = async (req: Request, res: Response, next: NextFunction) => {
try {
const userContext = req.user;
if (!userContext) {
throw new ApiError("Unauthorized", 401);
}
const orgId = userContext.orgId;
if (!orgId) {
throw new ApiError("No organization ID", 400);
}
const { roleId } = req.body;
if (!roleId) {
throw new ApiError("No role ID provided", 400);
}
const teamMembershipId = req.params.id as string;
if (!teamMembershipId) {
throw new ApiError("No team membership ID provided", 400);
}
await this.teamMemberService.update(orgId, teamMembershipId, roleId);
return res.status(200).json({
message: "Team updated successfully",
data: null,
});
} catch (error) {
next(error);
}
};
delete = async (req: Request, res: Response, next: NextFunction) => {
try {
const userContext = req.user;
if (!userContext) {
throw new ApiError("Unauthorized", 401);
}
const orgId = userContext.orgId;
if (!orgId) {
throw new ApiError("No organization ID", 400);
}
const teamMemberId = req.params.id;
if (!req.params.id) {
throw new ApiError("No team member ID", 400);
}
const deleted = await this.teamMemberService.delete(orgId, req.params.id);
if (!deleted) {
throw new ApiError("Failed to delete team member", 500);
}
return res.status(200).json({
message: "Team deleted successfully",
});
} catch (error) {
next(error);
}
};
}
export default TeamMemberController;
+15
View File
@@ -0,0 +1,15 @@
export { default as AuthController } from "./AuthController.js";
export { default as InviteController } from "./InviteController.js";
export { default as MaintenanceController } from "./MaintenanceController.js";
export { default as MonitorController } from "./MonitorController.js";
export { default as NotificationChannelController } from "./NotificationChannelController.js";
export { default as QueueController } from "./QueueController.js";
export { default as TeamController } from "./TeamController.js";
export { default as RoleController } from "./RoleController.js";
export { default as TeamMemberController } from "./TeamMemberController.js";
export { default as ChecksController } from "./ChecksController.js";
export { default as StatusPageController } from "./StatusPageController.js";
export { default as DiagnosticController } from "./DiagnosticController.js";
export { default as RecoveryController } from "./RecoveryController.js";
export { default as ProfileController } from "./ProfileController.js";
export { default as IncidentsController } from "./IncidentController.js";
@@ -1,77 +0,0 @@
import { createAnnouncementValidation } from "../../validation/joi.js";
import BaseController from "./baseController.js";
const SERVICE_NAME = "announcementController";
/**
* Controller for managing announcements in the system.
* This class handles the creation of new announcements.
*
* @class AnnouncementController
*/
class AnnouncementController extends BaseController {
static SERVICE_NAME = SERVICE_NAME;
constructor(commonDependencies) {
super(commonDependencies);
this.createAnnouncement = this.createAnnouncement.bind(this);
this.getAnnouncement = this.getAnnouncement.bind(this);
}
get serviceName() {
return AnnouncementController.SERVICE_NAME;
}
/**
* Handles the creation of a new announcement.
*
* @async
* @param {Object} req - The request object, containing the announcement data in the body.
* @param {Object} res - The response object used to send the result back to the client.
* @param {Function} next - The next middleware function in the stack for error handling.
*
* @returns {Promise<void>} A promise that resolves once the response is sent.
*/
createAnnouncement = asyncHandler(
async (req, res, next) => {
await createAnnouncementValidation.validateAsync(req.body);
const { title, message } = req.body;
const announcementData = {
title: title.trim(),
message: message.trim(),
userId: req.user._id,
};
const newAnnouncement = await this.db.createAnnouncement(announcementData);
return res.success({
msg: this.stringService.createAnnouncement,
data: newAnnouncement,
});
},
SERVICE_NAME,
"createAnnouncement"
);
/**
* Handles retrieving announcements with pagination.
*
* @async
* @param {Object} res - The response object used to send the result back to the client.
* - `data`: The list of announcements to be sent back to the client.
* - `msg`: A message about the success of the request.
* @param {Function} next - The next middleware function in the stack for error handling.
*/
getAnnouncement = asyncHandler(
async (req, res, next) => {
const allAnnouncements = await this.db.getAnnouncements();
return res.success({
msg: this.stringService.getAnnouncement,
data: allAnnouncements,
});
},
SERVICE_NAME,
"getAnnouncement"
);
}
export default AnnouncementController;
-478
View File
@@ -1,478 +0,0 @@
import BaseController from "./baseController.js";
import {
registrationBodyValidation,
loginValidation,
editUserBodyValidation,
recoveryValidation,
recoveryTokenBodyValidation,
newPasswordValidation,
getUserByIdParamValidation,
editUserByIdParamValidation,
editUserByIdBodyValidation,
editSuperadminUserByIdBodyValidation,
editUserPasswordByIdBodyValidation,
} from "../../validation/joi.js";
const SERVICE_NAME = "authController";
/**
* Authentication Controller
*
* Handles all authentication-related HTTP requests including user registration,
* login, password recovery, and user management operations.
*
* @class AuthController
* @description Manages user authentication and authorization operations
*/
class AuthController extends BaseController {
static SERVICE_NAME = SERVICE_NAME;
/**
* Creates an instance of AuthController.
*
* @param {Object} commonDependencies - Common dependencies injected into the controller
* @param {Object} dependencies - The dependencies required by the controller
* @param {Object} dependencies.settingsService - Service for application settings
* @param {Object} dependencies.emailService - Service for email operations
* @param {Object} dependencies.jobQueue - Service for job queue operations
* @param {Object} dependencies.userService - User business logic service
*/
constructor(commonDependencies, { settingsService, emailService, jobQueue, userService }) {
super(commonDependencies);
this.settingsService = settingsService;
this.emailService = emailService;
this.jobQueue = jobQueue;
this.userService = userService;
}
get serviceName() {
return AuthController.SERVICE_NAME;
}
/**
* Registers a new user in the system.
*
* @async
* @function registerUser
* @param {Object} req - Express request object
* @param {Object} req.body - Request body containing user registration data
* @param {string} req.body.firstName - User's first name
* @param {string} req.body.lastName - User's last name
* @param {string} req.body.email - User's email address (will be converted to lowercase)
* @param {string} req.body.password - User's password
* @param {string} [req.body.inviteToken] - Invite token for registration (required if superadmin exists)
* @param {string} [req.body.teamId] - Team ID (auto-assigned if superadmin)
* @param {Array<string>} [req.body.role] - User roles (auto-assigned if superadmin)
* @param {Object} [req.file] - Profile image file uploaded via multer
* @param {Object} res - Express response object
* @returns {Promise<Object>} Success response with user data and JWT token
* @throws {Error} 422 - Validation error if request body is invalid
* @throws {Error} 409 - Conflict if user already exists
* @example
* // Register first user (becomes superadmin)
* POST /auth/register
* {
* "firstName": "John",
* "lastName": "Doe",
* "email": "john@example.com",
* "password": "SecurePass123!"
* }
*
* // Register subsequent user (requires invite token)
* POST /auth/register
* {
* "firstName": "Jane",
* "lastName": "Smith",
* "email": "jane@example.com",
* "password": "SecurePass123!",
* "inviteToken": "abc123..."
* }
*/
registerUser = this.asyncHandler(
async (req, res) => {
if (req.body?.email) {
req.body.email = req.body.email?.toLowerCase();
}
await registrationBodyValidation.validateAsync(req.body);
const { user, token } = await this.userService.registerUser(req.body, req.file);
res.success({
msg: this.stringService.authCreateUser,
data: { user, token },
});
},
SERVICE_NAME,
"registerUser"
);
/**
* Authenticates a user and returns a JWT token.
*
* @async
* @function loginUser
* @param {Object} req - Express request object
* @param {Object} req.body - Request body containing login credentials
* @param {string} req.body.email - User's email address (will be converted to lowercase)
* @param {string} req.body.password - User's password
* @param {Object} res - Express response object
* @returns {Promise<Object>} Success response with user data and JWT token
* @throws {Error} 422 - Validation error if request body is invalid
* @throws {Error} 401 - Unauthorized if credentials are incorrect
* @example
* POST /auth/login
* {
* "email": "john@example.com",
* "password": "SecurePass123!"
* }
*/
loginUser = this.asyncHandler(
async (req, res) => {
if (req.body?.email) {
req.body.email = req.body.email?.toLowerCase();
}
await loginValidation.validateAsync(req.body);
const { user, token } = await this.userService.loginUser(req.body.email, req.body.password);
return res.success({
msg: this.stringService.authLoginUser,
data: {
user,
token,
},
});
},
SERVICE_NAME,
"loginUser"
);
/**
* Updates the current user's profile information.
*
* @async
* @function editUser
* @param {Object} req - Express request object
* @param {Object} req.body - Request body containing user update data
* @param {string} [req.body.firstName] - Updated first name
* @param {string} [req.body.lastName] - Updated last name
* @param {string} [req.body.password] - Current password (required for password change)
* @param {string} [req.body.newPassword] - New password (required for password change)
* @param {boolean} [req.body.deleteProfileImage] - Flag to delete profile image
* @param {Object} [req.file] - New profile image file
* @param {Object} req.user - Current authenticated user (from JWT)
* @param {Object} res - Express response object
* @returns {Promise<Object>} Success response with updated user data
* @throws {Error} 422 - Validation error if request body is invalid
* @throws {Error} 403 - Forbidden if current password is incorrect
* @example
* PUT /auth/user
* {
* "firstName": "John Updated",
* "lastName": "Doe Updated"
* }
*
* // Change password
* PUT /auth/user
* {
* "password": "OldPass123!",
* "newPassword": "NewPass123!"
* }
*/
editUser = this.asyncHandler(
async (req, res) => {
await editUserBodyValidation.validateAsync(req.body);
const updatedUser = await this.userService.editUser(req.body, req.file, req.user);
res.success({
msg: this.stringService.authUpdateUser,
data: updatedUser,
});
},
SERVICE_NAME,
"editUser"
);
/**
* Checks if a superadmin account exists in the system.
*
* @async
* @function checkSuperadminExists
* @param {Object} req - Express request object
* @param {Object} res - Express response object
* @returns {Promise<Object>} Success response with boolean indicating superadmin existence
* @example
* GET /auth/users/superadmin
* // Response: { "data": true } or { "data": false }
*/
checkSuperadminExists = this.asyncHandler(
async (req, res) => {
const superAdminExists = await this.userService.checkSuperadminExists();
return res.success({
msg: this.stringService.authAdminExists,
data: superAdminExists,
});
},
SERVICE_NAME,
"checkSuperadminExists"
);
/**
* Initiates password recovery process by sending a recovery email.
*
* @async
* @function requestRecovery
* @param {Object} req - Express request object
* @param {Object} req.body - Request body containing email
* @param {string} req.body.email - Email address for password recovery
* @param {Object} res - Express response object
* @returns {Promise<Object>} Success response with message ID
* @throws {Error} 422 - Validation error if email is invalid
* @throws {Error} 404 - Not found if user doesn't exist
* @example
* POST /auth/recovery/request
* {
* "email": "john@example.com"
* }
*/
requestRecovery = this.asyncHandler(
async (req, res) => {
await recoveryValidation.validateAsync(req.body);
const email = req?.body?.email;
const msgId = await this.userService.requestRecovery(email);
return res.success({
msg: this.stringService.authCreateRecoveryToken,
data: msgId,
});
},
SERVICE_NAME,
"requestRecovery"
);
/**
* Validates a password recovery token.
*
* @async
* @function validateRecovery
* @param {Object} req - Express request object
* @param {Object} req.body - Request body containing recovery token
* @param {string} req.body.recoveryToken - Recovery token to validate
* @param {Object} res - Express response object
* @returns {Promise<Object>} Success response if token is valid
* @throws {Error} 422 - Validation error if token format is invalid
* @throws {Error} 400 - Bad request if token is invalid or expired
* @example
* POST /auth/recovery/validate
* {
* "recoveryToken": "abc123..."
* }
*/
validateRecovery = this.asyncHandler(
async (req, res) => {
await recoveryTokenBodyValidation.validateAsync(req.body);
await this.userService.validateRecovery(req.body.recoveryToken);
return res.success({
msg: this.stringService.authVerifyRecoveryToken,
});
},
SERVICE_NAME,
"validateRecovery"
);
/**
* Resets user password using a valid recovery token.
*
* @async
* @function resetPassword
* @param {Object} req - Express request object
* @param {Object} req.body - Request body containing new password and recovery token
* @param {string} req.body.password - New password
* @param {string} req.body.recoveryToken - Valid recovery token
* @param {Object} res - Express response object
* @returns {Promise<Object>} Success response with user data and JWT token
* @throws {Error} 422 - Validation error if password format is invalid
* @throws {Error} 400 - Bad request if token is invalid or expired
* @example
* POST /auth/recovery/reset
* {
* "password": "NewSecurePass123!",
* "recoveryToken": "abc123..."
* }
*/
resetPassword = this.asyncHandler(
async (req, res) => {
await newPasswordValidation.validateAsync(req.body);
const { user, token } = await this.userService.resetPassword(req.body.password, req.body.recoveryToken);
return res.success({
msg: this.stringService.authResetPassword,
data: { user, token },
});
},
SERVICE_NAME,
"resetPassword"
);
/**
* Deletes the current user's account and associated data.
*
* @async
* @function deleteUser
* @param {Object} req - Express request object
* @param {Object} req.user - Current authenticated user (from JWT)
* @param {string} req.user._id - User ID
* @param {string} req.user.email - User email
* @param {string} req.user.teamId - User's team ID
* @param {Array<string>} req.user.role - User roles
* @param {Object} res - Express response object
* @returns {Promise<Object>} Success response confirming user deletion
* @throws {Error} 400 - Bad request if user is demo user
* @throws {Error} 404 - Not found if user doesn't exist
* @example
* DELETE /auth/user
* // Requires JWT authentication
*/
deleteUser = this.asyncHandler(
async (req, res) => {
await this.userService.deleteUser(req.user);
return res.success({
msg: this.stringService.authDeleteUser,
});
},
SERVICE_NAME,
"deleteUser"
);
/**
* Retrieves all users in the system (admin/superadmin only).
*
* @async
* @function getAllUsers
* @param {Object} req - Express request object
* @param {Object} res - Express response object
* @returns {Promise<Object>} Success response with array of users
* @throws {Error} 403 - Forbidden if user doesn't have admin/superadmin role
* @example
* GET /auth/users
* // Requires JWT authentication with admin/superadmin role
*/
getAllUsers = this.asyncHandler(
async (req, res) => {
const allUsers = await this.userService.getAllUsers();
return res.success({
msg: this.stringService.authGetAllUsers,
data: allUsers,
});
},
SERVICE_NAME,
"getAllUsers"
);
/**
* Retrieves a specific user by ID (superadmin only).
*
* @async
* @function getUserById
* @param {Object} req - Express request object
* @param {Object} req.params - URL parameters
* @param {string} req.params.userId - ID of the user to retrieve
* @param {Object} req.user - Current authenticated user (from JWT)
* @param {Array<string>} req.user.role - Current user's roles
* @param {Object} res - Express response object
* @returns {Promise<Object>} Success response with user data
* @throws {Error} 422 - Validation error if userId is invalid
* @throws {Error} 403 - Forbidden if user doesn't have superadmin role
* @throws {Error} 404 - Not found if user doesn't exist
* @example
* GET /auth/users/507f1f77bcf86cd799439011
* // Requires JWT authentication with superadmin role
*/
getUserById = this.asyncHandler(
async (req, res) => {
await getUserByIdParamValidation.validateAsync(req.params);
const userId = req?.params?.userId;
const roles = req?.user?.role;
if (!userId) {
throw new Error("No user ID in request");
}
if (!roles || roles.length === 0) {
throw new Error("No roles in request");
}
const user = await this.userService.getUserById(roles, userId);
return res.success({ msg: "ok", data: user });
},
SERVICE_NAME,
"getUserById"
);
/**
* Updates a specific user by ID (superadmin only).
*
* @async
* @function editUserById
* @param {Object} req - Express request object
* @param {Object} req.params - URL parameters
* @param {string} req.params.userId - ID of the user to update
* @param {Object} req.body - Request body containing user update data
* @param {string} [req.body.firstName] - Updated first name
* @param {string} [req.body.lastName] - Updated last name
* @param {Array<string>} [req.body.role] - Updated user roles
* @param {Object} req.user - Current authenticated user (from JWT)
* @param {string} req.user._id - Current user's ID
* @param {Array<string>} req.user.role - Current user's roles
* @param {Object} res - Express response object
* @returns {Promise<Object>} Success response confirming user update
* @throws {Error} 422 - Validation error if parameters or body are invalid
* @throws {Error} 403 - Forbidden if user doesn't have superadmin role
* @throws {Error} 404 - Not found if user doesn't exist
* @example
* PUT /auth/users/507f1f77bcf86cd799439011
* {
* "firstName": "Updated Name",
* "role": ["admin"]
* }
* // Requires JWT authentication with superadmin role
*/
editUserById = this.asyncHandler(
async (req, res) => {
const roles = req?.user?.role;
if (!roles.includes("superadmin")) {
throw this.errorService.createError("Unauthorized", 403);
}
const userId = req.params.userId;
const user = { ...req.body };
await editUserByIdParamValidation.validateAsync(req.params);
// If this is superadmin self edit, allow "superadmin" role
if (userId === req.user._id) {
await editSuperadminUserByIdBodyValidation.validateAsync(req.body);
} else {
await editUserByIdBodyValidation.validateAsync(req.body);
}
await this.userService.editUserById(userId, user);
return res.success({ msg: "ok" });
},
SERVICE_NAME,
"editUserById"
);
editUserPasswordById = this.asyncHandler(
async (req, res) => {
const roles = req?.user?.role;
if (!roles.includes("superadmin")) {
throw this.errorService.createError("Unauthorized", 403);
}
const userId = req.params.userId;
await editUserByIdParamValidation.validateAsync(req.params);
await editUserPasswordByIdBodyValidation.validateAsync(req.body);
const updatedPassword = req.body.password;
await this.userService.setPasswordByUserId(userId, updatedPassword);
return res.success({ msg: "Password reset successfully" });
},
SERVICE_NAME,
"editUserPasswordById"
);
}
export default AuthController;
@@ -1,83 +0,0 @@
import { AppError } from "../../service/v1/infrastructure/errorService.js";
export const createCommonDependencies = (db, errorService, logger, stringService) => {
return {
db,
errorService,
logger,
stringService,
};
};
class BaseController {
constructor({ db, logger, errorService, ...additionalDependencies }) {
this.db = db;
this.logger = logger;
this.errorService = errorService;
Object.assign(this, additionalDependencies);
this.asyncHandler = (fn, serviceName, methodName) => {
return async (req, res, next) => {
try {
await fn(req, res, next);
} catch (error) {
// Handle validation errors
if (error.isJoi) {
const validationError = this.errorService.createValidationError(error.message, error.details, serviceName, methodName);
return next(validationError);
}
if (error.name === "ValidationError") {
const validationError = this.errorService.createValidationError("Database validation failed", error.errors, serviceName, methodName);
return next(validationError);
}
if (error.name === "CastError") {
const notFoundError = this.errorService.createNotFoundError(
"Invalid resource identifier",
{ field: error.path, value: error.value },
serviceName,
methodName
);
return next(notFoundError);
}
if (error.code === "11000") {
const conflictError = this.errorService.createConflictError("Resource already exists", {
originalError: error.message,
code: error.code,
});
conflictError.service = serviceName;
conflictError.method = methodName;
return next(conflictError);
}
if (error instanceof AppError) {
error.service = error.service || serviceName;
error.method = error.method || methodName;
return next(error);
}
if (error.status) {
const appError = this.errorService.createError(error.message, error.status, serviceName, methodName, {
originalError: error.message,
stack: error.stack,
});
return next(appError);
}
// For unknown errors, create a server error
const appError = this.errorService.createServerError(error.message || "An unexpected error occurred", {
originalError: error.message,
stack: error.stack,
});
appError.service = serviceName;
appError.method = methodName;
appError.stack = error.stack; // Preserve original stack
return next(appError);
}
};
};
}
}
export default BaseController;
@@ -1,360 +0,0 @@
import BaseController from "./baseController.js";
import {
getChecksParamValidation,
getChecksQueryValidation,
getTeamChecksQueryValidation,
deleteChecksParamValidation,
deleteChecksByTeamIdParamValidation,
updateChecksTTLBodyValidation,
ackCheckBodyValidation,
ackAllChecksParamValidation,
ackAllChecksBodyValidation,
} from "../../validation/joi.js";
const SERVICE_NAME = "checkController";
/**
* Check Controller
*
* Handles all check-related HTTP requests including retrieving checks,
* acknowledging checks, deleting checks, and managing check TTL settings.
*
* @class CheckController
* @description Manages check operations and monitoring data
*/
class CheckController extends BaseController {
static SERVICE_NAME = SERVICE_NAME;
/**
* Creates an instance of CheckController.
*
* @param {Object} commonDependencies - Common dependencies injected into the controller
* @param {Object} dependencies - The dependencies required by the controller
* @param {Object} dependencies.settingsService - Service for application settings
* @param {Object} dependencies.checkService - Check business logic service
*/
constructor(commonDependencies, { settingsService, checkService }) {
super(commonDependencies);
this.settingsService = settingsService;
this.checkService = checkService;
}
get serviceName() {
return CheckController.SERVICE_NAME;
}
/**
* Retrieves checks for a specific monitor with filtering and pagination.
*
* @async
* @function getChecksByMonitor
* @param {Object} req - Express request object
* @param {Object} req.params - URL parameters
* @param {string} req.params.monitorId - ID of the monitor to get checks for
* @param {Object} req.query - Query parameters for filtering and pagination
* @param {string} [req.query.type] - Type of checks to filter by
* @param {string} [req.query.sortOrder] - Sort order (asc/desc)
* @param {string} [req.query.dateRange] - Date range filter
* @param {string} [req.query.filter] - General filter string
* @param {boolean} [req.query.ack] - Filter by acknowledgment status
* @param {number} [req.query.page] - Page number for pagination
* @param {number} [req.query.rowsPerPage] - Number of rows per page
* @param {string} [req.query.status] - Filter by check status
* @param {Object} req.user - Current authenticated user (from JWT)
* @param {string} req.user.teamId - User's team ID
* @param {Object} res - Express response object
* @returns {Promise<Object>} Success response with checks data
* @throws {Error} 422 - Validation error if parameters are invalid
* @throws {Error} 404 - Not found if monitor doesn't exist
* @throws {Error} 403 - Forbidden if user doesn't have access to monitor
* @example
* GET /checks/monitor/507f1f77bcf86cd799439011?page=1&rowsPerPage=10&status=down
* // Requires JWT authentication
*/
getChecksByMonitor = this.asyncHandler(
async (req, res) => {
await getChecksParamValidation.validateAsync(req.params);
await getChecksQueryValidation.validateAsync(req.query);
const result = await this.checkService.getChecksByMonitor({
monitorId: req?.params?.monitorId,
query: req?.query,
teamId: req?.user?.teamId,
});
return res.success({
msg: this.stringService.checkGet,
data: result,
});
},
SERVICE_NAME,
"getChecksByMonitor"
);
/**
* Retrieves all checks for the current user's team with filtering and pagination.
*
* @async
* @function getChecksByTeam
* @param {Object} req - Express request object
* @param {Object} req.query - Query parameters for filtering and pagination
* @param {string} [req.query.sortOrder] - Sort order (asc/desc)
* @param {string} [req.query.dateRange] - Date range filter
* @param {string} [req.query.filter] - General filter string
* @param {boolean} [req.query.ack] - Filter by acknowledgment status
* @param {number} [req.query.page] - Page number for pagination
* @param {number} [req.query.rowsPerPage] - Number of rows per page
* @param {Object} req.user - Current authenticated user (from JWT)
* @param {string} req.user.teamId - User's team ID
* @param {Object} res - Express response object
* @returns {Promise<Object>} Success response with checks data
* @throws {Error} 422 - Validation error if query parameters are invalid
* @example
* GET /checks/team?page=1&rowsPerPage=20&status=down&ack=false
* // Requires JWT authentication
*/
getChecksByTeam = this.asyncHandler(
async (req, res) => {
await getTeamChecksQueryValidation.validateAsync(req.query);
const checkData = await this.checkService.getChecksByTeam({
teamId: req?.user?.teamId,
query: req?.query,
});
return res.success({
msg: this.stringService.checkGet,
data: checkData,
});
},
SERVICE_NAME,
"getChecksByTeam"
);
/**
* Retrieves a summary of checks for the current user's team.
*
* @async
* @function getChecksSummaryByTeamId
* @param {Object} req - Express request object
* @param {Object} req.user - Current authenticated user (from JWT)
* @param {string} req.user.teamId - User's team ID
* @param {Object} res - Express response object
* @returns {Promise<Object>} Success response with checks summary
* @example
* GET /checks/summary
* // Requires JWT authentication
* // Response includes counts by status, time ranges, etc.
*/
getChecksSummaryByTeamId = this.asyncHandler(
async (req, res) => {
const summary = await this.checkService.getChecksSummaryByTeamId({ teamId: req?.user?.teamId });
return res.success({
msg: this.stringService.checkGetSummary,
data: summary,
});
},
SERVICE_NAME,
"getChecksSummaryByTeamId"
);
/**
* Acknowledges a specific check by ID.
*
* @async
* @function ackCheck
* @param {Object} req - Express request object
* @param {Object} req.params - URL parameters
* @param {string} req.params.checkId - ID of the check to acknowledge
* @param {Object} req.body - Request body containing acknowledgment data
* @param {boolean} req.body.ack - Acknowledgment status (true/false)
* @param {Object} req.user - Current authenticated user (from JWT)
* @param {string} req.user.teamId - User's team ID
* @param {Object} res - Express response object
* @returns {Promise<Object>} Success response with updated check data
* @throws {Error} 422 - Validation error if request body is invalid
* @throws {Error} 404 - Not found if check doesn't exist
* @throws {Error} 403 - Forbidden if user doesn't have access to check
* @example
* PUT /checks/507f1f77bcf86cd799439011/ack
* {
* "ack": true
* }
* // Requires JWT authentication
*/
ackCheck = this.asyncHandler(
async (req, res) => {
await ackCheckBodyValidation.validateAsync(req.body);
const updatedCheck = await this.checkService.ackCheck({
checkId: req?.params?.checkId,
teamId: req?.user?.teamId,
ack: req?.body?.ack,
});
return res.success({
msg: this.stringService.checkUpdateStatus,
data: updatedCheck,
});
},
SERVICE_NAME,
"ackCheck"
);
/**
* Acknowledges all checks for a specific monitor or path.
*
* @async
* @function ackAllChecks
* @param {Object} req - Express request object
* @param {Object} req.params - URL parameters
* @param {string} req.params.monitorId - ID of the monitor
* @param {string} req.params.path - Path for acknowledgment (e.g., "monitor")
* @param {Object} req.body - Request body containing acknowledgment data
* @param {boolean} req.body.ack - Acknowledgment status (true/false)
* @param {Object} req.user - Current authenticated user (from JWT)
* @param {string} req.user.teamId - User's team ID
* @param {Object} res - Express response object
* @returns {Promise<Object>} Success response with updated checks data
* @throws {Error} 422 - Validation error if parameters or body are invalid
* @throws {Error} 404 - Not found if monitor doesn't exist
* @throws {Error} 403 - Forbidden if user doesn't have access to monitor
* @example
* PUT /checks/monitor/507f1f77bcf86cd799439011/ack
* {
* "ack": true
* }
* // Requires JWT authentication
*/
ackAllChecks = this.asyncHandler(
async (req, res) => {
await ackAllChecksParamValidation.validateAsync(req.params);
await ackAllChecksBodyValidation.validateAsync(req.body);
const teamId = req?.user?.teamId;
if (!teamId) {
throw new Error("No team ID in request");
}
const updatedChecks = await this.checkService.ackAllChecks({
monitorId: req?.params?.monitorId,
path: req?.params?.path,
teamId: req?.user?.teamId,
ack: req?.body?.ack,
});
return res.success({
msg: this.stringService.checkUpdateStatus,
data: updatedChecks,
});
},
SERVICE_NAME,
"ackAllChecks"
);
/**
* Deletes all checks for a specific monitor.
*
* @async
* @function deleteChecks
* @param {Object} req - Express request object
* @param {Object} req.params - URL parameters
* @param {string} req.params.monitorId - ID of the monitor whose checks to delete
* @param {Object} req.user - Current authenticated user (from JWT)
* @param {string} req.user.teamId - User's team ID
* @param {Object} res - Express response object
* @returns {Promise<Object>} Success response with deletion count
* @throws {Error} 422 - Validation error if monitorId is invalid
* @throws {Error} 404 - Not found if monitor doesn't exist
* @throws {Error} 403 - Forbidden if user doesn't have access to monitor
* @example
* DELETE /checks/monitor/507f1f77bcf86cd799439011
* // Requires JWT authentication
* // Response: { "data": { "deletedCount": 150 } }
*/
deleteChecks = this.asyncHandler(
async (req, res) => {
await deleteChecksParamValidation.validateAsync(req.params);
const deletedCount = await this.checkService.deleteChecks({
monitorId: req.params.monitorId,
teamId: req?.user?.teamId,
});
return res.success({
msg: this.stringService.checkDelete,
data: { deletedCount },
});
},
SERVICE_NAME,
"deleteChecks"
);
/**
* Deletes all checks for the current user's team.
*
* @async
* @function deleteChecksByTeamId
* @param {Object} req - Express request object
* @param {Object} req.user - Current authenticated user (from JWT)
* @param {string} req.user.teamId - User's team ID
* @param {Object} res - Express response object
* @returns {Promise<Object>} Success response with deletion count
* @throws {Error} 422 - Validation error if parameters are invalid
* @example
* DELETE /checks/team
* // Requires JWT authentication
* // Response: { "data": { "deletedCount": 1250 } }
*/
deleteChecksByTeamId = this.asyncHandler(
async (req, res) => {
await deleteChecksByTeamIdParamValidation.validateAsync(req.params);
const deletedCount = await this.checkService.deleteChecksByTeamId({ teamId: req?.user?.teamId });
return res.success({
msg: this.stringService.checkDelete,
data: { deletedCount },
});
},
SERVICE_NAME,
"deleteChecksByTeamId"
);
/**
* Updates the TTL (Time To Live) setting for checks in the current user's team.
*
* @async
* @function updateChecksTTL
* @param {Object} req - Express request object
* @param {Object} req.body - Request body containing TTL data
* @param {number} req.body.ttl - TTL value in days
* @param {Object} req.user - Current authenticated user (from JWT)
* @param {string} req.user.teamId - User's team ID
* @param {Object} res - Express response object
* @returns {Promise<Object>} Success response confirming TTL update
* @throws {Error} 422 - Validation error if TTL value is invalid
* @example
* PUT /checks/ttl
* {
* "ttl": 30
* }
* // Requires JWT authentication
* // Sets check TTL to 30 days
*/
updateChecksTTL = this.asyncHandler(
async (req, res) => {
await updateChecksTTLBodyValidation.validateAsync(req.body);
await this.checkService.updateChecksTTL({
teamId: req?.user?.teamId,
ttl: req?.body?.ttl,
});
return res.success({
msg: this.stringService.checkUpdateTTL,
});
},
SERVICE_NAME,
"updateChecksTtl"
);
}
export default CheckController;
@@ -1,12 +0,0 @@
const fetchMonitorCertificate = async (sslChecker, monitor) => {
const monitorUrl = new URL(monitor.url);
const hostname = monitorUrl.hostname;
const cert = await sslChecker(hostname);
// Throw an error if no cert or if cert.validTo is not present
if (cert?.validTo === null || cert?.validTo === undefined) {
throw new Error("Certificate not found");
}
return cert;
};
export { fetchMonitorCertificate };
@@ -1,61 +0,0 @@
const SERVICE_NAME = "diagnosticController";
import BaseController from "./baseController.js";
/**
* Diagnostic Controller
*
* Handles system diagnostic and monitoring requests including system statistics,
* performance metrics, and health checks.
*
* @class DiagnosticController
* @description Manages system diagnostics and performance monitoring
*/
class DiagnosticController extends BaseController {
static SERVICE_NAME = SERVICE_NAME;
/**
* Creates an instance of DiagnosticController.
* @param {Object} commonDependencies - Common dependencies injected into the controller
* @param {Object} dependencies - The dependencies required by the controller
* @param {Object} dependencies.diagnosticService - Service for system diagnostics and monitoring
*/
constructor(commonDependencies, { diagnosticService }) {
super(commonDependencies);
this.diagnosticService = diagnosticService;
}
get serviceName() {
return DiagnosticController.SERVICE_NAME;
}
/**
* Retrieves comprehensive system statistics and performance metrics.
*
* @async
* @function getSystemStats
* @param {Object} req - Express request object
* @param {Object} res - Express response object
* @returns {Promise<Object>} Success response with system diagnostics data
* @description Returns system performance metrics, memory usage, CPU statistics,
* and other diagnostic information useful for monitoring system health.
* @example
* GET /diagnostics/stats
* // Response includes:
* // - Memory usage (heap, external, arrayBuffers)
* // - CPU usage statistics
* // - System uptime
* // - Performance metrics
* // - Database connection status
* // - Active processes/connections
*/
getSystemStats = this.asyncHandler(
async (req, res) => {
const diagnostics = await this.diagnosticService.getSystemStats();
return res.success({
msg: "OK",
data: diagnostics,
});
},
SERVICE_NAME,
"getSystemStats"
);
}
export default DiagnosticController;
@@ -1,101 +0,0 @@
import { inviteBodyValidation, inviteVerificationBodyValidation } from "../../validation/joi.js";
import BaseController from "./baseController.js";
const SERVICE_NAME = "inviteController";
/**
* Controller for handling user invitation operations
* Manages invite token generation, email sending, and token verification
*/
class InviteController extends BaseController {
static SERVICE_NAME = SERVICE_NAME;
/**
* Creates a new InviteController instance
* @param {Object} commonDependencies - Common dependencies injected into the controller
* @param {Object} dependencies.inviteService - Service for invite-related operations
*/
constructor(commonDependencies, { inviteService }) {
super(commonDependencies);
this.inviteService = inviteService;
}
get serviceName() {
return InviteController.SERVICE_NAME;
}
/**
* Generates an invite token for a user invitation
* @param {Object} req - Express request object
* @param {Object} req.body - Request body containing invite details
* @param {Object} req.user - Authenticated user object
* @param {string} req.user.teamId - Team ID of the authenticated user
* @param {Object} res - Express response object
* @returns {Promise<Object>} Response with invite token data
*/
getInviteToken = this.asyncHandler(
async (req, res) => {
const invite = req.body;
const teamId = req?.user?.teamId;
invite.teamId = teamId;
await inviteBodyValidation.validateAsync(invite);
const inviteToken = await this.inviteService.getInviteToken({ invite, teamId });
return res.success({
msg: this.stringService.inviteIssued,
data: inviteToken,
});
},
SERVICE_NAME,
"getInviteToken"
);
/**
* Sends an invitation email to a user
* @param {Object} req - Express request object
* @param {Object} req.body - Request body containing invite details
* @param {Object} req.user - Authenticated user object
* @param {string} req.user.teamId - Team ID of the authenticated user
* @param {string} req.user.firstName - First name of the authenticated user
* @param {Object} res - Express response object
* @returns {Promise<Object>} Response with invite token data
*/
sendInviteEmail = this.asyncHandler(
async (req, res) => {
const inviteRequest = req.body;
inviteRequest.teamId = req?.user?.teamId;
await inviteBodyValidation.validateAsync(inviteRequest);
const inviteToken = await this.inviteService.sendInviteEmail({
inviteRequest,
firstName: req?.user?.firstName,
});
return res.success({
msg: this.stringService.inviteIssued,
data: inviteToken,
});
},
SERVICE_NAME,
"sendInviteEmail"
);
/**
* Verifies an invite token and returns invite details
* @param {Object} req - Express request object
* @param {Object} req.body - Request body containing the invite token
* @param {string} req.body.token - The invite token to verify
* @param {Object} res - Express response object
* @returns {Promise<Object>} Response with verified invite data
*/
verifyInviteToken = this.asyncHandler(
async (req, res) => {
await inviteVerificationBodyValidation.validateAsync(req.body);
const invite = await this.inviteService.verifyInviteToken({ inviteToken: req?.body?.token });
return res.success({
msg: this.stringService.inviteVerified,
data: invite,
});
},
SERVICE_NAME,
"verifyInviteToken"
);
}
export default InviteController;
@@ -1,26 +0,0 @@
import BaseController from "./baseController.js";
const SERVICE_NAME = "LogController";
class LogController extends BaseController {
static SERVICE_NAME = SERVICE_NAME;
constructor(commonDependencies) {
super(commonDependencies);
}
get serviceName() {
return LogController.SERVICE_NAME;
}
getLogs = this.asyncHandler(
async (req, res) => {
const logs = await this.logger.getLogs();
res.success({
msg: "Logs fetched successfully",
data: logs,
});
},
SERVICE_NAME,
"getLogs"
);
}
export default LogController;
@@ -1,146 +0,0 @@
import {
createMaintenanceWindowBodyValidation,
editMaintenanceWindowByIdParamValidation,
editMaintenanceByIdWindowBodyValidation,
getMaintenanceWindowByIdParamValidation,
getMaintenanceWindowsByMonitorIdParamValidation,
getMaintenanceWindowsByTeamIdQueryValidation,
deleteMaintenanceWindowByIdParamValidation,
} from "../../validation/joi.js";
import BaseController from "./baseController.js";
const SERVICE_NAME = "maintenanceWindowController";
class MaintenanceWindowController extends BaseController {
static SERVICE_NAME = SERVICE_NAME;
constructor(commonDependencies, { settingsService, maintenanceWindowService }) {
super(commonDependencies);
this.settingsService = settingsService;
this.maintenanceWindowService = maintenanceWindowService;
}
get serviceName() {
return MaintenanceWindowController.SERVICE_NAME;
}
createMaintenanceWindows = this.asyncHandler(
async (req, res) => {
await createMaintenanceWindowBodyValidation.validateAsync(req.body);
const teamId = req?.user?.teamId;
if (!teamId) {
throw this.errorService.createBadRequestError("Team ID is required");
}
await this.maintenanceWindowService.createMaintenanceWindow({ teamId, body: req.body });
return res.success({
msg: this.stringService.maintenanceWindowCreate,
});
},
SERVICE_NAME,
"createMaintenanceWindows"
);
getMaintenanceWindowById = this.asyncHandler(
async (req, res) => {
await getMaintenanceWindowByIdParamValidation.validateAsync(req.params);
const teamId = req.user.teamId;
if (!teamId) {
throw this.errorService.createBadRequestError("Team ID is required");
}
const maintenanceWindow = await this.maintenanceWindowService.getMaintenanceWindowById({ id: req.params.id, teamId });
return res.success({
msg: this.stringService.maintenanceWindowGetById,
data: maintenanceWindow,
});
},
SERVICE_NAME,
"getMaintenanceWindowById"
);
getMaintenanceWindowsByTeamId = this.asyncHandler(
async (req, res) => {
await getMaintenanceWindowsByTeamIdQueryValidation.validateAsync(req.query);
const teamId = req?.user?.teamId;
if (!teamId) {
throw this.errorService.createBadRequestError("Team ID is required");
}
const maintenanceWindows = await this.maintenanceWindowService.getMaintenanceWindowsByTeamId({ teamId, query: req.query });
return res.success({
msg: this.stringService.maintenanceWindowGetByTeam,
data: maintenanceWindows,
});
},
SERVICE_NAME,
"getMaintenanceWindowsByTeamId"
);
getMaintenanceWindowsByMonitorId = this.asyncHandler(
async (req, res) => {
await getMaintenanceWindowsByMonitorIdParamValidation.validateAsync(req.params);
const teamId = req?.user?.teamId;
if (!teamId) {
throw this.errorService.createBadRequestError("Team ID is required");
}
const maintenanceWindows = await this.maintenanceWindowService.getMaintenanceWindowsByMonitorId({ monitorId: req.params.monitorId, teamId });
return res.success({
msg: this.stringService.maintenanceWindowGetByUser,
data: maintenanceWindows,
});
},
SERVICE_NAME,
"getMaintenanceWindowsByMonitorId"
);
deleteMaintenanceWindow = this.asyncHandler(
async (req, res) => {
await deleteMaintenanceWindowByIdParamValidation.validateAsync(req.params);
const teamId = req?.user?.teamId;
if (!teamId) {
throw this.errorService.createBadRequestError("Team ID is required");
}
await this.maintenanceWindowService.deleteMaintenanceWindow({ id: req.params.id, teamId });
return res.success({
msg: this.stringService.maintenanceWindowDelete,
});
},
SERVICE_NAME,
"deleteMaintenanceWindow"
);
editMaintenanceWindow = this.asyncHandler(
async (req, res) => {
await editMaintenanceWindowByIdParamValidation.validateAsync(req.params);
await editMaintenanceByIdWindowBodyValidation.validateAsync(req.body);
const teamId = req.user.teamId;
if (!teamId) {
throw this.errorService.createBadRequestError("Team ID is required");
}
const editedMaintenanceWindow = await this.maintenanceWindowService.editMaintenanceWindow({ id: req.params.id, body: req.body, teamId });
return res.success({
msg: this.stringService.maintenanceWindowEdit,
data: editedMaintenanceWindow,
});
},
SERVICE_NAME,
"editMaintenanceWindow"
);
}
export default MaintenanceWindowController;
@@ -1,475 +0,0 @@
import {
getMonitorByIdParamValidation,
getMonitorByIdQueryValidation,
getMonitorsByTeamIdParamValidation,
getMonitorsByTeamIdQueryValidation,
createMonitorBodyValidation,
editMonitorBodyValidation,
pauseMonitorParamValidation,
getMonitorStatsByIdParamValidation,
getMonitorStatsByIdQueryValidation,
getCertificateParamValidation,
getHardwareDetailsByIdParamValidation,
getHardwareDetailsByIdQueryValidation,
} from "../../validation/joi.js";
import sslChecker from "ssl-checker";
import { fetchMonitorCertificate } from "./controllerUtils.js";
import BaseController from "./baseController.js";
const SERVICE_NAME = "monitorController";
class MonitorController extends BaseController {
static SERVICE_NAME = SERVICE_NAME;
constructor(commonDependencies, { settingsService, jobQueue, emailService, monitorService }) {
super(commonDependencies);
this.settingsService = settingsService;
this.jobQueue = jobQueue;
this.emailService = emailService;
this.monitorService = monitorService;
}
get serviceName() {
return MonitorController.SERVICE_NAME;
}
async verifyTeamAccess(teamId, monitorId) {
const monitor = await this.db.monitorModule.getMonitorById(monitorId);
if (!monitor.teamId.equals(teamId)) {
throw this.errorService.createAuthorizationError();
}
}
getAllMonitors = this.asyncHandler(
async (req, res) => {
const monitors = await this.monitorService.getAllMonitors();
return res.success({
msg: this.stringService.monitorGetAll,
data: monitors,
});
},
SERVICE_NAME,
"getAllMonitors"
);
getUptimeDetailsById = this.asyncHandler(
async (req, res) => {
const monitorId = req?.params?.monitorId;
const dateRange = req?.query?.dateRange;
const normalize = req?.query?.normalize;
const teamId = req?.user?.teamId;
if (!teamId) {
throw this.errorService.createBadRequestError("Team ID is required");
}
const data = await this.monitorService.getUptimeDetailsById({
teamId,
monitorId,
dateRange,
normalize,
});
return res.success({
msg: this.stringService.monitorGetByIdSuccess,
data: data,
});
},
SERVICE_NAME,
"getUptimeDetailsById"
);
getMonitorStatsById = this.asyncHandler(
async (req, res) => {
await getMonitorStatsByIdParamValidation.validateAsync(req.params);
await getMonitorStatsByIdQueryValidation.validateAsync(req.query);
let { limit, sortOrder, dateRange, numToDisplay, normalize } = req.query;
const monitorId = req?.params?.monitorId;
const teamId = req?.user?.teamId;
if (!teamId) {
throw this.errorService.createBadRequestError("Team ID is required");
}
const monitorStats = await this.monitorService.getMonitorStatsById({
teamId,
monitorId,
limit,
sortOrder,
dateRange,
numToDisplay,
normalize,
});
return res.success({
msg: this.stringService.monitorStatsById,
data: monitorStats,
});
},
SERVICE_NAME,
"getMonitorStatsById"
);
/**
* Get hardware details for a specific monitor by ID
* @async
* @param {Express.Request} req - Express request object containing monitorId in params
* @param {Express.Response} res - Express response object
* @param {Express.NextFunction} next - Express next middleware function
* @returns {Promise<Express.Response>}
* @throws {Error} - Throws error if monitor not found or other database errors
*/
getHardwareDetailsById = this.asyncHandler(
async (req, res) => {
await getHardwareDetailsByIdParamValidation.validateAsync(req.params);
await getHardwareDetailsByIdQueryValidation.validateAsync(req.query);
const monitorId = req?.params?.monitorId;
const dateRange = req?.query?.dateRange;
const teamId = req?.user?.teamId;
if (!teamId) {
throw this.errorService.createBadRequestError("Team ID is required");
}
const monitor = await this.monitorService.getHardwareDetailsById({
teamId,
monitorId,
dateRange,
});
return res.success({
msg: this.stringService.monitorGetByIdSuccess,
data: monitor,
});
},
SERVICE_NAME,
"getHardwareDetailsById"
);
getMonitorCertificate = this.asyncHandler(
async (req, res) => {
await getCertificateParamValidation.validateAsync(req.params);
const { monitorId } = req.params;
const monitor = await this.db.monitorModule.getMonitorById(monitorId);
const certificate = await fetchMonitorCertificate(sslChecker, monitor);
return res.success({
msg: this.stringService.monitorCertificate,
data: {
certificateDate: new Date(certificate.validTo),
},
});
},
SERVICE_NAME,
"getMonitorCertificate"
);
getMonitorById = this.asyncHandler(
async (req, res) => {
await getMonitorByIdParamValidation.validateAsync(req.params);
await getMonitorByIdQueryValidation.validateAsync(req.query);
const teamId = req?.user?.teamId;
if (!teamId) {
throw this.errorService.createBadRequestError("Team ID is required");
}
const monitor = await this.monitorService.getMonitorById({ teamId, monitorId: req?.params?.monitorId });
return res.success({
msg: this.stringService.monitorGetByIdSuccess,
data: monitor,
});
},
SERVICE_NAME,
"getMonitorById"
);
createMonitor = this.asyncHandler(
async (req, res) => {
await createMonitorBodyValidation.validateAsync(req.body);
const userId = req?.user?._id;
const teamId = req?.user?.teamId;
const monitor = await this.monitorService.createMonitor({ teamId, userId, body: req.body });
return res.success({
msg: this.stringService.monitorCreate,
data: monitor,
});
},
SERVICE_NAME,
"createMonitor"
);
createBulkMonitors = this.asyncHandler(
async (req, res) => {
if (!req.file) {
throw this.errorService.createBadRequestError("No file uploaded");
}
if (!req.file.mimetype.includes("csv")) {
throw this.errorService.createBadRequestError("File is not a CSV");
}
if (req.file.size === 0) {
throw this.errorService.createBadRequestError("File is empty");
}
const userId = req?.user?._id;
const teamId = req?.user?.teamId;
if (!userId || !teamId) {
throw this.errorService.createBadRequestError("Missing userId or teamId");
}
const fileData = req?.file?.buffer?.toString("utf-8");
if (!fileData) {
throw this.errorService.createBadRequestError("Cannot get file from buffer");
}
const monitors = await this.monitorService.createBulkMonitors({ fileData, userId, teamId });
return res.success({
msg: this.stringService.bulkMonitorsCreate,
data: monitors,
});
},
SERVICE_NAME,
"createBulkMonitors"
);
deleteMonitor = this.asyncHandler(
async (req, res) => {
await getMonitorByIdParamValidation.validateAsync(req.params);
const monitorId = req.params.monitorId;
const teamId = req?.user?.teamId;
if (!teamId) {
throw this.errorService.createBadRequestError("Team ID is required");
}
const deletedMonitor = await this.monitorService.deleteMonitor({ teamId, monitorId });
return res.success({ msg: this.stringService.monitorDelete, data: deletedMonitor });
},
SERVICE_NAME,
"deleteMonitor"
);
deleteAllMonitors = this.asyncHandler(
async (req, res) => {
const teamId = req?.user?.teamId;
if (!teamId) {
throw this.errorService.createBadRequestError("Team ID is required");
}
const deletedCount = await this.monitorService.deleteAllMonitors({ teamId });
return res.success({ msg: `Deleted ${deletedCount} monitors` });
},
SERVICE_NAME,
"deleteAllMonitors"
);
editMonitor = this.asyncHandler(
async (req, res) => {
await getMonitorByIdParamValidation.validateAsync(req.params);
await editMonitorBodyValidation.validateAsync(req.body);
const monitorId = req?.params?.monitorId;
const teamId = req?.user?.teamId;
if (!teamId) {
throw this.errorService.createBadRequestError("Team ID is required");
}
const editedMonitor = await this.monitorService.editMonitor({ teamId, monitorId, body: req.body });
return res.success({
msg: this.stringService.monitorEdit,
data: editedMonitor,
});
},
SERVICE_NAME,
"editMonitor"
);
pauseMonitor = this.asyncHandler(
async (req, res) => {
await pauseMonitorParamValidation.validateAsync(req.params);
const monitorId = req.params.monitorId;
const teamId = req?.user?.teamId;
if (!teamId) {
throw this.errorService.createBadRequestError("Team ID is required");
}
const monitor = await this.monitorService.pauseMonitor({ teamId, monitorId });
return res.success({
msg: monitor.isActive ? this.stringService.monitorResume : this.stringService.monitorPause,
data: monitor,
});
},
SERVICE_NAME,
"pauseMonitor"
);
addDemoMonitors = this.asyncHandler(
async (req, res) => {
const { _id, teamId } = req.user;
const demoMonitors = await this.monitorService.addDemoMonitors({ userId: _id, teamId });
return res.success({
msg: this.stringService.monitorDemoAdded,
data: demoMonitors?.length ?? 0,
});
},
SERVICE_NAME,
"addDemoMonitors"
);
sendTestEmail = this.asyncHandler(
async (req, res) => {
const { to } = req.body;
if (!to || typeof to !== "string") {
throw this.errorService.createBadRequestError(this.stringService.errorForValidEmailAddress);
}
const messageId = await this.monitorService.sendTestEmail({ to });
return res.success({
msg: this.stringService.sendTestEmail,
data: { messageId },
});
},
SERVICE_NAME,
"sendTestEmail"
);
getMonitorsByTeamId = this.asyncHandler(
async (req, res) => {
await getMonitorsByTeamIdParamValidation.validateAsync(req.params);
await getMonitorsByTeamIdQueryValidation.validateAsync(req.query);
let { limit, type, page, rowsPerPage, filter, field, order } = req.query;
const teamId = req?.user?.teamId;
const monitors = await this.monitorService.getMonitorsByTeamId({ teamId, limit, type, page, rowsPerPage, filter, field, order });
return res.success({
msg: this.stringService.monitorGetByTeamId,
data: monitors,
});
},
SERVICE_NAME,
"getMonitorsByTeamId"
);
getMonitorsAndSummaryByTeamId = this.asyncHandler(
async (req, res) => {
await getMonitorsByTeamIdParamValidation.validateAsync(req.params);
await getMonitorsByTeamIdQueryValidation.validateAsync(req.query);
const explain = req?.query?.explain;
const type = req?.query?.type;
const teamId = req?.user?.teamId;
if (!teamId) {
throw this.errorService.createBadRequestError("Team ID is required");
}
const result = await this.monitorService.getMonitorsAndSummaryByTeamId({ teamId, type, explain });
return res.success({
msg: "OK", // TODO
data: result,
});
},
SERVICE_NAME,
"getMonitorsAndSummaryByTeamId"
);
getMonitorsWithChecksByTeamId = this.asyncHandler(
async (req, res) => {
await getMonitorsByTeamIdParamValidation.validateAsync(req.params);
await getMonitorsByTeamIdQueryValidation.validateAsync(req.query);
const explain = req?.query?.explain;
let { limit, type, page, rowsPerPage, filter, field, order } = req.query;
const teamId = req?.user?.teamId;
if (!teamId) {
throw this.errorService.createBadRequestError("Team ID is required");
}
const monitors = await this.monitorService.getMonitorsWithChecksByTeamId({
teamId,
limit,
type,
page,
rowsPerPage,
filter,
field,
order,
explain,
});
return res.success({
msg: "OK",
data: monitors,
});
},
SERVICE_NAME,
"getMonitorsWithChecksByTeamId"
);
exportMonitorsToCSV = this.asyncHandler(
async (req, res) => {
const teamId = req?.user?.teamId;
if (!teamId) {
throw this.errorService.createBadRequestError("Team ID is required");
}
const csv = await this.monitorService.exportMonitorsToCSV({ teamId });
return res.file({
data: csv,
headers: {
"Content-Type": "text/csv",
"Content-Disposition": "attachment; filename=monitors.csv",
},
});
},
SERVICE_NAME,
"exportMonitorsToCSV"
);
getAllGames = this.asyncHandler(
async (req, res) => {
return res.success({
msg: "OK",
data: this.monitorService.getAllGames(),
});
},
SERVICE_NAME,
"getAllGames"
);
getGroupsByTeamId = this.asyncHandler(
async (req, res) => {
const teamId = req?.user?.teamId;
if (!teamId) {
throw this.errorService.createBadRequestError("Team ID is required");
}
const groups = await this.monitorService.getGroupsByTeamId({ teamId });
return res.success({
msg: "OK",
data: groups,
});
},
SERVICE_NAME,
"getGroupsByTeamId"
);
}
export default MonitorController;
@@ -1,180 +0,0 @@
import { createNotificationBodyValidation } from "../../validation/joi.js";
import BaseController from "./baseController.js";
const SERVICE_NAME = "NotificationController";
class NotificationController extends BaseController {
static SERVICE_NAME = SERVICE_NAME;
constructor(commonDependencies, { notificationService, statusService }) {
super(commonDependencies);
this.notificationService = notificationService;
this.statusService = statusService;
}
get serviceName() {
return NotificationController.SERVICE_NAME;
}
testNotification = this.asyncHandler(
async (req, res) => {
const notification = req.body;
const success = await this.notificationService.sendTestNotification(notification);
if (!success) {
throw this.errorService.createServerError("Sending notification failed");
}
return res.success({
msg: "Notification sent successfully",
});
},
SERVICE_NAME,
"testNotification"
);
createNotification = this.asyncHandler(
async (req, res) => {
await createNotificationBodyValidation.validateAsync(req.body, {
abortEarly: false,
});
const body = req.body;
const teamId = req?.user?.teamId;
if (!teamId) {
throw this.errorService.createBadRequestError("Team ID is required");
}
const userId = req?.user?._id;
if (!userId) {
throw this.errorService.createBadRequestError("User ID is required");
}
body.userId = userId;
body.teamId = teamId;
const notification = await this.db.notificationModule.createNotification(body);
return res.success({
msg: "Notification created successfully",
data: notification,
});
},
SERVICE_NAME,
"createNotification"
);
getNotificationsByTeamId = this.asyncHandler(
async (req, res) => {
const teamId = req?.user?.teamId;
if (!teamId) {
throw this.errorService.createBadRequestError("Team ID is required");
}
const notifications = await this.db.notificationModule.getNotificationsByTeamId(teamId);
return res.success({
msg: "Notifications fetched successfully",
data: notifications,
});
},
SERVICE_NAME,
"getNotificationsByTeamId"
);
deleteNotification = this.asyncHandler(
async (req, res) => {
const teamId = req?.user?.teamId;
if (!teamId) {
throw this.errorService.createBadRequestError("Team ID is required");
}
const notification = await this.db.notificationModule.getNotificationById(req.params.id);
if (!notification.teamId.equals(teamId)) {
throw this.errorService.createAuthorizationError();
}
await this.db.notificationModule.deleteNotificationById(req.params.id);
return res.success({
msg: "Notification deleted successfully",
});
},
SERVICE_NAME,
"deleteNotification"
);
getNotificationById = this.asyncHandler(
async (req, res) => {
const notification = await this.db.notificationModule.getNotificationById(req.params.id);
const teamId = req?.user?.teamId;
if (!teamId) {
throw this.errorService.createBadRequestError("Team ID is required");
}
if (!notification.teamId.equals(teamId)) {
throw this.errorService.createAuthorizationError();
}
return res.success({
msg: "Notification fetched successfully",
data: notification,
});
},
SERVICE_NAME,
"getNotificationById"
);
editNotification = this.asyncHandler(
async (req, res) => {
await createNotificationBodyValidation.validateAsync(req.body, {
abortEarly: false,
});
const teamId = req?.user?.teamId;
if (!teamId) {
throw this.errorService.createBadRequestError("Team ID is required");
}
const notification = await this.db.notificationModule.getNotificationById(req.params.id);
if (!notification.teamId.equals(teamId)) {
throw this.errorService.createAuthorizationError();
}
const editedNotification = await this.db.notificationModule.editNotification(req.params.id, req.body);
return res.success({
msg: "Notification updated successfully",
data: editedNotification,
});
},
SERVICE_NAME,
"editNotification"
);
testAllNotifications = this.asyncHandler(
async (req, res) => {
const monitorId = req.body.monitorId;
const teamId = req?.user?.teamId;
if (!teamId) {
throw this.errorService.createBadRequestError("Team ID is required");
}
const monitor = await this.db.monitorModule.getMonitorById(monitorId);
if (!monitor.teamId.equals(teamId)) {
throw this.errorService.createAuthorizationError();
}
const notifications = monitor.notifications;
if (notifications.length === 0) throw this.errorService.createBadRequestError("No notifications");
const result = await this.notificationService.testAllNotifications(notifications);
if (!result) throw this.errorService.createServerError("Failed to send all notifications");
return res.success({
msg: "All notifications sent successfully",
});
},
SERVICE_NAME,
"testAllNotifications"
);
}
export default NotificationController;
@@ -1,87 +0,0 @@
import BaseController from "./baseController.js";
const SERVICE_NAME = "JobQueueController";
class JobQueueController extends BaseController {
static SERVICE_NAME = SERVICE_NAME;
constructor(commonDependencies, { jobQueue }) {
super(commonDependencies);
this.jobQueue = jobQueue;
}
get serviceName() {
return JobQueueController.SERVICE_NAME;
}
getMetrics = this.asyncHandler(
async (req, res) => {
const metrics = await this.jobQueue.getMetrics();
res.success({
msg: this.stringService.queueGetMetrics,
data: metrics,
});
},
SERVICE_NAME,
"getMetrics"
);
getJobs = this.asyncHandler(
async (req, res) => {
const jobs = await this.jobQueue.getJobs();
return res.success({
msg: this.stringService.queueGetJobs,
data: jobs,
});
},
SERVICE_NAME,
"getJobs"
);
getAllMetrics = this.asyncHandler(
async (req, res) => {
const jobs = await this.jobQueue.getJobs();
const metrics = await this.jobQueue.getMetrics();
return res.success({
msg: this.stringService.queueGetAllMetrics,
data: { jobs, metrics },
});
},
SERVICE_NAME,
"getAllMetrics"
);
addJob = this.asyncHandler(
async (req, res) => {
await this.jobQueue.addJob(Math.random().toString(36).substring(7));
return res.success({
msg: this.stringService.queueAddJob,
});
},
SERVICE_NAME,
"addJob"
);
flushQueue = this.asyncHandler(
async (req, res) => {
const result = await this.jobQueue.flushQueues();
return res.success({
msg: this.stringService.jobQueueFlush,
data: result,
});
},
SERVICE_NAME,
"flushQueue"
);
checkQueueHealth = this.asyncHandler(
async (req, res) => {
const stuckQueues = await this.jobQueue.checkQueueHealth();
return res.success({
msg: this.stringService.queueHealthCheck,
data: stuckQueues,
});
},
SERVICE_NAME,
"checkQueueHealth"
);
}
export default JobQueueController;
@@ -1,122 +0,0 @@
import { updateAppSettingsBodyValidation } from "../../validation/joi.js";
import { sendTestEmailBodyValidation } from "../../validation/joi.js";
import BaseController from "./baseController.js";
const SERVICE_NAME = "SettingsController";
class SettingsController extends BaseController {
static SERVICE_NAME = SERVICE_NAME;
constructor(commonDependencies, { settingsService, emailService }) {
super(commonDependencies);
this.settingsService = settingsService;
this.emailService = emailService;
}
get serviceName() {
return SettingsController.SERVICE_NAME;
}
buildAppSettings = (dbSettings) => {
const sanitizedSettings = { ...dbSettings };
delete sanitizedSettings.version;
const returnSettings = {
pagespeedKeySet: false,
emailPasswordSet: false,
};
if (typeof sanitizedSettings.pagespeedApiKey !== "undefined") {
returnSettings.pagespeedKeySet = true;
delete sanitizedSettings.pagespeedApiKey;
}
if (typeof sanitizedSettings.systemEmailPassword !== "undefined") {
returnSettings.emailPasswordSet = true;
delete sanitizedSettings.systemEmailPassword;
}
returnSettings.settings = sanitizedSettings;
return returnSettings;
};
getAppSettings = this.asyncHandler(
async (req, res) => {
const dbSettings = await this.settingsService.getDBSettings();
const returnSettings = this.buildAppSettings(dbSettings);
return res.success({
msg: this.stringService.getAppSettings,
data: returnSettings,
});
},
SERVICE_NAME,
"getAppSettings"
);
updateAppSettings = this.asyncHandler(
async (req, res) => {
await updateAppSettingsBodyValidation.validateAsync(req.body);
const updatedSettings = await this.db.settingsModule.updateAppSettings(req.body);
const returnSettings = this.buildAppSettings(updatedSettings);
return res.success({
msg: this.stringService.updateAppSettings,
data: returnSettings,
});
},
SERVICE_NAME,
"updateAppSettings"
);
sendTestEmail = this.asyncHandler(
async (req, res) => {
await sendTestEmailBodyValidation.validateAsync(req.body);
const {
to,
systemEmailHost,
systemEmailPort,
systemEmailAddress,
systemEmailPassword,
systemEmailUser,
systemEmailConnectionHost,
systemEmailSecure,
systemEmailPool,
systemEmailIgnoreTLS,
systemEmailRequireTLS,
systemEmailRejectUnauthorized,
systemEmailTLSServername,
} = req.body;
const subject = this.stringService.testEmailSubject;
const context = { testName: "Monitoring System" };
const html = await this.emailService.buildEmail("testEmailTemplate", context);
const messageId = await this.emailService.sendEmail(to, subject, html, {
systemEmailHost,
systemEmailPort,
systemEmailUser,
systemEmailAddress,
systemEmailPassword,
systemEmailConnectionHost,
systemEmailSecure,
systemEmailPool,
systemEmailIgnoreTLS,
systemEmailRequireTLS,
systemEmailRejectUnauthorized,
systemEmailTLSServername,
});
if (!messageId) {
throw this.errorService.createServerError("Failed to send test email.");
}
return res.success({
msg: this.stringService.sendTestEmail,
data: { messageId },
});
},
SERVICE_NAME,
"sendTestEmail"
);
}
export default SettingsController;
@@ -1,108 +0,0 @@
import { createStatusPageBodyValidation, getStatusPageParamValidation, getStatusPageQueryValidation, imageValidation } from "../../validation/joi.js";
import BaseController from "./baseController.js";
const SERVICE_NAME = "statusPageController";
class StatusPageController extends BaseController {
static SERVICE_NAME = SERVICE_NAME;
constructor(commonDependencies) {
super(commonDependencies);
}
get serviceName() {
return StatusPageController.SERVICE_NAME;
}
createStatusPage = this.asyncHandler(
async (req, res) => {
await createStatusPageBodyValidation.validateAsync(req.body);
await imageValidation.validateAsync(req.file);
const { _id, teamId } = req.user;
const statusPage = await this.db.statusPageModule.createStatusPage({
statusPageData: req.body,
image: req.file,
userId: _id,
teamId,
});
return res.success({
msg: this.stringService.statusPageCreate,
data: statusPage,
});
},
SERVICE_NAME,
"createStatusPage"
);
updateStatusPage = this.asyncHandler(
async (req, res) => {
await createStatusPageBodyValidation.validateAsync(req.body);
await imageValidation.validateAsync(req.file);
const statusPage = await this.db.statusPageModule.updateStatusPage(req.body, req.file);
if (statusPage === null) {
throw this.errorService.createNotFoundError(this.stringService.statusPageNotFound);
}
return res.success({
msg: this.stringService.statusPageUpdate,
data: statusPage,
});
},
SERVICE_NAME,
"updateStatusPage"
);
getStatusPage = this.asyncHandler(
async (req, res) => {
const statusPage = await this.db.statusPageModule.getStatusPage();
return res.success({
msg: this.stringService.statusPageByUrl,
data: statusPage,
});
},
SERVICE_NAME,
"getStatusPage"
);
getStatusPageByUrl = this.asyncHandler(
async (req, res) => {
await getStatusPageParamValidation.validateAsync(req.params);
await getStatusPageQueryValidation.validateAsync(req.query);
const statusPage = await this.db.statusPageModule.getStatusPageByUrl(req.params.url);
return res.success({
msg: this.stringService.statusPageByUrl,
data: statusPage,
});
},
SERVICE_NAME,
"getStatusPageByUrl"
);
getStatusPagesByTeamId = this.asyncHandler(
async (req, res) => {
const teamId = req.user.teamId;
const statusPages = await this.db.statusPageModule.getStatusPagesByTeamId(teamId);
return res.success({
msg: this.stringService.statusPageByTeamId,
data: statusPages,
});
},
SERVICE_NAME,
"getStatusPagesByTeamId"
);
deleteStatusPage = this.asyncHandler(
async (req, res) => {
await this.db.statusPageModule.deleteStatusPage(req.params.url);
return res.success({
msg: this.stringService.statusPageDelete,
});
},
SERVICE_NAME,
"deleteStatusPage"
);
}
export default StatusPageController;
-150
View File
@@ -1,150 +0,0 @@
import { Request, Response, NextFunction } from "express";
import { encode, decode } from "../../utils/JWTUtils.js";
import AuthService from "../../service/v2/business/AuthService.js";
import ApiError from "../../utils/ApiError.js";
import InviteService from "../../service/v2/business/InviteService.js";
import { IInvite } from "../../db/v2/models/index.js";
class AuthController {
private authService: AuthService;
private inviteService: InviteService;
constructor(authService: AuthService, inviteService: InviteService) {
this.authService = authService;
this.inviteService = inviteService;
}
register = async (req: Request, res: Response, next: NextFunction) => {
try {
const { email, firstName, lastName, password } = req.body;
if (!email || !firstName || !lastName || !password) {
throw new Error("Email, firstName, lastName, and password are required");
}
const result = await this.authService.register({
email,
firstName,
lastName,
password,
});
const token = encode(result);
res.cookie("token", token, {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "strict",
maxAge: 7 * 24 * 60 * 60 * 1000, // 1 week
});
res.status(201).json({
message: "User created successfully",
});
} catch (error) {
next(error);
}
};
registerWithInvite = async (req: Request, res: Response, next: NextFunction) => {
try {
const token = req.params.token;
if (!token) {
throw new ApiError("Invite token is required", 400);
}
const invite: IInvite = await this.inviteService.get(token);
const { firstName, lastName, password } = req.body;
const email = invite?.email;
const roles = invite?.roles;
if (!email || !firstName || !lastName || !password || !roles || roles.length === 0) {
throw new Error("Email, firstName, lastName, password, and roles are required");
}
const result = await this.authService.registerWithInvite({
email,
firstName,
lastName,
password,
roles,
});
if (!result) {
throw new Error("Registration failed");
}
await this.inviteService.delete(invite._id.toString());
const jwt = encode(result);
res.cookie("token", jwt, {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "strict",
maxAge: 7 * 24 * 60 * 60 * 1000, // 1 week
});
res.status(201).json({ message: "User created successfully" });
} catch (error) {
next(error);
}
};
login = async (req: Request, res: Response, next: NextFunction) => {
try {
const { email, password } = req.body;
// Validation
if (!email || !password) {
return res.status(400).json({ message: "Email and password are required" });
}
const result = await this.authService.login({ email, password });
const token = encode(result);
res.cookie("token", token, {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "strict",
maxAge: 7 * 24 * 60 * 60 * 1000, // 1 week
});
res.status(200).json({
message: "Login successful",
});
} catch (error) {
next(error);
}
};
logout = (req: Request, res: Response) => {
res.clearCookie("token", {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "strict",
});
res.status(200).json({ message: "Logout successful" });
};
me = (req: Request, res: Response, next: NextFunction) => {
return res.status(200).json({ message: "OK" });
};
cleanup = async (req: Request, res: Response) => {
try {
await this.authService.cleanup();
res.status(200).json({ message: "Cleanup successful" });
} catch (error) {}
};
cleanMonitors = async (req: Request, res: Response) => {
try {
await this.authService.cleanMonitors();
res.status(200).json({ message: "Monitors cleanup successful" });
} catch (error) {
res.status(500).json({ message: "Internal server error" });
}
};
}
export default AuthController;
@@ -1,62 +0,0 @@
import { Request, Response, NextFunction } from "express";
import InviteService from "../../service/v2/business/InviteService.js";
class InviteController {
private inviteService: InviteService;
constructor(inviteService: InviteService) {
this.inviteService = inviteService;
}
create = async (req: Request, res: Response, next: NextFunction) => {
try {
const tokenizedUser = req.user;
if (!tokenizedUser) {
return res.status(401).json({ message: "Unauthorized" });
}
const invite = await this.inviteService.create(tokenizedUser, req.body);
res.status(201).json({ message: "OK", data: invite });
} catch (error: any) {
next(error);
}
};
getAll = async (req: Request, res: Response, next: NextFunction) => {
try {
const invites = await this.inviteService.getAll();
res.status(200).json({
message: "OK",
data: invites,
});
} catch (error) {
next(error);
}
};
get = async (req: Request, res: Response, next: NextFunction) => {
try {
const token = req.params.token;
if (!token) {
return res.status(400).json({ message: "Token parameter is required" });
}
const invite = await this.inviteService.get(token);
res.status(200).json({ message: "OK", data: invite });
} catch (error) {
next(error);
}
};
delete = async (req: Request, res: Response, next: NextFunction) => {
try {
const id = req.params.id;
if (!id) {
return res.status(400).json({ message: "ID parameter is required" });
}
await this.inviteService.delete(id);
res.status(204).json({ message: "OK" });
} catch (error: any) {
next(error);
}
};
}
export default InviteController;
@@ -1,96 +0,0 @@
import { Request, Response, NextFunction } from "express";
import MaintenanceService from "../../service/v2/business/MaintenanceService.js";
class MaintenanceController {
private maintenanceService: MaintenanceService;
constructor(maintenanceService: MaintenanceService) {
this.maintenanceService = maintenanceService;
}
create = async (req: Request, res: Response, next: NextFunction) => {
try {
const tokenizedUser = req.user;
if (!tokenizedUser) {
return res.status(401).json({ message: "Unauthorized" });
}
const maintenance = await this.maintenanceService.create(tokenizedUser, req.body);
res.status(201).json({ message: "OK", data: maintenance });
} catch (error) {
next(error);
}
};
getAll = async (req: Request, res: Response, next: NextFunction) => {
try {
const maintenances = await this.maintenanceService.getAll();
res.status(200).json({
message: "OK",
data: maintenances,
});
} catch (error) {
next(error);
}
};
toggleActive = async (req: Request, res: Response, next: NextFunction) => {
try {
const tokenizedUser = req.user;
if (!tokenizedUser) {
return res.status(401).json({ message: "Unauthorized" });
}
const id = req.params.id;
if (!id) {
return res.status(400).json({ message: "ID parameter is required" });
}
const maintenance = await this.maintenanceService.toggleActive(tokenizedUser, id);
res.status(200).json({ message: "OK", data: maintenance });
} catch (error) {
next(error);
}
};
update = async (req: Request, res: Response, next: NextFunction) => {
try {
const tokenizedUser = req.user;
if (!tokenizedUser) {
return res.status(401).json({ message: "Unauthorized" });
}
const id = req.params.id;
if (!id) {
return res.status(400).json({ message: "ID parameter is required" });
}
const updatedMaintenance = await this.maintenanceService.update(tokenizedUser, id, req.body);
res.status(200).json({ message: "OK", data: updatedMaintenance });
} catch (error) {
next(error);
}
};
get = async (req: Request, res: Response, next: NextFunction) => {
try {
const id = req.params.id;
if (!id) {
return res.status(400).json({ message: "ID parameter is required" });
}
const maintenance = await this.maintenanceService.get(id);
res.status(200).json({ message: "OK", data: maintenance });
} catch (error) {
next(error);
}
};
delete = async (req: Request, res: Response, next: NextFunction) => {
try {
const id = req.params.id;
if (!id) {
return res.status(400).json({ message: "ID parameter is required" });
}
await this.maintenanceService.delete(id);
res.status(204).json({ message: "OK" });
} catch (error) {
next(error);
}
};
}
export default MaintenanceController;
@@ -1,191 +0,0 @@
import { Request, Response, NextFunction } from "express";
import ApiError from "../../utils/ApiError.js";
import MonitorService from "../../service/v2/business/MonitorService.js";
import { MonitorType } from "../../db/v2/models/monitors/Monitor.js";
import CheckService from "../../service/v2/business/CheckService.js";
class MonitorController {
private monitorService: MonitorService;
private checkService: CheckService;
constructor(monitorService: MonitorService, checkService: CheckService) {
this.monitorService = monitorService;
this.checkService = checkService;
}
create = async (req: Request, res: Response, next: NextFunction) => {
try {
const tokenizedUser = req.user;
if (!tokenizedUser) {
return res.status(401).json({ message: "Unauthorized" });
}
const monitor = await this.monitorService.create(tokenizedUser, req.body);
res.status(201).json({
message: "Monitor created successfully",
data: monitor,
});
} catch (error) {
next(error);
}
};
getAll = async (req: Request, res: Response, next: NextFunction) => {
try {
const tokenizedUser = req.user;
if (!tokenizedUser) {
return res.status(401).json({ message: "Unauthorized" });
}
let monitors;
if (req.query.embedChecks === "true") {
const page = Math.max(1, Number(req.query.page) || 1);
const limit = Math.max(1, Number(req.query.limit) || 10);
const type: MonitorType[] = req.query.type as MonitorType[];
monitors = await this.monitorService.getAllEmbedChecks(page, limit, type);
} else {
monitors = await this.monitorService.getAll();
}
res.status(200).json({
message: "Monitors retrieved successfully",
data: monitors,
});
} catch (error) {
next(error);
}
};
getChecks = async (req: Request, res: Response, next: NextFunction) => {
try {
const tokenizedUser = req.user;
if (!tokenizedUser) {
return res.status(401).json({ message: "Unauthorized" });
}
const id = req.params.id;
if (!id) {
throw new ApiError("Monitor ID is required", 400);
}
const page = Number(req.query.page);
const rowsPerPage = Number(req.query.rowsPerPage);
if (isNaN(page)) throw new ApiError("Page query parameter must be a number", 400);
if (isNaN(rowsPerPage)) throw new ApiError("rowsPerPage query parameter must be a number", 400);
if (page < 0) throw new ApiError("Page must be greater than 0", 400);
if (rowsPerPage < 0) throw new ApiError("rowsPerPage must be greater than 0", 400);
const { count, checks } = await this.checkService.getChecks(id, page, rowsPerPage);
res.status(200).json({
message: "Checks retrieved successfully",
data: { count, checks },
});
} catch (error) {
next(error);
}
};
toggleActive = async (req: Request, res: Response, next: NextFunction) => {
try {
const tokenizedUser = req.user;
if (!tokenizedUser) {
return res.status(401).json({ message: "Unauthorized" });
}
const id = req.params.id;
if (!id) {
throw new ApiError("Monitor ID is required", 400);
}
const monitor = await this.monitorService.toggleActive(id, tokenizedUser);
res.status(200).json({
message: "Monitor paused/unpaused successfully",
data: monitor,
});
} catch (error) {
next(error);
}
};
get = async (req: Request, res: Response, next: NextFunction) => {
try {
const tokenizedUser = req.user;
if (!tokenizedUser) {
return res.status(401).json({ message: "Unauthorized" });
}
const id = req.params.id;
if (!id) {
throw new ApiError("Monitor ID is required", 400);
}
const range = req.query.range;
if (!range || typeof range !== "string") throw new ApiError("Range query parameter is required", 400);
let monitor;
const status = req.query.status;
if (status && typeof status !== "string") {
throw new ApiError("Status query parameter must be a string", 400);
}
if (req.query.embedChecks === "true") {
monitor = await this.monitorService.getEmbedChecks(id, range, status);
} else {
monitor = await this.monitorService.get(id);
}
res.status(200).json({
message: "Monitor retrieved successfully",
data: monitor,
});
} catch (error) {
next(error);
}
};
update = async (req: Request, res: Response, next: NextFunction) => {
try {
const tokenizedUser = req.user;
if (!tokenizedUser) {
return res.status(401).json({ message: "Unauthorized" });
}
const id = req.params.id;
if (!id) {
throw new ApiError("Monitor ID is required", 400);
}
const monitor = await this.monitorService.update(tokenizedUser, id, req.body);
res.status(200).json({
message: "Monitor updated successfully",
data: monitor,
});
} catch (error) {
next(error);
}
};
delete = async (req: Request, res: Response, next: NextFunction) => {
try {
const tokenizedUser = req.user;
if (!tokenizedUser) {
return res.status(401).json({ message: "Unauthorized" });
}
const id = req.params.id;
if (!id) {
throw new ApiError("Monitor ID is required", 400);
}
await this.monitorService.delete(id);
res.status(200).json({
message: "Monitor deleted successfully",
});
} catch (error) {
next(error);
}
};
}
export default MonitorController;
@@ -1,96 +0,0 @@
import { Request, Response, NextFunction } from "express";
import NotificationService from "../../service/v2/business/NotificationChannelService.js";
class NotificationChannelController {
private notificationService: NotificationService;
constructor(notificationService: NotificationService) {
this.notificationService = notificationService;
}
create = async (req: Request, res: Response, next: NextFunction) => {
try {
const tokenizedUser = req.user;
if (!tokenizedUser) {
return res.status(401).json({ message: "Unauthorized" });
}
const channel = await this.notificationService.create(tokenizedUser, req.body);
res.status(201).json({ message: "OK", data: channel });
} catch (error) {
next(error);
}
};
getAll = async (req: Request, res: Response, next: NextFunction) => {
try {
const notificationChannels = await this.notificationService.getAll();
res.status(200).json({
message: "OK",
data: notificationChannels,
});
} catch (error) {
next(error);
}
};
toggleActive = async (req: Request, res: Response, next: NextFunction) => {
try {
const tokenizedUser = req.user;
if (!tokenizedUser) {
return res.status(401).json({ message: "Unauthorized" });
}
const id = req.params.id;
if (!id) {
return res.status(400).json({ message: "ID parameter is required" });
}
const notificationChannel = await this.notificationService.toggleActive(tokenizedUser, id);
res.status(200).json({ message: "OK", data: notificationChannel });
} catch (error) {
next(error);
}
};
update = async (req: Request, res: Response, next: NextFunction) => {
try {
const tokenizedUser = req.user;
if (!tokenizedUser) {
return res.status(401).json({ message: "Unauthorized" });
}
const id = req.params.id;
if (!id) {
return res.status(400).json({ message: "ID parameter is required" });
}
const updatedChannel = await this.notificationService.update(tokenizedUser, id, req.body);
res.status(200).json({ message: "OK", data: updatedChannel });
} catch (error) {
next(error);
}
};
get = async (req: Request, res: Response, next: NextFunction) => {
try {
const id = req.params.id;
if (!id) {
return res.status(400).json({ message: "ID parameter is required" });
}
const notificationChannel = await this.notificationService.get(id);
res.status(200).json({ message: "OK", data: notificationChannel });
} catch (error) {
next(error);
}
};
delete = async (req: Request, res: Response, next: NextFunction) => {
try {
const id = req.params.id;
if (!id) {
return res.status(400).json({ message: "ID parameter is required" });
}
await this.notificationService.delete(id);
res.status(204).json({ message: "OK" });
} catch (error) {
next(error);
}
};
}
export default NotificationChannelController;
@@ -1,29 +0,0 @@
import { Request, Response, NextFunction } from "express";
import QueueService from "../../service/v2/business/QueueService.js";
class QueueController {
private queueService: QueueService;
constructor(queueService: QueueService) {
this.queueService = queueService;
}
getJobs = async (req: Request, res: Response, next: NextFunction) => {
try {
const jobs = await this.queueService.getJobs();
res.status(200).json({ message: "ok", data: jobs });
} catch (error) {
next(error);
}
};
getMetrics = async (req: Request, res: Response, next: NextFunction) => {
const metrics = await this.queueService.getMetrics();
res.status(200).json({ message: "ok", data: metrics });
};
flush = async (req: Request, res: Response, next: NextFunction) => {
const result = await this.queueService.flush();
res.status(200).json({ message: "ok", flushed: result });
};
}
export default QueueController;
+43
View File
@@ -0,0 +1,43 @@
import mongoose from "mongoose";
import { getChildLogger } from "@/logger/Logger.js";
const MONGODB_URI = process.env.MONGODB_URI || "mongodb://localhost:27017/saas";
const RETRY_INTERVAL_MS = 2000; // wait 2 seconds between retries
const MAX_RETRIES = 10; // number of retries before giving up
const logger = getChildLogger("MongoDB");
export const connectDatabase = async (): Promise<boolean> => {
for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {
try {
await mongoose.connect(MONGODB_URI);
logger.info("Connected to MongoDB");
return true;
} catch (error) {
logger.error(
`MongoDB connection attempt ${attempt} failed. Retrying in ${RETRY_INTERVAL_MS}ms...`,
error
);
if (attempt === MAX_RETRIES) {
logger.error(
"Could not connect to MongoDB after max retries. Exiting."
);
process.exit(1);
}
await new Promise((resolve) => setTimeout(resolve, RETRY_INTERVAL_MS));
}
}
return false;
};
export const disconnectDatabase = async (): Promise<boolean> => {
try {
await mongoose.disconnect();
logger.info("Disconnected from MongoDB");
return true;
} catch (error) {
logger.error("MongoDB disconnection error:", error);
return false;
}
};
+44
View File
@@ -0,0 +1,44 @@
import mongoose, { Schema, Document, Types } from "mongoose";
export interface IInvite extends Document {
_id: Types.ObjectId;
orgId: Types.ObjectId;
orgRoleId?: Types.ObjectId;
teamId: Types.ObjectId;
teamRoleId: Types.ObjectId;
email: string;
tokenHash: string;
createdBy: Types.ObjectId;
updatedBy: Types.ObjectId;
expiry: Date;
createdAt: Date;
updatedAt: Date;
}
const InviteSchema = new Schema<IInvite>(
{
orgId: { type: Schema.Types.ObjectId, ref: "Org", required: true },
teamId: { type: Schema.Types.ObjectId, ref: "Team", required: true },
orgRoleId: { type: Schema.Types.ObjectId, ref: "Role" },
teamRoleId: { type: Schema.Types.ObjectId, ref: "Role", required: true },
email: {
type: String,
required: true,
unique: true,
trim: true,
lowercase: true,
},
tokenHash: { type: String, required: true, unique: true },
expiry: {
type: Date,
default: () => new Date(Date.now() + 24 * 60 * 60 * 1000),
expires: 0,
},
createdBy: { type: Schema.Types.ObjectId, ref: "User", required: true },
updatedBy: { type: Schema.Types.ObjectId, ref: "User", required: true },
},
{ timestamps: true }
);
export const Invite = mongoose.model<IInvite>("Invite", InviteSchema);
+18
View File
@@ -0,0 +1,18 @@
import mongoose, { Schema, Document, Types } from "mongoose";
export interface IOrg extends Document {
_id: Types.ObjectId;
name: string;
ownerId: Types.ObjectId;
createdAt: Date;
updatedAt: Date;
}
const orgSchema = new Schema<IOrg>(
{
name: { type: String, required: true },
ownerId: { type: Schema.Types.ObjectId, ref: "User", required: true },
},
{ timestamps: true }
);
export const Org = mongoose.model<IOrg>("Org", orgSchema);
@@ -0,0 +1,51 @@
import mongoose, { Schema, Document, Types } from "mongoose";
import { invalidateCachesForUser } from "@/middleware/AddUserContext.js";
export interface IOrgMembership extends Document {
_id: Types.ObjectId;
orgId: Types.ObjectId;
userId: Types.ObjectId;
roleId?: Types.ObjectId;
role: string;
createdAt: Date;
updatedAt: Date;
}
const orgMembershipSchema = new Schema<IOrgMembership>(
{
orgId: { type: Schema.Types.ObjectId, ref: "Org", required: true },
userId: { type: Schema.Types.ObjectId, ref: "User", required: true },
roleId: { type: Schema.Types.ObjectId, ref: "Role" },
},
{ timestamps: true }
);
orgMembershipSchema.post<IOrgMembership>("save", async function (doc) {
invalidateCachesForUser(doc.userId.toString());
});
orgMembershipSchema.post<IOrgMembership>(
"deleteOne",
{ document: true, query: false },
async function (doc) {
invalidateCachesForUser(doc.userId.toString());
}
);
orgMembershipSchema.post("findOneAndDelete", function (doc: IOrgMembership) {
if (!doc) return;
invalidateCachesForUser(doc.userId.toString());
});
orgMembershipSchema.post(
"findOneAndUpdate",
async function (doc: IOrgMembership) {
if (!doc) return;
invalidateCachesForUser(doc.userId.toString());
}
);
export const OrgMembership = mongoose.model<IOrgMembership>(
"OrgMembership",
orgMembershipSchema
);
+26
View File
@@ -0,0 +1,26 @@
import mongoose, { Schema, Document, Types } from "mongoose";
export const ScopeTypes = ["organization", "team"] as const;
export type ScopeType = (typeof ScopeTypes)[number];
export interface IRole extends Document {
_id: Types.ObjectId;
organizationId: Types.ObjectId;
name: string;
scope: ScopeType;
permissions: string[];
createdAt: Date;
updatedAt: Date;
}
const roleSchema = new Schema<IRole>(
{
organizationId: { type: Schema.Types.ObjectId, ref: "Org" },
name: { type: String, required: true },
scope: { type: String, enum: ScopeTypes, required: true },
permissions: { type: [String], default: [] },
},
{ timestamps: true }
);
export const Role = mongoose.model<IRole>("Role", roleSchema);
+22
View File
@@ -0,0 +1,22 @@
import mongoose, { Schema, Document, Types } from "mongoose";
export interface ITeam extends Document {
_id: Types.ObjectId;
orgId: Types.ObjectId;
name: string;
description?: string;
isSystem?: boolean;
createdAt: Date;
updatedAt: Date;
}
const teamSchema = new Schema<ITeam>(
{
orgId: { type: Schema.Types.ObjectId, ref: "Org", required: true },
name: { type: String, required: true },
description: { type: String, required: false },
isSystem: { type: Boolean, default: false },
},
{ timestamps: true }
);
export const Team = mongoose.model<ITeam>("Team", teamSchema);
@@ -0,0 +1,51 @@
import mongoose, { Schema, Document, Types } from "mongoose";
import { invalidateCachesForUser } from "@/middleware/AddUserContext.js";
export interface ITeamMembership extends Document {
_id: Types.ObjectId;
orgId: Types.ObjectId;
teamId: Types.ObjectId;
userId: Types.ObjectId;
roleId: Types.ObjectId;
createdAt: Date;
updatedAt: Date;
}
const teamMembershipSchema = new Schema<ITeamMembership>(
{
orgId: { type: Schema.Types.ObjectId, ref: "Org", required: true },
teamId: { type: Schema.Types.ObjectId, ref: "Team", required: true },
userId: { type: Schema.Types.ObjectId, ref: "User", required: true },
roleId: { type: Schema.Types.ObjectId, ref: "Role" },
},
{ timestamps: true }
);
teamMembershipSchema.post<ITeamMembership>("save", async function (doc) {
invalidateCachesForUser(doc.userId.toString());
});
teamMembershipSchema.post<ITeamMembership>(
"deleteOne",
{ document: true, query: false },
async function (doc) {
invalidateCachesForUser(doc.userId.toString());
}
);
teamMembershipSchema.post("findOneAndDelete", function (doc: ITeamMembership) {
if (!doc) return;
invalidateCachesForUser(doc.userId.toString());
});
teamMembershipSchema.post(
"findOneAndUpdate",
async function (doc: ITeamMembership) {
if (!doc) return;
invalidateCachesForUser(doc.userId.toString());
}
);
export const TeamMembership = mongoose.model<ITeamMembership>(
"TeamMembership",
teamMembershipSchema
);
+67
View File
@@ -0,0 +1,67 @@
import mongoose, { Schema, Document, Types } from "mongoose";
import { IRole, ITeam } from "@/db/models/index.js";
export interface ITokenizedUser {
sub: string;
email: string;
orgId: string;
}
export interface IUserContext {
sub: string;
email: string;
orgId: string;
teamIds?: string[];
teams?: ITeam[];
currentTeamId?: string;
roles?: {
orgRole?: IRole;
teamRole: IRole;
};
}
export interface IUserReturnable {
id: string;
email: string;
firstName: string;
lastName: string;
org: {
name: string;
permissions: string[];
};
teams: {
id: string;
name: string;
permissions: string[];
}[];
}
export interface IUser extends Document {
_id: Types.ObjectId;
firstName: string;
lastName: string;
email: string;
passwordHash: string;
lastLoginAt?: Date;
createdAt: Date;
updatedAt: Date;
}
export interface IUserProfile {
firstName?: string;
lastName?: string;
password?: string;
confirmPassword?: string;
}
const userSchema = new Schema<IUser>(
{
firstName: { type: String, required: true },
lastName: { type: String, required: true },
email: { type: String, required: true, unique: true },
passwordHash: { type: String, required: true },
lastLoginAt: { type: Date },
},
{ timestamps: true }
);
export const User = mongoose.model<IUser>("User", userSchema);
+315
View File
@@ -0,0 +1,315 @@
import mongoose, { Schema, Document, Types } from "mongoose";
import {
MonitorType,
MonitorTypes,
MonitorStatus,
MonitorStatuses,
} from "../monitors/Monitor.js";
import type { Response } from "got";
export type GotTimings = Response["timings"];
export interface ITimingPhases {
wait: number;
dns: number;
tcp: number;
tls: number;
request: number;
firstByte: number;
download: number;
total: number;
}
export interface ICpuInfo {
physical_core: number;
logical_core: number;
frequency: number;
current_frequency: number;
temperature: number[]; // per-core temps
free_percent: number;
usage_percent: number;
}
export interface IMemoryInfo {
total_bytes: number;
available_bytes: number;
used_bytes: number;
usage_percent: number;
}
export interface IHostInfo {
os?: string;
platform?: string;
kernel_version?: string;
pretty_name?: string;
}
export interface IDiskInfo {
device: string;
total_bytes: number;
free_bytes: number;
used_bytes: number;
usage_percent: number;
total_inodes?: number;
free_inodes?: number;
used_inodes?: number;
inodes_usage_percent?: number;
read_bytes?: number;
write_bytes?: number;
read_time?: number;
write_time?: number;
}
export interface INetInfo {
name: string;
bytes_sent: number;
bytes_recv: number;
packets_sent: number;
packets_recv: number;
err_in: number;
err_out: number;
drop_in: number;
drop_out: number;
fifo_in: number;
fifo_out: number;
}
export interface ICaptureInfo {
version?: string;
mode?: string;
}
export interface ISystemInfo {
cpu: ICpuInfo;
memory: IMemoryInfo;
disk: IDiskInfo[];
host: IHostInfo;
net: INetInfo[];
}
export interface ILighthouseAudit {
id?: string;
title?: string;
score?: number | null;
displayValue?: string;
numericValue?: number;
numericUnit?: string;
}
export interface ILighthouseCategories {
accessibility?: { score?: number | null };
"best-practices"?: { score?: number | null };
seo?: { score?: number | null };
performance?: { score?: number | null };
}
export interface ILighthouseResult {
categories?: ILighthouseCategories;
audits?: Record<string, ILighthouseAudit>;
}
export interface ICheckLighthouseFields {
accessibility: number;
bestPractices: number;
seo: number;
performance: number;
audits: {
cls: ILighthouseAudit;
si: ILighthouseAudit;
fcp: ILighthouseAudit;
lcp: ILighthouseAudit;
tbt: ILighthouseAudit;
};
}
export interface ICheck extends Document {
_id: Types.ObjectId;
metadata: {
monitorId: Types.ObjectId;
teamId: Types.ObjectId;
type: MonitorType;
};
status: MonitorStatus;
httpStatusCode?: number;
message: string;
responseTime?: number;
timings?: GotTimings;
errorMessage?: string;
ackAt?: Date;
ackBy?: Types.ObjectId;
system?: ISystemInfo;
capture?: ICaptureInfo;
lighthouse?: ICheckLighthouseFields;
createdAt: Date;
updatedAt: Date;
expiry: Date;
}
const CheckSchema = new Schema<ICheck>(
{
metadata: {
monitorId: {
type: Schema.Types.ObjectId,
ref: "Monitor",
required: true,
},
teamId: {
type: Schema.Types.ObjectId,
ref: "Team",
required: true,
},
type: {
type: String,
required: true,
enum: MonitorTypes,
},
},
status: {
type: String,
required: true,
enum: MonitorStatuses,
},
httpStatusCode: { type: Number },
message: { type: String, trim: true },
responseTime: { type: Number },
timings: {
start: { type: Date },
socket: { type: Date },
lookup: { type: Date },
connect: { type: Date },
secureConnect: { type: Date },
response: { type: Date },
end: { type: Date },
phases: {
wait: { type: Number },
dns: { type: Number },
tcp: { type: Number },
tls: { type: Number },
request: { type: Number },
firstByte: { type: Number },
download: { type: Number },
total: { type: Number },
},
},
system: {
type: {
cpu: {
physical_core: { type: Number },
logical_core: { type: Number },
frequency: { type: Number },
current_frequency: { type: Number },
temperature: [{ type: Number }],
free_percent: { type: Number },
usage_percent: { type: Number },
},
memory: {
total_bytes: { type: Number },
available_bytes: { type: Number },
used_bytes: { type: Number },
usage_percent: { type: Number },
},
disk: [
{
device: { type: String },
total_bytes: { type: Number },
free_bytes: { type: Number },
used_bytes: { type: Number },
usage_percent: { type: Number },
total_inodes: { type: Number },
free_inodes: { type: Number },
used_inodes: { type: Number },
inodes_usage_percent: { type: Number },
read_bytes: { type: Number },
write_bytes: { type: Number },
read_time: { type: Number },
write_time: { type: Number },
},
],
host: {
os: { type: String },
platform: { type: String },
kernel_version: { type: String },
pretty_name: { type: String },
},
net: [
{
name: { type: String },
bytes_sent: { type: Number },
bytes_recv: { type: Number },
packets_sent: { type: Number },
packets_recv: { type: Number },
err_in: { type: Number },
err_out: { type: Number },
drop_in: { type: Number },
drop_out: { type: Number },
fifo_in: { type: Number },
fifo_out: { type: Number },
},
],
},
required: false,
},
capture: {
type: {
version: { type: String },
mode: { type: String },
},
required: false,
},
lighthouse: {
accessibility: { type: Number, required: false },
bestPractices: { type: Number, required: false },
seo: { type: Number, required: false },
performance: { type: Number, required: false },
audits: {
cls: {
type: Object,
},
si: {
type: Object,
},
fcp: {
type: Object,
},
lcp: {
type: Object,
},
tbt: {
type: Object,
},
},
type: {
accessibility: { type: Number },
bestPractices: { type: Number },
seo: { type: Number },
performance: { type: Number },
audits: {
cls: { type: Object },
si: { type: Object },
fcp: { type: Object },
lcp: { type: Object },
tbt: { type: Object },
},
},
required: false,
},
errorMessage: { type: String, trim: true },
ackAt: { type: Date },
ackBy: { type: Schema.Types.ObjectId, ref: "User" },
expiry: {
type: Date,
default: Date.now,
expires: 60 * 60 * 24 * 30,
},
},
{
timestamps: true,
timeseries: {
timeField: "createdAt",
metaField: "metadata",
granularity: "seconds",
},
}
);
export const Check = mongoose.model<ICheck>("Check", CheckSchema);
@@ -0,0 +1,39 @@
import mongoose, { Schema, Document, Types } from "mongoose";
export const ResolutionTypes = ["auto", "manual"] as const;
export type ResolutionType = (typeof ResolutionTypes)[number];
export interface IIncident {
_id: Types.ObjectId;
monitorId: Types.ObjectId;
teamId: Types.ObjectId;
startedAt: Date;
startCheck: Types.ObjectId;
endedAt?: Date;
endCheck?: Types.ObjectId;
resolved: boolean;
resolvedBy?: Types.ObjectId;
resolutionType?: ResolutionType;
resolutionNote?: string;
}
const IncidentSchema = new Schema<IIncident>(
{
monitorId: { type: Schema.Types.ObjectId, ref: "Monitor", required: true },
teamId: { type: Schema.Types.ObjectId, ref: "Team", required: true },
startedAt: { type: Date, required: true },
startCheck: { type: Schema.Types.ObjectId, ref: "Check", required: true },
endedAt: { type: Date },
endCheck: { type: Schema.Types.ObjectId, ref: "Check" },
resolved: { type: Boolean, default: false },
resolvedBy: { type: Schema.Types.ObjectId, ref: "User" },
resolutionType: {
type: String,
enum: ResolutionTypes,
},
resolutionNote: { type: String },
},
{ timestamps: true }
);
export const Incident = mongoose.model<IIncident>("Incident", IncidentSchema);
+58
View File
@@ -0,0 +1,58 @@
export { Check } from "./checks/Check.js";
export type {
ICheck,
ISystemInfo,
ICaptureInfo,
ILighthouseResult,
} from "./checks/Check.js";
export { Monitor, MonitorStatuses } from "./monitors/Monitor.js";
export type { IMonitor } from "./monitors/Monitor.js";
export { MonitorStats } from "./monitors/MonitorStats.js";
export type { IMonitorStats } from "./monitors/MonitorStats.js";
export { User } from "./auth/User.js";
export type {
IUser,
ITokenizedUser,
IUserReturnable,
IUserContext,
IUserProfile,
} from "./auth/User.js";
export {
NotificationChannel,
ChannelTypes,
} from "./notification-channel/NotificationChannel.js";
export type { INotificationChannel } from "./notification-channel/NotificationChannel.js";
export { Invite } from "./auth/Invite.js";
export type { IInvite } from "./auth/Invite.js";
export { Role } from "./auth/Role.js";
export type { IRole } from "./auth/Role.js";
export { Maintenance, MaintenanceRepeats } from "./maintenance/Maintenance.js";
export type { IMaintenance } from "./maintenance/Maintenance.js";
export { Org } from "./auth/Org.js";
export type { IOrg } from "./auth/Org.js";
export { OrgMembership } from "./auth/OrgMembership.js";
export type { IOrgMembership } from "./auth/OrgMembership.js";
export { Team } from "./auth/Team.js";
export type { ITeam } from "./auth/Team.js";
export { TeamMembership } from "./auth/TeamMembership.js";
export type { ITeamMembership } from "./auth/TeamMembership.js";
export { StatusPage } from "./status-page/StatusPage.js";
export type { IStatusPage } from "./status-page/StatusPage.js";
export { RecoveryToken } from "./recovery/RecoveryToken.js";
export type { IRecoveryToken } from "./recovery/RecoveryToken.js";
export { Incident, ResolutionTypes } from "./incidents/Incident.js";
export type { IIncident, ResolutionType } from "./incidents/Incident.js";
@@ -0,0 +1,54 @@
import mongoose, { Schema, Document, Types } from "mongoose";
export const MaintenanceRepeats = ["no repeat", "daily", "weekly"] as const;
export type MaintenanceRepeat = (typeof MaintenanceRepeats)[number];
export interface IMaintenance extends Document {
_id: Types.ObjectId;
orgId: Types.ObjectId;
teamId: Types.ObjectId;
name: string;
isActive: boolean;
repeat: MaintenanceRepeat;
monitors: Types.ObjectId[];
startTime: Date;
endTime: Date;
createdBy: Types.ObjectId;
updatedBy: Types.ObjectId;
createdAt: Date;
updatedAt: Date;
}
const MaintenanceSchema = new Schema<IMaintenance>(
{
orgId: { type: Schema.Types.ObjectId, ref: "Org", required: true },
teamId: { type: Schema.Types.ObjectId, ref: "Team", required: true },
name: { type: String, required: true, trim: true },
isActive: { type: Boolean, required: true, default: true },
repeat: {
type: String,
enum: MaintenanceRepeats,
required: false,
default: null,
},
monitors: [
{
type: Schema.Types.ObjectId,
ref: "Monitor",
required: true,
},
],
startTime: { type: Date, required: true },
endTime: { type: Date, required: true },
createdBy: { type: Schema.Types.ObjectId, ref: "User", required: true },
updatedBy: { type: Schema.Types.ObjectId, ref: "User", required: true },
},
{ timestamps: true }
);
MaintenanceSchema.index({ isActive: 1 });
MaintenanceSchema.index({ startTime: 1 });
MaintenanceSchema.index({ endTime: 1 });
export const Maintenance = mongoose.model<IMaintenance>(
"Maintenance",
MaintenanceSchema
);
+134
View File
@@ -0,0 +1,134 @@
import mongoose, { Schema, Document, Types } from "mongoose";
import { Check, MonitorStats } from "@/db/models/index.js";
export const MonitorTypes = [
"http",
"https",
"ping",
"infrastructure",
"pagespeed",
] as const;
export type MonitorType = (typeof MonitorTypes)[number];
export const MonitorStatuses = [
"up",
"down",
"paused",
"initializing",
] as const;
export type MonitorStatus = (typeof MonitorStatuses)[number];
export interface IMonitor extends Document {
_id: Types.ObjectId;
orgId: Types.ObjectId;
teamId: Types.ObjectId;
name: string;
url: string;
secret?: string;
type: MonitorType;
interval: number; // in ms
isActive: boolean;
status: MonitorStatus;
n: number; // Number of consecutive successes required to change status
lastCheckedAt?: Date;
latestChecks: {
status: MonitorStatus;
responseTime: number;
checkedAt: Date;
}[];
notificationChannels?: Types.ObjectId[];
createdBy: Types.ObjectId;
updatedBy: Types.ObjectId;
createdAt: Date;
updatedAt: Date;
}
const MonitorSchema = new Schema<IMonitor>(
{
orgId: { type: Schema.Types.ObjectId, ref: "Org", required: true },
teamId: { type: Schema.Types.ObjectId, ref: "Team", required: true },
name: { type: String, required: true, trim: true, maxlength: 100 },
url: { type: String, required: true, trim: true },
secret: { type: String, required: false },
type: {
type: String,
required: true,
enum: MonitorTypes,
},
interval: { type: Number, required: true, default: 60000 },
isActive: { type: Boolean, required: true, default: true },
status: {
type: String,
required: true,
default: "initializing",
enum: MonitorStatuses,
},
n: { type: Number, required: true, default: 1 },
lastCheckedAt: { type: Date },
latestChecks: {
type: [
{
status: {
type: String,
required: true,
enum: MonitorStatuses,
},
responseTime: { type: Number, required: true },
checkedAt: { type: Date, required: true },
},
],
default: [],
},
notificationChannels: {
type: [{ type: Schema.Types.ObjectId, ref: "NotificationChannel" }],
default: [],
},
createdBy: { type: Schema.Types.ObjectId, ref: "User", required: true },
updatedBy: { type: Schema.Types.ObjectId, ref: "User", required: true },
},
{ timestamps: true }
);
MonitorSchema.pre(
"deleteOne",
{ document: true, query: false },
async function (next) {
try {
const monitorId = this._id;
await Check.deleteMany({ "metadata.monitorId": monitorId });
await MonitorStats.deleteMany({ monitorId });
next();
} catch (error: any) {
next(error);
}
}
);
MonitorSchema.pre(
"deleteMany",
{ document: false, query: true },
async function (next) {
try {
const filter = this.getFilter();
const monitors = await this.model.find(filter).select("_id");
const monitorIds = monitors.map((m) => m._id);
if (monitorIds.length > 0) {
await Check.deleteMany({ "metadata.monitorId": { $in: monitorIds } });
await MonitorStats.deleteMany({ monitorId: { $in: monitorIds } });
}
next();
} catch (error: any) {
next(error);
}
}
);
MonitorSchema.index({ isActive: 1 });
MonitorSchema.index({ status: 1 });
MonitorSchema.index({ type: 1 });
MonitorSchema.index({ lastCheckedAt: 1 });
MonitorSchema.index({ isActive: 1, status: 1 });
MonitorSchema.index({ createdBy: 1 });
MonitorSchema.index({ updatedBy: 1 });
export const Monitor = mongoose.model<IMonitor>("Monitor", MonitorSchema);
@@ -0,0 +1,80 @@
import mongoose, { Schema, Document, Types } from "mongoose";
import { MonitorStatus, MonitorStatuses } from "./Monitor.js";
export interface IMonitorStats extends mongoose.Document {
monitorId: mongoose.Types.ObjectId;
avgResponseTime: number;
maxResponseTime: number;
totalChecks: number;
totalUpChecks: number;
totalDownChecks: number;
uptimePercentage: number;
lastCheckTimestamp: number;
lastResponseTime: number;
timeOfLastFailure: number;
currentStreak: number;
currentStreakStatus: MonitorStatus;
currentStreakStartedAt: number;
createdAt: Date;
updatedAt: Date;
}
const MonitorStatsSchema = new Schema<IMonitorStats>(
{
monitorId: {
type: mongoose.Schema.Types.ObjectId,
ref: "Monitor",
immutable: true,
index: true,
},
avgResponseTime: {
type: Number,
default: 0,
},
maxResponseTime: {
type: Number,
default: 0,
},
lastResponseTime: {
type: Number,
default: 0,
},
totalChecks: {
type: Number,
default: 0,
},
totalUpChecks: {
type: Number,
default: 0,
},
totalDownChecks: {
type: Number,
default: 0,
},
uptimePercentage: {
type: Number,
default: 0,
},
lastCheckTimestamp: {
type: Number,
default: 0,
},
timeOfLastFailure: {
type: Number,
default: 0,
},
currentStreak: { type: Number, required: false, default: 0 },
currentStreakStatus: {
type: String,
required: false,
enum: MonitorStatuses,
},
currentStreakStartedAt: { type: Number, required: false },
},
{ timestamps: true }
);
export const MonitorStats = mongoose.model<IMonitorStats>(
"MonitorStats",
MonitorStatsSchema
);
@@ -0,0 +1,57 @@
import mongoose, { Schema, Types } from "mongoose";
export const ChannelTypes = ["email", "slack", "discord", "webhook"] as const;
export type ChannelType = (typeof ChannelTypes)[number];
export interface INotificationChannelConfig {
url?: string; // For webhook, slack, discord
emailAddress?: string; // For email
}
export interface INotificationChannel {
_id: Types.ObjectId;
orgId: Types.ObjectId;
teamId: Types.ObjectId;
name: string;
type: ChannelType;
config: INotificationChannelConfig;
isActive: boolean;
createdBy: Types.ObjectId;
updatedBy: Types.ObjectId;
createdAt: Date;
updatedAt: Date;
}
const NotificationChannelConfigSchema = new Schema<INotificationChannelConfig>(
{
url: { type: String, required: false },
emailAddress: { type: String, required: false },
},
{ _id: false, strict: "throw" }
);
const NotificationChannelSchema = new Schema<INotificationChannel>(
{
orgId: { type: Schema.Types.ObjectId, ref: "Org", required: true },
teamId: { type: Schema.Types.ObjectId, ref: "Team", required: true },
name: { type: String, required: true, trim: true },
type: {
type: String,
required: true,
enum: ChannelTypes,
},
config: { type: NotificationChannelConfigSchema, required: true },
isActive: { type: Boolean, required: true, default: true },
createdBy: { type: Schema.Types.ObjectId, ref: "User", required: true },
updatedBy: { type: Schema.Types.ObjectId, ref: "User", required: true },
},
{ timestamps: true }
);
NotificationChannelSchema.index({ isActive: 1 });
NotificationChannelSchema.index({ type: 1 });
NotificationChannelSchema.index({ type: 1, isActive: 1 });
export const NotificationChannel = mongoose.model<INotificationChannel>(
"NotificationChannel",
NotificationChannelSchema
);
@@ -0,0 +1,35 @@
import mongoose, { Schema, Document, Types } from "mongoose";
export interface IRecoveryToken {
_id: string;
userId: Types.ObjectId;
tokenHash: string;
expiry: Date;
createdAt: Date;
updatedAt: Date;
}
const RecoveryTokenSchema = new Schema<IRecoveryToken>(
{
userId: {
type: Schema.Types.ObjectId,
ref: "User",
required: true,
unique: true,
},
tokenHash: { type: String, required: true },
expiry: {
type: Date,
default: () => new Date(Date.now() + 24 * 60 * 60 * 1000),
expires: 0,
},
},
{
timestamps: true,
}
);
export const RecoveryToken = mongoose.model<IRecoveryToken>(
"RecoveryToken",
RecoveryTokenSchema
);
@@ -0,0 +1,38 @@
import mongoose, { Schema, Document, Types } from "mongoose";
export interface IStatusPage {
_id: Types.ObjectId;
orgId: Types.ObjectId;
teamId: Types.ObjectId;
name: string;
description?: string;
url: string;
isPublished: boolean;
monitors: Types.ObjectId[];
createdBy: Types.ObjectId;
updatedBy: Types.ObjectId;
createdAt: Date;
updatedAt: Date;
}
const StatusPageSchema = new Schema<IStatusPage>(
{
orgId: { type: Schema.Types.ObjectId, ref: "Org", required: true },
teamId: { type: Schema.Types.ObjectId, ref: "Team", required: true },
name: { type: String, required: true, trim: true },
description: { type: String, required: false, trim: true },
url: { type: String, required: true, trim: true },
isPublished: { type: Boolean, required: true, default: false },
monitors: [{ type: Schema.Types.ObjectId, ref: "Monitor", required: true }],
createdBy: { type: Schema.Types.ObjectId, ref: "User", required: true },
updatedBy: { type: Schema.Types.ObjectId, ref: "User", required: true },
},
{ timestamps: true }
);
StatusPageSchema.index({ isPublished: 1 });
export const StatusPage = mongoose.model<IStatusPage>(
"StatusPage",
StatusPageSchema
);
-98
View File
@@ -1,98 +0,0 @@
import mongoose from "mongoose";
import AppSettings from "./models/AppSettings.js";
import { runMigrations } from "./migration/index.js";
class MongoDB {
static SERVICE_NAME = "MongoDB";
constructor({
logger,
envSettings,
checkModule,
inviteModule,
statusPageModule,
userModule,
hardwareCheckModule,
maintenanceWindowModule,
monitorModule,
networkCheckModule,
notificationModule,
pageSpeedCheckModule,
recoveryModule,
settingsModule,
}) {
this.logger = logger;
this.envSettings = envSettings;
this.userModule = userModule;
this.inviteModule = inviteModule;
this.recoveryModule = recoveryModule;
this.pageSpeedCheckModule = pageSpeedCheckModule;
this.hardwareCheckModule = hardwareCheckModule;
this.checkModule = checkModule;
this.maintenanceWindowModule = maintenanceWindowModule;
this.monitorModule = monitorModule;
this.notificationModule = notificationModule;
this.settingsModule = settingsModule;
this.statusPageModule = statusPageModule;
this.networkCheckModule = networkCheckModule;
}
get serviceName() {
return MongoDB.SERVICE_NAME;
}
connect = async () => {
try {
const connectionString = this.envSettings.dbConnectionString || "mongodb://localhost:27017/uptime_db";
await mongoose.connect(connectionString);
// If there are no AppSettings, create one // TODO why is this here?
await AppSettings.findOneAndUpdate(
{}, // empty filter to match any document
{}, // empty update
{
new: true,
setDefaultsOnInsert: true,
}
);
// Sync indexes
const models = mongoose.modelNames();
for (const modelName of models) {
const model = mongoose.model(modelName);
await model.syncIndexes();
}
this.logger.info({
message: "Connected to MongoDB",
service: this.SERVICE_NAME,
method: "connect",
});
await runMigrations();
} catch (error) {
this.logger.error({
message: error.message,
service: this.SERVICE_NAME,
method: "connect",
stack: error.stack,
});
throw error;
}
};
disconnect = async () => {
try {
this.logger.info({ message: "Disconnecting from MongoDB" });
await mongoose.disconnect();
this.logger.info({ message: "Disconnected from MongoDB" });
return;
} catch (error) {
this.logger.error({
message: error.message,
service: this.SERVICE_NAME,
method: "disconnect",
stack: error.stack,
});
}
};
}
export default MongoDB;
@@ -1,18 +0,0 @@
import Monitor from "../models/Monitor.js";
async function migrateStatusWindowThreshold() {
try {
const monitors = await Monitor.find({ statusWindowThreshold: { $lt: 1 } });
for (const monitor of monitors) {
monitor.statusWindowThreshold = monitor.statusWindowThreshold * 100;
await monitor.save();
console.log(`Migrated monitor ${monitor._id}: statusWindowThreshold set to ${monitor.statusWindowThreshold}`);
}
console.log("StatusWindowThreshold migration complete.");
return true;
} catch (err) {
console.error("Migration error:", err);
return false;
}
}
export { migrateStatusWindowThreshold };
-7
View File
@@ -1,7 +0,0 @@
import { migrateStatusWindowThreshold } from "./0001_migrateStatusWindowThreshold.js";
const runMigrations = async () => {
await migrateStatusWindowThreshold();
};
export { runMigrations };
-80
View File
@@ -1,80 +0,0 @@
import mongoose from "mongoose";
const AppSettingsSchema = mongoose.Schema(
{
checkTTL: {
type: Number,
default: 30,
},
language: {
type: String,
default: "gb",
},
pagespeedApiKey: {
type: String,
},
systemEmailHost: {
type: String,
},
systemEmailPort: {
type: Number,
},
systemEmailAddress: {
type: String,
},
systemEmailPassword: {
type: String,
},
systemEmailUser: {
type: String,
},
systemEmailConnectionHost: {
type: String,
default: "localhost",
},
systemEmailTLSServername: {
type: String,
},
systemEmailSecure: {
type: Boolean,
default: false,
},
systemEmailPool: {
type: Boolean,
default: false,
},
systemEmailIgnoreTLS: {
type: Boolean,
default: false,
},
systemEmailRequireTLS: {
type: Boolean,
default: false,
},
systemEmailRejectUnauthorized: {
type: Boolean,
default: true,
},
singleton: {
type: Boolean,
required: true,
unique: true,
default: true,
},
version: {
type: Number,
default: 1,
},
globalThresholds: {
cpu: { type: Number },
memory: { type: Number },
disk: { type: Number },
temperature: { type: Number },
},
},
{
timestamps: true,
}
);
export default mongoose.model("AppSettings", AppSettingsSchema);
-176
View File
@@ -1,176 +0,0 @@
import mongoose from "mongoose";
const cpuSchema = mongoose.Schema({
physical_core: { type: Number, default: 0 },
logical_core: { type: Number, default: 0 },
frequency: { type: Number, default: 0 },
temperature: { type: [Number], default: [] },
free_percent: { type: Number, default: 0 },
usage_percent: { type: Number, default: 0 },
});
const memorySchema = mongoose.Schema({
total_bytes: { type: Number, default: 0 },
available_bytes: { type: Number, default: 0 },
used_bytes: { type: Number, default: 0 },
usage_percent: { type: Number, default: 0 },
});
const diskSchema = mongoose.Schema({
read_speed_bytes: { type: Number, default: 0 },
write_speed_bytes: { type: Number, default: 0 },
total_bytes: { type: Number, default: 0 },
free_bytes: { type: Number, default: 0 },
usage_percent: { type: Number, default: 0 },
});
const hostSchema = mongoose.Schema({
os: { type: String, default: "" },
platform: { type: String, default: "" },
kernel_version: { type: String, default: "" },
});
const errorSchema = mongoose.Schema({
metric: { type: [String], default: [] },
err: { type: String, default: "" },
});
const captureSchema = mongoose.Schema({
version: { type: String, default: "" },
mode: { type: String, default: "" },
});
const networkInterfaceSchema = mongoose.Schema({
name: { type: String },
bytes_sent: { type: Number, default: 0 },
bytes_recv: { type: Number, default: 0 },
packets_sent: { type: Number, default: 0 },
packets_recv: { type: Number, default: 0 },
err_in: { type: Number, default: 0 },
err_out: { type: Number, default: 0 },
drop_in: { type: Number, default: 0 },
drop_out: { type: Number, default: 0 },
fifo_in: { type: Number, default: 0 },
fifo_out: { type: Number, default: 0 },
});
const CheckSchema = new mongoose.Schema(
{
// Common fields
monitorId: {
type: mongoose.Schema.Types.ObjectId,
ref: "Monitor",
immutable: true,
index: true,
},
teamId: {
type: mongoose.Schema.Types.ObjectId,
ref: "Team",
immutable: true,
index: true,
},
type: {
type: String,
enum: ["http", "ping", "pagespeed", "hardware", "docker", "port", "game"],
required: true,
index: true,
},
status: {
type: Boolean,
index: true,
},
responseTime: {
type: Number,
},
timings: {
type: Object,
default: {},
},
statusCode: {
type: Number,
index: true,
},
message: {
type: String,
},
expiry: {
type: Date,
default: Date.now,
expires: 60 * 60 * 24 * 30, // 30 days
},
ack: {
type: Boolean,
default: false,
},
ackAt: {
type: Date,
},
// Hardware fields
cpu: {
type: cpuSchema,
default: () => ({}),
},
memory: {
type: memorySchema,
default: () => ({}),
},
disk: {
type: [diskSchema],
default: () => [],
},
host: {
type: hostSchema,
default: () => ({}),
},
errors: {
type: [errorSchema],
default: () => [],
},
capture: {
type: captureSchema,
default: () => ({}),
},
net: {
type: [networkInterfaceSchema],
default: () => [],
},
// PageSpeed fields
accessibility: {
type: Number,
},
bestPractices: {
type: Number,
},
seo: {
type: Number,
},
performance: {
type: Number,
},
audits: {
type: Object,
},
},
{ timestamps: true }
);
CheckSchema.index({ updatedAt: 1 });
CheckSchema.index({ monitorId: 1, updatedAt: 1 });
CheckSchema.index({ monitorId: 1, updatedAt: -1 });
CheckSchema.index({ teamId: 1, updatedAt: -1 });
export default mongoose.model("Check", CheckSchema);
-35
View File
@@ -1,35 +0,0 @@
import mongoose from "mongoose";
const InviteTokenSchema = mongoose.Schema(
{
email: {
type: String,
required: true,
unique: true,
},
teamId: {
type: mongoose.Schema.Types.ObjectId,
ref: "Team",
immutable: true,
required: true,
},
role: {
type: Array,
required: true,
default: ["user"],
},
token: {
type: String,
required: true,
},
expiry: {
type: Date,
default: Date.now,
expires: 3600,
},
},
{
timestamps: true,
}
);
export default mongoose.model("InviteToken", InviteTokenSchema);
@@ -1,68 +0,0 @@
import mongoose from "mongoose";
/**
* MaintenanceWindow Schema
* @module MaintenanceWindow
* @typedef {Object} MaintenanceWindow
* @property {mongoose.Schema.Types.ObjectId} monitorId - The ID of the monitor. This is a reference to the Monitor model and is immutable.
* @property {Boolean} active - Indicates whether the maintenance window is active.
* @property {Number} repeat - Indicates how often this maintenance window should repeat.
* @property {Date} start - The start date and time of the maintenance window.
* @property {Date} end - The end date and time of the maintenance window.
* @property {Date} expiry - The expiry date and time of the maintenance window. This is used for MongoDB's TTL index to automatically delete the document at this time. This field is set to the same value as `end` when `oneTime` is `true`.
*
* @example
*
* let maintenanceWindow = new MaintenanceWindow({
* monitorId: monitorId,
* active: active,
* repeat: repeat,
* start: start,
* end: end,
* });
*
* if (repeat === 0) {
* maintenanceWindow.expiry = end;
* }
*
*/
const MaintenanceWindow = mongoose.Schema(
{
monitorId: {
type: mongoose.Schema.Types.ObjectId,
ref: "Monitor",
immutable: true,
},
teamId: {
type: mongoose.Schema.Types.ObjectId,
ref: "Team",
immutable: true,
},
active: {
type: Boolean,
default: true,
},
name: {
type: String,
},
repeat: {
type: Number,
},
start: {
type: Date,
},
end: {
type: Date,
},
expiry: {
type: Date,
index: { expires: "0s" },
},
},
{
timestamps: true,
}
);
export default mongoose.model("MaintenanceWindow", MaintenanceWindow);
-208
View File
@@ -1,208 +0,0 @@
import mongoose from "mongoose";
import Check from "./Check.js";
import MonitorStats from "./MonitorStats.js";
import StatusPage from "./StatusPage.js";
const MonitorSchema = mongoose.Schema(
{
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
immutable: true,
required: true,
},
teamId: {
type: mongoose.Schema.Types.ObjectId,
ref: "Team",
immutable: true,
required: true,
},
name: {
type: String,
required: true,
},
description: {
type: String,
},
status: {
type: Boolean,
default: undefined,
},
statusWindow: {
type: [Boolean],
default: [],
},
statusWindowSize: {
type: Number,
default: 5,
},
statusWindowThreshold: {
type: Number,
default: 60,
},
type: {
type: String,
required: true,
enum: ["http", "ping", "pagespeed", "hardware", "docker", "port", "game"],
},
ignoreTlsErrors: {
type: Boolean,
default: false,
},
jsonPath: {
type: String,
},
expectedValue: {
type: String,
},
matchMethod: {
type: String,
enum: ["equal", "include", "regex", ""],
},
url: {
type: String,
required: true,
},
port: {
type: Number,
},
isActive: {
type: Boolean,
default: true,
},
interval: {
// in milliseconds
type: Number,
default: 60000,
},
uptimePercentage: {
type: Number,
default: undefined,
},
notifications: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Notification",
},
],
secret: {
type: String,
},
thresholds: {
type: {
usage_cpu: { type: Number },
usage_memory: { type: Number },
usage_disk: { type: Number },
usage_temperature: { type: Number },
},
_id: false,
},
alertThreshold: {
type: Number,
default: 5,
},
cpuAlertThreshold: {
type: Number,
default: function () {
return this.alertThreshold;
},
},
memoryAlertThreshold: {
type: Number,
default: function () {
return this.alertThreshold;
},
},
diskAlertThreshold: {
type: Number,
default: function () {
return this.alertThreshold;
},
},
tempAlertThreshold: {
type: Number,
default: function () {
return this.alertThreshold;
},
},
gameId: {
type: String,
},
group: {
type: String,
trim: true,
maxLength: 50,
default: null,
set: function (value) {
return value && value.trim() ? value.trim() : null;
},
},
},
{
timestamps: true,
}
);
MonitorSchema.pre("findOneAndDelete", async function (next) {
// Delete checks and stats
try {
const doc = await this.model.findOne(this.getFilter());
if (!doc) {
throw new Error("Monitor not found");
}
await Check.deleteMany({ monitorId: doc._id });
// Deal with status pages
await StatusPage.updateMany({ monitors: doc?._id }, { $pull: { monitors: doc?._id } });
await MonitorStats.deleteMany({ monitorId: doc?._id.toString() });
next();
} catch (error) {
next(error);
}
});
MonitorSchema.pre("deleteMany", async function (next) {
const filter = this.getFilter();
const monitors = await this.model.find(filter).select(["_id", "type"]).lean();
for (const monitor of monitors) {
await Check.deleteMany({ monitorId: monitor._id });
await StatusPage.updateMany({ monitors: monitor._id }, { $pull: { monitors: monitor._id } });
await MonitorStats.deleteMany({ monitorId: monitor._id.toString() });
}
next();
});
MonitorSchema.pre("save", function (next) {
if (!this.cpuAlertThreshold || this.isModified("alertThreshold")) {
this.cpuAlertThreshold = this.alertThreshold;
}
if (!this.memoryAlertThreshold || this.isModified("alertThreshold")) {
this.memoryAlertThreshold = this.alertThreshold;
}
if (!this.diskAlertThreshold || this.isModified("alertThreshold")) {
this.diskAlertThreshold = this.alertThreshold;
}
if (!this.tempAlertThreshold || this.isModified("alertThreshold")) {
this.tempAlertThreshold = this.alertThreshold;
}
next();
});
MonitorSchema.pre("findOneAndUpdate", function (next) {
const update = this.getUpdate();
if (update.alertThreshold) {
update.cpuAlertThreshold = update.alertThreshold;
update.memoryAlertThreshold = update.alertThreshold;
update.diskAlertThreshold = update.alertThreshold;
update.tempAlertThreshold = update.alertThreshold;
}
next();
});
MonitorSchema.index({ teamId: 1, type: 1 });
export default mongoose.model("Monitor", MonitorSchema);
-49
View File
@@ -1,49 +0,0 @@
import mongoose from "mongoose";
const MonitorStatsSchema = new mongoose.Schema(
{
monitorId: {
type: mongoose.Schema.Types.ObjectId,
ref: "Monitor",
immutable: true,
index: true,
},
avgResponseTime: {
type: Number,
default: 0,
},
totalChecks: {
type: Number,
default: 0,
},
totalUpChecks: {
type: Number,
default: 0,
},
totalDownChecks: {
type: Number,
default: 0,
},
uptimePercentage: {
type: Number,
default: 0,
},
lastCheckTimestamp: {
type: Number,
default: 0,
},
lastResponseTime: {
type: Number,
default: 0,
},
timeOfLastFailure: {
type: Number,
default: 0,
},
},
{ timestamps: true }
);
const MonitorStats = mongoose.model("MonitorStats", MonitorStatsSchema);
export default MonitorStats;
-74
View File
@@ -1,74 +0,0 @@
import mongoose from "mongoose";
const NotificationSchema = mongoose.Schema(
{
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
immutable: true,
required: true,
},
teamId: {
type: mongoose.Schema.Types.ObjectId,
ref: "Team",
immutable: true,
required: true,
},
type: {
type: String,
enum: ["email", "slack", "discord", "webhook", "pager_duty", "matrix"],
},
notificationName: {
type: String,
required: true,
},
address: {
type: String,
},
phone: {
type: String,
},
// Matrix-specific fields
homeserverUrl: {
type: String,
},
roomId: {
type: String,
},
accessToken: {
type: String,
},
},
{
timestamps: true,
}
);
NotificationSchema.pre("save", function (next) {
if (!this.cpuAlertThreshold || this.isModified("alertThreshold")) {
this.cpuAlertThreshold = this.alertThreshold;
}
if (!this.memoryAlertThreshold || this.isModified("alertThreshold")) {
this.memoryAlertThreshold = this.alertThreshold;
}
if (!this.diskAlertThreshold || this.isModified("alertThreshold")) {
this.diskAlertThreshold = this.alertThreshold;
}
if (!this.tempAlertThreshold || this.isModified("alertThreshold")) {
this.tempAlertThreshold = this.alertThreshold;
}
next();
});
NotificationSchema.pre("findOneAndUpdate", function (next) {
const update = this.getUpdate();
if (update.alertThreshold) {
update.cpuAlertThreshold = update.alertThreshold;
update.memoryAlertThreshold = update.alertThreshold;
update.diskAlertThreshold = update.alertThreshold;
update.tempAlertThreshold = update.alertThreshold;
}
next();
});
export default mongoose.model("Notification", NotificationSchema);
-25
View File
@@ -1,25 +0,0 @@
import mongoose from "mongoose";
const RecoveryTokenSchema = mongoose.Schema(
{
email: {
type: String,
required: true,
unique: true,
},
token: {
type: String,
required: true,
},
expiry: {
type: Date,
default: Date.now,
expires: 600,
},
},
{
timestamps: true,
}
);
export default mongoose.model("RecoveryToken", RecoveryTokenSchema);
-85
View File
@@ -1,85 +0,0 @@
import mongoose from "mongoose";
const StatusPageSchema = mongoose.Schema(
{
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
immutable: true,
required: true,
},
teamId: {
type: mongoose.Schema.Types.ObjectId,
ref: "Team",
immutable: true,
required: true,
},
type: {
type: String,
required: true,
default: "uptime",
enum: ["uptime"],
},
companyName: {
type: String,
required: true,
default: "",
},
url: {
type: String,
unique: true,
required: true,
default: "",
},
timezone: {
type: String,
required: false,
},
color: {
type: String,
required: false,
default: "#4169E1",
},
monitors: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Monitor",
required: true,
},
],
subMonitors: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Monitor",
required: true,
},
],
logo: {
data: Buffer,
contentType: String,
},
isPublished: {
type: Boolean,
default: false,
},
showCharts: {
type: Boolean,
default: true,
},
showUptimePercentage: {
type: Boolean,
default: true,
},
showAdminLoginLink: {
type: Boolean,
default: false,
},
customCSS: {
type: String,
default: "",
},
},
{ timestamps: true }
);
export default mongoose.model("StatusPage", StatusPageSchema);
-14
View File
@@ -1,14 +0,0 @@
import mongoose from "mongoose";
const TeamSchema = mongoose.Schema(
{
email: {
type: String,
required: true,
unique: true,
},
},
{
timestamps: true,
}
);
export default mongoose.model("Team", TeamSchema);
-105
View File
@@ -1,105 +0,0 @@
import mongoose from "mongoose";
import bcrypt from "bcryptjs";
import Monitor from "./Monitor.js";
import Team from "./Team.js";
import Notification from "./Notification.js";
const UserSchema = mongoose.Schema(
{
firstName: {
type: String,
required: true,
},
lastName: {
type: String,
required: true,
},
email: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
required: true,
},
avatarImage: {
type: String,
},
profileImage: {
data: Buffer,
contentType: String,
},
isActive: {
type: Boolean,
default: true,
},
isVerified: {
type: Boolean,
default: false,
},
role: {
type: [String],
default: "user",
enum: ["user", "admin", "superadmin", "demo"],
},
teamId: {
type: mongoose.Schema.Types.ObjectId,
ref: "Team",
immutable: true,
},
checkTTL: {
type: Number,
},
},
{
timestamps: true,
}
);
UserSchema.pre("save", function (next) {
if (!this.isModified("password")) {
return next();
}
const salt = bcrypt.genSaltSync(10);
this.password = bcrypt.hashSync(this.password, salt);
next();
});
UserSchema.pre("findOneAndUpdate", function (next) {
const update = this.getUpdate();
if ("password" in update) {
const salt = bcrypt.genSaltSync(10);
update.password = bcrypt.hashSync(update.password, salt);
}
next();
});
UserSchema.pre("findOneAndDelete", async function (next) {
try {
const userToDelete = await this.model.findOne(this.getFilter());
if (!userToDelete) return next();
if (userToDelete.role.includes("superadmin")) {
await Team.deleteOne({ _id: userToDelete.teamId });
await Monitor.deleteMany({ userId: userToDelete._id });
await this.model.deleteMany({
teamId: userToDelete.teamId,
_id: { $ne: userToDelete._id },
});
await Notification.deleteMany({ teamId: userToDelete.teamId });
}
next();
} catch (error) {
next(error);
}
});
UserSchema.methods.comparePassword = async function (submittedPassword) {
const res = await bcrypt.compare(submittedPassword, this.password);
return res;
};
const User = mongoose.model("User", UserSchema);
export default User;
-283
View File
@@ -1,283 +0,0 @@
import { ObjectId } from "mongodb";
import { buildChecksSummaryByTeamIdPipeline } from "./checkModuleQueries.js";
const SERVICE_NAME = "checkModule";
const dateRangeLookup = {
recent: new Date(new Date().setDate(new Date().getDate() - 2)),
hour: new Date(new Date().setHours(new Date().getHours() - 1)),
day: new Date(new Date().setDate(new Date().getDate() - 1)),
week: new Date(new Date().setDate(new Date().getDate() - 7)),
month: new Date(new Date().setMonth(new Date().getMonth() - 1)),
all: undefined,
};
class CheckModule {
constructor({ logger, Check, HardwareCheck, PageSpeedCheck, Monitor, User }) {
this.logger = logger;
this.Check = Check;
this.HardwareCheck = HardwareCheck;
this.PageSpeedCheck = PageSpeedCheck;
this.Monitor = Monitor;
this.User = User;
}
createChecks = async (checks) => {
try {
await this.Check.insertMany(checks, { ordered: false });
} catch (error) {
error.service = SERVICE_NAME;
error.method = "createCheck";
throw error;
}
};
getChecksByMonitor = async ({ monitorId, sortOrder, dateRange, filter, ack, page, rowsPerPage, status }) => {
try {
status = status === "true" ? true : status === "false" ? false : undefined;
page = parseInt(page);
rowsPerPage = parseInt(rowsPerPage);
const ackStage = ack === "true" ? { ack: true } : { $or: [{ ack: false }, { ack: { $exists: false } }] };
// Match
const matchStage = {
monitorId: new ObjectId(monitorId),
...(typeof status !== "undefined" && { status }),
...(typeof ack !== "undefined" && ackStage),
...(dateRangeLookup[dateRange] && {
createdAt: {
$gte: dateRangeLookup[dateRange],
},
}),
};
if (filter !== undefined) {
switch (filter) {
case "all":
break;
case "down":
break;
case "resolve":
matchStage.statusCode = 5000;
break;
default:
this.logger.warn({
message: "invalid filter",
service: SERVICE_NAME,
method: "getChecks",
});
break;
}
}
//Sort
sortOrder = sortOrder === "asc" ? 1 : -1;
// Pagination
let skip = 0;
if (page && rowsPerPage) {
skip = page * rowsPerPage;
}
const checks = await this.Check.aggregate([
{ $match: matchStage },
{ $sort: { createdAt: sortOrder } },
{
$facet: {
summary: [{ $count: "checksCount" }],
checks: [{ $skip: skip }, { $limit: rowsPerPage }],
},
},
{
$project: {
checksCount: {
$ifNull: [{ $arrayElemAt: ["$summary.checksCount", 0] }, 0],
},
checks: {
$ifNull: ["$checks", []],
},
},
},
]);
return checks[0];
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getChecks";
throw error;
}
};
getChecksByTeam = async ({ sortOrder, dateRange, filter, ack, page, rowsPerPage, teamId }) => {
try {
page = parseInt(page);
rowsPerPage = parseInt(rowsPerPage);
const ackStage = ack === "true" ? { ack: true } : { $or: [{ ack: false }, { ack: { $exists: false } }] };
const matchStage = {
teamId: new ObjectId(teamId),
status: false,
...(typeof ack !== "undefined" && ackStage),
...(dateRangeLookup[dateRange] && {
createdAt: {
$gte: dateRangeLookup[dateRange],
},
}),
};
// Add filter to match stage
if (filter !== undefined) {
switch (filter) {
case "all":
break;
case "down":
break;
case "resolve":
matchStage.statusCode = 5000;
break;
default:
this.logger.warn({
message: "invalid filter",
service: SERVICE_NAME,
method: "getChecksByTeam",
});
break;
}
}
sortOrder = sortOrder === "asc" ? 1 : -1;
// pagination
let skip = 0;
if (page && rowsPerPage) {
skip = page * rowsPerPage;
}
const aggregatePipeline = [
{ $match: matchStage },
{ $sort: { createdAt: sortOrder } },
{
$facet: {
summary: [{ $count: "checksCount" }],
checks: [{ $skip: skip }, { $limit: rowsPerPage }],
},
},
{
$project: {
checksCount: { $arrayElemAt: ["$summary.checksCount", 0] },
checks: "$checks",
},
},
];
const checks = await this.Check.aggregate(aggregatePipeline);
return checks[0];
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getChecksByTeam";
throw error;
}
};
ackCheck = async (checkId, teamId, ack) => {
try {
const updatedCheck = await this.Check.findOneAndUpdate({ _id: checkId, teamId: teamId }, { $set: { ack, ackAt: new Date() } }, { new: true });
if (!updatedCheck) {
throw new Error("Check not found");
}
return updatedCheck;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "ackCheck";
throw error;
}
};
ackAllChecks = async (monitorId, teamId, ack, path) => {
try {
const updatedChecks = await this.Check.updateMany(path === "monitor" ? { monitorId } : { teamId }, { $set: { ack, ackAt: new Date() } });
return updatedChecks.modifiedCount;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "ackAllChecks";
throw error;
}
};
getChecksSummaryByTeamId = async ({ teamId }) => {
try {
const matchStage = {
teamId: new ObjectId(teamId),
};
const checks = await this.Check.aggregate(buildChecksSummaryByTeamIdPipeline({ matchStage }));
return checks[0].summary;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getChecksSummaryByTeamId";
throw error;
}
};
deleteChecks = async (monitorId) => {
try {
const result = await this.Check.deleteMany({ monitorId });
return result.deletedCount;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "deleteChecks";
throw error;
}
};
deleteChecksByTeamId = async (teamId) => {
try {
// Find all monitor IDs for this team (only get _id field for efficiency)
const teamMonitors = await this.Monitor.find({ teamId }, { _id: 1 });
const monitorIds = teamMonitors.map((monitor) => monitor._id);
// Delete all checks for these monitors in one operation
const deleteResult = await this.Check.deleteMany({ monitorId: { $in: monitorIds } });
return deleteResult.deletedCount;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "deleteChecksByTeamId";
throw error;
}
};
updateChecksTTL = async (teamId, ttl) => {
try {
await this.Check.collection.dropIndex("expiry_1");
} catch (error) {
this.logger.error({
message: error.message,
service: SERVICE_NAME,
method: "updateChecksTTL",
stack: error.stack,
});
}
try {
await this.Check.collection.createIndex(
{ expiry: 1 },
{ expireAfterSeconds: ttl } // TTL in seconds, adjust as necessary
);
} catch (error) {
error.service = SERVICE_NAME;
error.method = "updateChecksTTL";
throw error;
}
// Update user
try {
await this.User.updateMany({ teamId: teamId }, { checkTTL: ttl });
} catch (error) {
error.service = SERVICE_NAME;
error.method = "updateChecksTTL";
throw error;
}
};
}
export default CheckModule;
@@ -1,44 +0,0 @@
const buildChecksSummaryByTeamIdPipeline = ({ matchStage }) => {
return [
{ $match: matchStage },
{
$facet: {
summary: [
{
$group: {
_id: null,
totalChecks: { $sum: { $cond: [{ $eq: ["$status", false] }, 1, 0] } },
resolvedChecks: {
$sum: {
$cond: [{ $and: [{ $eq: ["$ack", true] }, { $eq: ["$status", false] }] }, 1, 0],
},
},
downChecks: {
$sum: {
$cond: [{ $and: [{ $eq: ["$ack", false] }, { $eq: ["$status", false] }] }, 1, 0],
},
},
cannotResolveChecks: {
$sum: {
$cond: [{ $eq: ["$statusCode", 5000] }, 1, 0],
},
},
},
},
{
$project: {
_id: 0,
},
},
],
},
},
{
$project: {
summary: { $arrayElemAt: ["$summary", 0] },
},
},
];
};
export { buildChecksSummaryByTeamIdPipeline };
-56
View File
@@ -1,56 +0,0 @@
const SERVICE_NAME = "inviteModule";
class InviteModule {
constructor({ InviteToken, crypto, stringService }) {
this.InviteToken = InviteToken;
this.crypto = crypto;
this.stringService = stringService;
}
requestInviteToken = async (userData) => {
try {
await this.InviteToken.deleteMany({ email: userData.email });
userData.token = this.crypto.randomBytes(32).toString("hex");
let inviteToken = new this.InviteToken(userData);
await inviteToken.save();
return inviteToken;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "requestInviteToken";
throw error;
}
};
getInviteToken = async (token) => {
try {
const invite = await this.InviteToken.findOne({
token,
});
if (invite === null) {
throw new Error(this.stringService.authInviteNotFound);
}
return invite;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getInviteToken";
throw error;
}
};
getInviteTokenAndDelete = async (token) => {
try {
const invite = await this.InviteToken.findOneAndDelete({
token,
});
if (invite === null) {
throw new Error(this.stringService.authInviteNotFound);
}
return invite;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getInviteTokenAndDelete";
throw error;
}
};
}
export default InviteModule;
@@ -1,106 +0,0 @@
const SERVICE_NAME = "maintenanceWindowModule";
class MaintenanceWindowModule {
constructor({ MaintenanceWindow }) {
this.MaintenanceWindow = MaintenanceWindow;
}
createMaintenanceWindow = async (maintenanceWindowData) => {
try {
const maintenanceWindow = new this.MaintenanceWindow({
...maintenanceWindowData,
});
// If the maintenance window is a one time window, set the expiry to the end date
if (maintenanceWindowData.oneTime) {
maintenanceWindow.expiry = maintenanceWindowData.end;
}
const result = await maintenanceWindow.save();
return result;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "createMaintenanceWindow";
throw error;
}
};
getMaintenanceWindowById = async ({ id, teamId }) => {
try {
const maintenanceWindow = await this.MaintenanceWindow.findOne({
_id: id,
teamId: teamId,
});
return maintenanceWindow;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getMaintenanceWindowById";
throw error;
}
};
getMaintenanceWindowsByTeamId = async (teamId, query) => {
try {
let { active, page, rowsPerPage, field, order } = query || {};
const maintenanceQuery = { teamId };
if (active !== undefined) maintenanceQuery.active = active;
const maintenanceWindowCount = await this.MaintenanceWindow.countDocuments(maintenanceQuery);
// Pagination
let skip = 0;
if (page && rowsPerPage) {
skip = page * rowsPerPage;
}
// Sorting
let sort = {};
if (field !== undefined && order !== undefined) {
sort[field] = order === "asc" ? 1 : -1;
}
const maintenanceWindows = await this.MaintenanceWindow.find(maintenanceQuery).skip(skip).limit(rowsPerPage).sort(sort);
return { maintenanceWindows, maintenanceWindowCount };
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getMaintenanceWindowByUserId";
throw error;
}
};
getMaintenanceWindowsByMonitorId = async ({ monitorId, teamId }) => {
try {
const maintenanceWindows = await this.MaintenanceWindow.find({
monitorId: monitorId,
teamId: teamId,
});
return maintenanceWindows;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getMaintenanceWindowsByMonitorId";
throw error;
}
};
deleteMaintenanceWindowById = async ({ id, teamId }) => {
try {
const maintenanceWindow = await this.MaintenanceWindow.findOneAndDelete({ _id: id, teamId });
return maintenanceWindow;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "deleteMaintenanceWindowById";
throw error;
}
};
editMaintenanceWindowById = async ({ id, body }) => {
try {
const editedMaintenanceWindow = await this.MaintenanceWindow.findByIdAndUpdate(id, body, { new: true });
return editedMaintenanceWindow;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "editMaintenanceWindowById";
throw error;
}
};
}
export default MaintenanceWindowModule;
-593
View File
@@ -1,593 +0,0 @@
import {
buildUptimeDetailsPipeline,
buildHardwareDetailsPipeline,
buildMonitorSummaryByTeamIdPipeline,
buildMonitorsByTeamIdPipeline,
buildMonitorsAndSummaryByTeamIdPipeline,
buildMonitorsWithChecksByTeamIdPipeline,
buildFilteredMonitorsByTeamIdPipeline,
} from "./monitorModuleQueries.js";
const SERVICE_NAME = "monitorModule";
class MonitorModule {
constructor({ Monitor, MonitorStats, Check, stringService, fs, path, fileURLToPath, ObjectId, NormalizeData, NormalizeDataUptimeDetails }) {
this.Monitor = Monitor;
this.MonitorStats = MonitorStats;
this.Check = Check;
this.stringService = stringService;
this.fs = fs;
this.path = path;
this.fileURLToPath = fileURLToPath;
this.ObjectId = ObjectId;
this.NormalizeData = NormalizeData;
this.NormalizeDataUptimeDetails = NormalizeDataUptimeDetails;
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
this.demoMonitorsPath = path.resolve(__dirname, "../../../utils/demoMonitors.json");
}
// Helper
calculateUptimeDuration = (checks) => {
if (!checks || checks.length === 0) {
return 0;
}
const latestCheck = new Date(checks[0].createdAt);
let latestDownCheck = 0;
for (let i = checks.length - 1; i >= 0; i--) {
if (checks[i].status === false) {
latestDownCheck = new Date(checks[i].createdAt);
break;
}
}
// If no down check is found, uptime is from the last check to now
if (latestDownCheck === 0) {
return Date.now() - new Date(checks[checks.length - 1].createdAt);
}
// Otherwise the uptime is from the last check to the last down check
return latestCheck - latestDownCheck;
};
// Helper
getLastChecked = (checks) => {
if (!checks || checks.length === 0) {
return 0; // Handle case when no checks are available
}
// Data is sorted newest->oldest, so last check is the most recent
return new Date() - new Date(checks[0].createdAt);
};
getLatestResponseTime = (checks) => {
if (!checks || checks.length === 0) {
return 0;
}
return checks[0]?.responseTime ?? 0;
};
// Helper
getAverageResponseTime = (checks) => {
if (!checks || checks.length === 0) {
return 0;
}
const validChecks = checks.filter((check) => typeof check.responseTime === "number");
if (validChecks.length === 0) {
return 0;
}
const aggResponseTime = validChecks.reduce((sum, check) => {
return sum + check.responseTime;
}, 0);
return aggResponseTime / validChecks.length;
};
// Helper
getUptimePercentage = (checks) => {
if (!checks || checks.length === 0) {
return 0;
}
const upCount = checks.reduce((count, check) => {
return check.status === true ? count + 1 : count;
}, 0);
return (upCount / checks.length) * 100;
};
// Helper
getIncidents = (checks) => {
if (!checks || checks.length === 0) {
return 0; // Handle case when no checks are available
}
return checks.reduce((acc, check) => {
return check.status === false ? (acc += 1) : acc;
}, 0);
};
// Helper
getDateRange = (dateRange) => {
const startDates = {
recent: new Date(new Date().setHours(new Date().getHours() - 2)),
day: new Date(new Date().setDate(new Date().getDate() - 1)),
week: new Date(new Date().setDate(new Date().getDate() - 7)),
month: new Date(new Date().setMonth(new Date().getMonth() - 1)),
all: new Date(0),
};
return {
start: startDates[dateRange],
end: new Date(),
};
};
//Helper
getMonitorChecks = async (monitorId, dateRange, sortOrder) => {
const indexSpec = {
monitorId: 1,
updatedAt: sortOrder, // This will be 1 or -1
};
const [checksAll, checksForDateRange] = await Promise.all([
this.Check.find({ monitorId }).sort({ createdAt: sortOrder }).hint(indexSpec).lean(),
this.Check.find({
monitorId,
createdAt: { $gte: dateRange.start, $lte: dateRange.end },
})
.hint(indexSpec)
.lean(),
]);
return { checksAll, checksForDateRange };
};
// Helper
processChecksForDisplay = (normalizeData, checks, numToDisplay, normalize) => {
let processedChecks = checks;
if (numToDisplay && checks.length > numToDisplay) {
const n = Math.ceil(checks.length / numToDisplay);
processedChecks = checks.filter((_, index) => index % n === 0);
}
return normalize ? normalizeData(processedChecks, 1, 100) : processedChecks;
};
// Helper
groupChecksByTime = (checks, dateRange) => {
return checks.reduce((acc, check) => {
// Validate the date
const checkDate = new Date(check.createdAt);
if (Number.isNaN(checkDate.getTime()) || checkDate.getTime() === 0) {
return acc;
}
const time = dateRange === "day" ? checkDate.setMinutes(0, 0, 0) : checkDate.toISOString().split("T")[0];
if (!acc[time]) {
acc[time] = { time, checks: [] };
}
acc[time].checks.push(check);
return acc;
}, {});
};
// Helper
calculateGroupStats = (group) => {
const totalChecks = group.checks.length;
const checksWithResponseTime = group.checks.filter((check) => typeof check.responseTime === "number" && !Number.isNaN(check.responseTime));
return {
time: group.time,
uptimePercentage: this.getUptimePercentage(group.checks),
totalChecks,
totalIncidents: group.checks.filter((check) => !check.status).length,
avgResponseTime:
checksWithResponseTime.length > 0
? checksWithResponseTime.reduce((sum, check) => sum + check.responseTime, 0) / checksWithResponseTime.length
: 0,
};
};
getAllMonitors = async () => {
try {
const monitors = await this.Monitor.find();
return monitors;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getAllMonitors";
throw error;
}
};
getMonitorById = async (monitorId) => {
try {
const monitor = await this.Monitor.findById(monitorId);
if (monitor === null || monitor === undefined) {
const error = new Error(this.stringService.getDbFindMonitorById(monitorId));
error.status = 404;
throw error;
}
return monitor;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getMonitorById";
throw error;
}
};
getMonitorsByIds = async (monitorIds) => {
try {
const objectIds = monitorIds.map((id) => new this.ObjectId(id));
return await this.Monitor.find({ _id: { $in: objectIds } }, { _id: 1, teamId: 1 }).lean();
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getMonitorsByIds";
throw error;
}
};
getUptimeDetailsById = async ({ monitorId, dateRange }) => {
try {
const dates = this.getDateRange(dateRange);
const formatLookup = {
recent: "%Y-%m-%dT%H:%M:00Z",
day: "%Y-%m-%dT%H:00:00Z",
week: "%Y-%m-%dT00:00:00Z",
month: "%Y-%m-%dT00:00:00Z",
};
const dateString = formatLookup[dateRange];
const results = await this.Check.aggregate(buildUptimeDetailsPipeline(monitorId, dates, dateString));
const monitorData = results[0];
monitorData.groupedUpChecks = this.NormalizeDataUptimeDetails(monitorData.groupedUpChecks, 10, 100);
monitorData.groupedDownChecks = this.NormalizeDataUptimeDetails(monitorData.groupedDownChecks, 10, 100);
const normalizedGroupChecks = this.NormalizeDataUptimeDetails(monitorData.groupedChecks, 10, 100);
monitorData.groupedChecks = normalizedGroupChecks;
const monitorStats = await this.MonitorStats.findOne({ monitorId });
return { monitorData, monitorStats };
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getUptimeDetailsById";
throw error;
}
};
getMonitorStatsById = async ({ monitorId, sortOrder, dateRange, numToDisplay, normalize }) => {
try {
// Get monitor, if we can't find it, abort with error
const monitor = await this.Monitor.findById(monitorId);
if (monitor === null || monitor === undefined) {
throw new Error(this.stringService.getDbFindMonitorById(monitorId));
}
// Get query params
const sort = sortOrder === "asc" ? 1 : -1;
// Get Checks for monitor in date range requested
const dates = this.getDateRange(dateRange);
const { checksAll, checksForDateRange } = await this.getMonitorChecks(monitorId, dates, sort);
// Build monitor stats
const monitorStats = {
...monitor.toObject(),
uptimeDuration: this.calculateUptimeDuration(checksAll),
lastChecked: this.getLastChecked(checksAll),
latestResponseTime: this.getLatestResponseTime(checksAll),
periodIncidents: this.getIncidents(checksForDateRange),
periodTotalChecks: checksForDateRange.length,
checks: this.processChecksForDisplay(this.NormalizeData, checksForDateRange, numToDisplay, normalize),
};
if (monitor.type === "http" || monitor.type === "ping" || monitor.type === "docker" || monitor.type === "port" || monitor.type === "game") {
// HTTP/PING Specific stats
monitorStats.periodAvgResponseTime = this.getAverageResponseTime(checksForDateRange);
monitorStats.periodUptime = this.getUptimePercentage(checksForDateRange);
const groupedChecks = this.groupChecksByTime(checksForDateRange, dateRange);
monitorStats.aggregateData = Object.values(groupedChecks).map(this.calculateGroupStats);
}
return monitorStats;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getMonitorStatsById";
throw error;
}
};
getHardwareDetailsById = async ({ monitorId, dateRange }) => {
try {
const monitor = await this.Monitor.findById(monitorId);
const dates = this.getDateRange(dateRange);
const formatLookup = {
recent: "%Y-%m-%dT%H:%M:00Z",
day: "%Y-%m-%dT%H:00:00Z",
week: "%Y-%m-%dT00:00:00Z",
month: "%Y-%m-%dT00:00:00Z",
};
const dateString = formatLookup[dateRange];
const hardwareStats = await this.Check.aggregate(buildHardwareDetailsPipeline(monitor, dates, dateString));
const stats = hardwareStats[0];
return {
...monitor.toObject(),
stats,
};
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getHardwareDetailsById";
throw error;
}
};
getMonitorsByTeamId = async ({ limit, type, page, rowsPerPage, filter, field, order, teamId }) => {
limit = parseInt(limit);
page = parseInt(page);
rowsPerPage = parseInt(rowsPerPage);
if (field === undefined) {
field = "name";
order = "asc";
}
// Build match stage
const matchStage = { teamId: new this.ObjectId(teamId) };
if (type !== undefined) {
matchStage.type = Array.isArray(type) ? { $in: type } : type;
}
const summaryResult = await this.Monitor.aggregate(buildMonitorSummaryByTeamIdPipeline({ matchStage }));
const summary = summaryResult[0];
const monitors = await this.Monitor.aggregate(buildMonitorsByTeamIdPipeline({ matchStage, field, order }));
const filteredMonitors = await this.Monitor.aggregate(
buildFilteredMonitorsByTeamIdPipeline({
matchStage,
filter,
page,
rowsPerPage,
field,
order,
limit,
type,
})
);
const normalizedFilteredMonitors = filteredMonitors.map((monitor) => {
if (!monitor.checks) {
return monitor;
}
monitor.checks = this.NormalizeData(monitor.checks, 10, 100);
return monitor;
});
return { summary, monitors, filteredMonitors: normalizedFilteredMonitors };
};
getMonitorsAndSummaryByTeamId = async ({ type, explain, teamId }) => {
try {
const matchStage = { teamId: new this.ObjectId(teamId) };
if (type !== undefined) {
matchStage.type = Array.isArray(type) ? { $in: type } : type;
}
if (explain === true) {
return this.Monitor.aggregate(buildMonitorsAndSummaryByTeamIdPipeline({ matchStage })).explain("executionStats");
}
const queryResult = await this.Monitor.aggregate(buildMonitorsAndSummaryByTeamIdPipeline({ matchStage }));
const { monitors, summary } = queryResult?.[0] ?? {};
return { monitors, summary };
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getMonitorsAndSummaryByTeamId";
throw error;
}
};
getMonitorsWithChecksByTeamId = async ({ limit, type, page, rowsPerPage, filter, field, order, teamId, explain }) => {
try {
limit = parseInt(limit);
page = parseInt(page);
rowsPerPage = parseInt(rowsPerPage);
if (field === undefined) {
field = "name";
order = "asc";
}
// Build match stage
const matchStage = { teamId: new this.ObjectId(teamId) };
if (type !== undefined) {
matchStage.type = Array.isArray(type) ? { $in: type } : type;
}
if (explain === true) {
return this.Monitor.aggregate(
buildMonitorsWithChecksByTeamIdPipeline({
matchStage,
filter,
page,
rowsPerPage,
field,
order,
limit,
type,
})
).explain("executionStats");
}
const queryResult = await this.Monitor.aggregate(
buildMonitorsWithChecksByTeamIdPipeline({
matchStage,
filter,
page,
rowsPerPage,
field,
order,
limit,
type,
})
);
const monitors = queryResult[0]?.monitors;
const count = queryResult[0]?.count;
const normalizedFilteredMonitors = monitors.map((monitor) => {
if (!monitor.checks) {
return monitor;
}
monitor.checks = this.NormalizeData(monitor.checks, 10, 100);
return monitor;
});
return { count, monitors: normalizedFilteredMonitors };
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getMonitorsWithChecksByTeamId";
throw error;
}
};
createMonitor = async ({ body, teamId, userId }) => {
try {
const monitor = new this.Monitor({ ...body, teamId, userId });
const saved = await monitor.save();
return saved;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "createMonitor";
throw error;
}
};
createBulkMonitors = async (req) => {
try {
const monitors = req.map((item) => new this.Monitor({ ...item, notifications: undefined }));
await this.Monitor.bulkSave(monitors);
return monitors;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "createBulkMonitors";
throw error;
}
};
deleteMonitor = async ({ teamId, monitorId }) => {
try {
const deletedMonitor = await this.Monitor.findOneAndDelete({ _id: monitorId, teamId });
if (!deletedMonitor) {
throw new Error(this.stringService.getDbFindMonitorById(monitorId));
}
return deletedMonitor;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "deleteMonitor";
throw error;
}
};
deleteAllMonitors = async (teamId) => {
try {
const monitors = await this.Monitor.find({ teamId });
const { deletedCount } = await this.Monitor.deleteMany({ teamId });
return { monitors, deletedCount };
} catch (error) {
error.service = SERVICE_NAME;
error.method = "deleteAllMonitors";
throw error;
}
};
deleteMonitorsByUserId = async (userId) => {
try {
const result = await this.Monitor.deleteMany({ userId: userId });
return result;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "deleteMonitorsByUserId";
throw error;
}
};
editMonitor = async ({ monitorId, body }) => {
try {
const editedMonitor = await this.Monitor.findByIdAndUpdate(monitorId, body, {
new: true,
});
return editedMonitor;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "editMonitor";
throw error;
}
};
addDemoMonitors = async (userId, teamId) => {
try {
const demoMonitors = JSON.parse(this.fs.readFileSync(this.demoMonitorsPath, "utf8"));
const demoMonitorsToInsert = demoMonitors.map((monitor) => {
return {
userId,
teamId,
name: monitor.name,
description: monitor.name,
type: "http",
url: monitor.url,
interval: 60000,
};
});
const insertedMonitors = await this.Monitor.insertMany(demoMonitorsToInsert);
return insertedMonitors;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "addDemoMonitors";
throw error;
}
};
pauseMonitor = async ({ monitorId }) => {
try {
const monitor = await this.Monitor.findOneAndUpdate(
{ _id: monitorId },
[
{
$set: {
isActive: { $not: "$isActive" },
status: "$$REMOVE",
},
},
],
{ new: true }
);
return monitor;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "pauseMonitor";
throw error;
}
};
getGroupsByTeamId = async ({ teamId }) => {
try {
const groups = await this.Monitor.distinct("group", {
teamId: new this.ObjectId(teamId),
group: { $ne: null, $ne: "" },
});
return groups.filter(Boolean).sort();
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getGroupsByTeamId";
throw error;
}
};
}
export default MonitorModule;
File diff suppressed because it is too large. Load diff
@@ -1,100 +0,0 @@
// import Notification from "../../models/Notification.js";
// import Monitor from "../../models/Monitor.js";
const SERVICE_NAME = "notificationModule";
class NotificationModule {
constructor({ Notification, Monitor }) {
this.Notification = Notification;
this.Monitor = Monitor;
}
createNotification = async (notificationData) => {
try {
const notification = await new this.Notification({ ...notificationData }).save();
return notification;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "createNotification";
throw error;
}
};
getNotificationsByTeamId = async (teamId) => {
try {
const notifications = await this.Notification.find({ teamId });
return notifications;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getNotificationsByTeamId";
throw error;
}
};
getNotificationsByIds = async (notificationIds) => {
try {
const notifications = await this.Notification.find({ _id: { $in: notificationIds } });
return notifications;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getNotificationsByIds";
throw error;
}
};
getNotificationsByMonitorId = async (monitorId) => {
try {
const notifications = await this.Notification.find({ monitorId });
return notifications;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getNotificationsByMonitorId";
throw error;
}
};
deleteNotificationsByMonitorId = async (monitorId) => {
try {
const result = await this.Notification.deleteMany({ monitorId });
return result.deletedCount;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "deleteNotificationsByMonitorId";
throw error;
}
};
deleteNotificationById = async (id) => {
try {
const notification = await this.Notification.findById(id);
if (!notification) {
throw new Error("Notification not found");
}
const result = await this.Notification.findByIdAndDelete(id);
await this.Monitor.updateMany({ notifications: id }, { $pull: { notifications: id } });
return result;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "deleteNotificationById";
throw error;
}
};
getNotificationById = async (id) => {
try {
const notification = await this.Notification.findById(id);
return notification;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getNotificationById";
throw error;
}
};
editNotification = async (id, notificationData) => {
try {
const notification = await this.Notification.findByIdAndUpdate(id, notificationData, {
new: true,
});
return notification;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "editNotification";
throw error;
}
};
}
export default NotificationModule;
@@ -1,80 +0,0 @@
const SERVICE_NAME = "recoveryModule";
class RecoveryModule {
constructor({ User, RecoveryToken, crypto, stringService }) {
this.User = User;
this.RecoveryToken = RecoveryToken;
this.crypto = crypto;
this.stringService = stringService;
}
requestRecoveryToken = async (email) => {
try {
// Delete any existing tokens
await this.RecoveryToken.deleteMany({ email });
let recoveryToken = new this.RecoveryToken({
email,
token: this.crypto.randomBytes(32).toString("hex"),
});
await recoveryToken.save();
return recoveryToken;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "requestRecoveryToken";
throw error;
}
};
validateRecoveryToken = async (candidateToken) => {
try {
const recoveryToken = await this.RecoveryToken.findOne({
token: candidateToken,
});
if (recoveryToken !== null) {
return recoveryToken;
} else {
throw new Error(this.stringService.dbTokenNotFound);
}
} catch (error) {
error.service = SERVICE_NAME;
error.method = "validateRecoveryToken";
throw error;
}
};
resetPassword = async (password, candidateToken) => {
try {
const newPassword = password;
// Validate token again
const recoveryToken = await this.validateRecoveryToken(candidateToken);
const user = await this.User.findOne({ email: recoveryToken.email });
if (user === null) {
throw new Error(this.stringService.dbUserNotFound);
}
const match = await user.comparePassword(newPassword);
if (match === true) {
throw new Error("Password cannot be the same as the old password");
}
user.password = newPassword;
await user.save();
await this.RecoveryToken.deleteMany({ email: recoveryToken.email });
// Fetch the user again without the password
const userWithoutPassword = await this.User.findOne({
email: recoveryToken.email,
})
.select("-password")
.select("-profileImage");
return userWithoutPassword;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "resetPassword";
throw error;
}
};
}
export default RecoveryModule;
@@ -1,36 +0,0 @@
// import AppSettings from "../../models/AppSettings.js";
const SERVICE_NAME = "SettingsModule";
class SettingsModule {
constructor({ AppSettings }) {
this.AppSettings = AppSettings;
}
updateAppSettings = async (newSettings) => {
try {
const update = { $set: { ...newSettings } };
if (newSettings.pagespeedApiKey === "") {
update.$unset = { pagespeedApiKey: "" };
delete update.$set.pagespeedApiKey;
}
if (newSettings.systemEmailPassword === "") {
update.$unset = { systemEmailPassword: "" };
delete update.$set.systemEmailPassword;
}
await this.AppSettings.findOneAndUpdate({}, update, {
upsert: true,
});
const settings = await this.AppSettings.findOne().select("-__v -_id -createdAt -updatedAt -singleton").lean();
return settings;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "updateAppSettings";
throw error;
}
};
}
export default SettingsModule;
@@ -1,298 +0,0 @@
// import StatusPage from "../../models/StatusPage.js";
// import { NormalizeData } from "../../../utils/dataUtils.js";
// import ServiceRegistry from "../../../service/system/serviceRegistry.js";
// import StringService from "../../../service/system/stringService.js";
const SERVICE_NAME = "statusPageModule";
class StatusPageModule {
constructor({ StatusPage, NormalizeData, stringService }) {
this.StatusPage = StatusPage;
this.NormalizeData = NormalizeData;
this.stringService = stringService;
}
createStatusPage = async ({ statusPageData, image, userId, teamId }) => {
try {
const statusPage = new this.StatusPage({
...statusPageData,
userId,
teamId,
});
if (image) {
statusPage.logo = {
data: image.buffer,
contentType: image.mimetype,
};
}
await statusPage.save();
return statusPage;
} catch (error) {
if (error?.code === 11000) {
// Handle duplicate URL errors
error.status = 400;
error.message = this.stringService.statusPageUrlNotUnique;
}
error.service = SERVICE_NAME;
error.method = "createStatusPage";
throw error;
}
};
updateStatusPage = async (statusPageData, image) => {
try {
if (image) {
statusPageData.logo = {
data: image.buffer,
contentType: image.mimetype,
};
} else {
statusPageData.logo = null;
}
if (statusPageData.deleteSubmonitors === "true") {
statusPageData.subMonitors = [];
}
const statusPage = await this.StatusPage.findOneAndUpdate({ url: statusPageData.url }, statusPageData, {
new: true,
});
return statusPage;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "updateStatusPage";
throw error;
}
};
getStatusPageByUrl = async (url) => {
// TODO This is deprecated, can remove and have controller call getStatusPage
try {
return this.getStatusPage(url);
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getStatusPageByUrl";
throw error;
}
};
getStatusPagesByTeamId = async (teamId) => {
try {
const statusPages = await this.StatusPage.find({ teamId });
return statusPages;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getStatusPagesByTeamId";
throw error;
}
};
getStatusPage = async (url) => {
try {
const preliminaryStatusPage = await this.StatusPage.findOne({ url });
if (!preliminaryStatusPage) {
const error = new Error(this.stringService.statusPageNotFound);
error.status = 404;
throw error;
}
if (!preliminaryStatusPage.monitors || preliminaryStatusPage.monitors.length === 0) {
const { _id, color, companyName, isPublished, logo, originalMonitors, showCharts, showUptimePercentage, timezone, showAdminLoginLink, url } =
preliminaryStatusPage;
return {
statusPage: {
_id,
color,
companyName,
isPublished,
logo,
originalMonitors,
showCharts,
showUptimePercentage,
timezone,
showAdminLoginLink,
url,
},
monitors: [],
};
}
const statusPageQuery = await this.StatusPage.aggregate([
{ $match: { url: url } },
{
$set: {
originalMonitors: "$monitors",
},
},
{
$lookup: {
from: "monitors",
localField: "monitors",
foreignField: "_id",
as: "monitors",
},
},
{
$unwind: {
path: "$monitors",
preserveNullAndEmptyArrays: true,
},
},
{
$lookup: {
from: "maintenancewindows",
let: { monitorId: "$monitors._id" },
pipeline: [{ $match: { $expr: { $eq: ["$monitorId", "$$monitorId"] } } }],
as: "monitors.maintenanceWindows",
},
},
{
$lookup: {
from: "checks",
let: { monitorId: "$monitors._id" },
pipeline: [
{
$match: {
$expr: { $eq: ["$monitorId", "$$monitorId"] },
},
},
{ $sort: { createdAt: -1 } },
{ $limit: 25 },
],
as: "monitors.checks",
},
},
{
$lookup: {
from: "monitorstats",
localField: "monitors._id",
foreignField: "monitorId",
as: "monitors.stats",
},
},
{
$addFields: {
"monitors.orderIndex": {
$indexOfArray: ["$originalMonitors", "$monitors._id"],
},
"monitors.isMaintenance": {
$reduce: {
input: "$monitors.maintenanceWindows",
initialValue: false,
in: {
$or: [
"$$value",
{
$and: [{ $eq: ["$$this.active", true] }, { $lte: ["$$this.start", "$$NOW"] }, { $gte: ["$$this.end", "$$NOW"] }],
},
],
},
},
},
"monitors.uptimePercentage": {
$arrayElemAt: ["$monitors.stats.uptimePercentage", 0],
},
},
},
{ $match: { "monitors.orderIndex": { $ne: -1 } } },
{ $sort: { "monitors.orderIndex": 1 } },
{
$group: {
_id: "$_id",
statusPage: { $first: "$$ROOT" },
monitors: { $push: "$monitors" },
},
},
{
$project: {
statusPage: {
_id: 1,
color: 1,
companyName: 1,
isPublished: 1,
logo: 1,
originalMonitors: 1,
showCharts: 1,
showUptimePercentage: 1,
timezone: 1,
showAdminLoginLink: 1,
url: 1,
},
monitors: {
_id: 1,
userId: 1,
teamId: 1,
name: 1,
description: 1,
status: 1,
type: 1,
ignoreTlsErrors: 1,
jsonPath: 1,
expectedValue: 1,
matchMethod: 1,
url: 1,
port: 1,
isActive: 1,
interval: 1,
uptimePercentage: 1,
notifications: 1,
secret: 1,
thresholds: 1,
alertThreshold: 1,
cpuAlertThreshold: 1,
memoryAlertThreshold: 1,
diskAlertThreshold: 1,
tempAlertThreshold: 1,
checks: 1,
isMaintenance: 1,
createdAt: 1,
updatedAt: 1,
},
},
},
]);
if (!statusPageQuery.length) {
const error = new Error(this.stringService.statusPageNotFound);
error.status = 404;
throw error;
}
const { statusPage, monitors } = statusPageQuery[0];
const normalizedMonitors = monitors.map((monitor) => {
return {
...monitor,
checks: this.NormalizeData(monitor.checks, 10, 100),
};
});
return { statusPage, monitors: normalizedMonitors };
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getStatusPageByUrl";
throw error;
}
};
deleteStatusPage = async (url) => {
try {
await this.StatusPage.deleteOne({ url });
} catch (error) {
error.service = SERVICE_NAME;
error.method = "deleteStatusPage";
throw error;
}
};
deleteStatusPagesByMonitorId = async (monitorId) => {
try {
await this.StatusPage.deleteMany({ monitors: { $in: [monitorId] } });
} catch (error) {
error.service = SERVICE_NAME;
error.method = "deleteStatusPageByMonitorId";
throw error;
}
};
}
export default StatusPageModule;
-171
View File
@@ -1,171 +0,0 @@
const SERVICE_NAME = "userModule";
const DUPLICATE_KEY_CODE = 11000; // MongoDB error code for duplicate key
class UserModule {
constructor({ User, Team, GenerateAvatarImage, ParseBoolean, stringService }) {
this.User = User;
this.Team = Team;
this.GenerateAvatarImage = GenerateAvatarImage;
this.ParseBoolean = ParseBoolean;
this.stringService = stringService;
}
checkSuperadmin = async () => {
try {
const superAdmin = await this.User.findOne({ role: "superadmin" });
if (superAdmin !== null) {
return true;
}
return false;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "checkSuperadmin";
throw error;
}
};
insertUser = async (userData, imageFile) => {
try {
if (imageFile) {
// 1. Save the full size image
userData.profileImage = {
data: imageFile.buffer,
contentType: imageFile.mimetype,
};
// 2. Get the avatar sized image
const avatar = await this.GenerateAvatarImage(imageFile);
userData.avatarImage = avatar;
}
// Handle creating team if superadmin
if (userData.role.includes("superadmin")) {
const team = new this.Team({
email: userData.email,
});
userData.teamId = team._id;
userData.checkTTL = 60 * 60 * 24 * 30;
await team.save();
}
const newUser = new this.User(userData);
await newUser.save();
return await this.User.findOne({ _id: newUser._id }).select("-password").select("-profileImage"); // .select() doesn't work with create, need to save then find
} catch (error) {
if (error.code === DUPLICATE_KEY_CODE) {
error.message = this.stringService.dbUserExists;
}
error.service = SERVICE_NAME;
error.method = "insertUser";
throw error;
}
};
getUserByEmail = async (email) => {
try {
// Need the password to be able to compare, removed .select()
// We can strip the hash before returning the user
const user = await this.User.findOne({ email: email }).select("-profileImage");
if (!user) {
throw new Error(this.stringService.dbUserNotFound);
}
return user;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getUserByEmail";
throw error;
}
};
updateUser = async ({ userId, user, file }) => {
if (!userId) {
throw new Error("No user in request");
}
try {
const candidateUser = { ...user };
if (this.ParseBoolean(candidateUser.deleteProfileImage) === true) {
candidateUser.profileImage = null;
candidateUser.avatarImage = null;
} else if (file) {
// 1. Save the full size image
candidateUser.profileImage = {
data: file.buffer,
contentType: file.mimetype,
};
// 2. Get the avatar sized image
const avatar = await this.GenerateAvatarImage(file);
candidateUser.avatarImage = avatar;
}
const updatedUser = await this.User.findByIdAndUpdate(
userId,
candidateUser,
{ new: true } // Returns updated user instead of pre-update user
)
.select("-password")
.select("-profileImage");
return updatedUser;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "updateUser";
throw error;
}
};
deleteUser = async (userId) => {
try {
const deletedUser = await this.User.findByIdAndDelete(userId);
if (!deletedUser) {
throw new Error(this.stringService.dbUserNotFound);
}
return deletedUser;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "deleteUser";
throw error;
}
};
getAllUsers = async () => {
try {
const users = await this.User.find().select("-password").select("-profileImage");
return users;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getAllUsers";
throw error;
}
};
getUserById = async (roles, userId) => {
try {
if (!roles.includes("superadmin")) {
throw new Error("User is not a superadmin");
}
const user = await this.User.findById(userId).select("-password").select("-profileImage");
if (!user) {
throw new Error("User not found");
}
return user;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getUserById";
throw error;
}
};
editUserById = async (userId, user) => {
try {
await this.User.findByIdAndUpdate(userId, user, { new: true }).select("-password").select("-profileImage");
} catch (error) {
error.service = SERVICE_NAME;
error.method = "editUserById";
throw error;
}
};
}
export default UserModule;
Loaded 100 of 955 files, more files were not shown because too many files have changed in this diff. Show more