Initial commit

This commit is contained in:
zervo 2024-07-04 11:22:03 +02:00
commit 169b8c2269
45 changed files with 3968 additions and 0 deletions

1
.gitignore vendored Executable file
View file

@ -0,0 +1 @@
*.db

15
.vscode/launch.json vendored Normal file
View file

@ -0,0 +1,15 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Launch Package",
"type": "go",
"request": "launch",
"mode": "auto",
"program": "${fileDirname}"
}
]
}

661
LICENSE Executable file
View file

@ -0,0 +1,661 @@
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) <year> <name of author>
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/>.

5
README.md Executable file
View file

@ -0,0 +1,5 @@
# ScheduleTogether Backend
This is the backend for ScheduleTogether, the schedule management service. It provides a REST API for managing and organizing schedules, users, communication and more. This API is made to integrate with the official frontend. This includes features such as user authentication, event management, integration with third-party services and more. The service is built using Go and Iris, and primarely uses MariaDB as its database.
Proper documentation is soon to come.

52
cmd/stbackend/main.go Executable file
View file

@ -0,0 +1,52 @@
/*
ScheduleTogether Backend
Copyright (C) 2024, Zervó Zadachin
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation.
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 version 3 for more details.
This program incorporates external libraries for certain functionalities.
These libraries are covered by their respective licenses, and their usage
agreements are as outlined in their respective documentation or source
code.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package main
import (
"fmt"
"log"
"git.zervo.org/scheduletogether/scheduletogetherbackend/internal/api"
"git.zervo.org/scheduletogether/scheduletogetherbackend/pkg/helpers/config"
)
// main starts the server
func main() {
// Load configuration
cfg, err := config.LoadConfig()
if err != nil {
log.Fatal(err)
}
// Create Iris server instance
app := api.NewServer()
// Start the server
addr := fmt.Sprintf(":%d", cfg.ServerPort) // Assuming port is in config
log.Printf("Starting server on address: %s\n", addr)
if err := app.Listen(addr); err != nil {
log.Fatal(err)
}
}

59
go.mod Executable file
View file

@ -0,0 +1,59 @@
module git.zervo.org/scheduletogether/scheduletogetherbackend
go 1.22.1
require (
github.com/google/uuid v1.6.0
github.com/kataras/iris/v12 v12.2.10
github.com/robfig/cron/v3 v3.0.0
golang.org/x/crypto v0.18.0
gorm.io/driver/sqlite v1.5.5
gorm.io/gorm v1.25.9
)
require (
github.com/BurntSushi/toml v1.3.2 // indirect
github.com/CloudyKit/fastprinter v0.0.0-20200109182630-33d98a066a53 // indirect
github.com/CloudyKit/jet/v6 v6.2.0 // indirect
github.com/Joker/jade v1.1.3 // indirect
github.com/Shopify/goreferrer v0.0.0-20220729165902-8cddb4f5de06 // indirect
github.com/andybalholm/brotli v1.1.0 // indirect
github.com/aymerick/douceur v0.2.0 // indirect
github.com/fatih/structs v1.1.0 // indirect
github.com/flosch/pongo2/v4 v4.0.2 // indirect
github.com/golang/snappy v0.0.4 // indirect
github.com/gomarkdown/markdown v0.0.0-20231222211730-1d6d20845b47 // indirect
github.com/gorilla/css v1.0.0 // indirect
github.com/iris-contrib/schema v0.0.6 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/josharian/intern v1.0.0 // indirect
github.com/kataras/blocks v0.0.8 // indirect
github.com/kataras/golog v0.1.11 // indirect
github.com/kataras/jwt v0.1.12 // indirect
github.com/kataras/pio v0.0.13 // indirect
github.com/kataras/sitemap v0.0.6 // indirect
github.com/kataras/tunnel v0.0.4 // indirect
github.com/klauspost/compress v1.17.4 // indirect
github.com/mailgun/raymond/v2 v2.0.48 // indirect
github.com/mailru/easyjson v0.7.7 // indirect
github.com/mattn/go-sqlite3 v1.14.22 // indirect
github.com/microcosm-cc/bluemonday v1.0.26 // indirect
github.com/russross/blackfriday/v2 v2.1.0 // indirect
github.com/schollz/closestmatch v2.1.0+incompatible // indirect
github.com/sirupsen/logrus v1.8.1 // indirect
github.com/tdewolff/minify/v2 v2.20.14 // indirect
github.com/tdewolff/parse/v2 v2.7.8 // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect
github.com/vmihailenco/msgpack/v5 v5.4.1 // indirect
github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect
github.com/yosssi/ace v0.0.5 // indirect
golang.org/x/exp v0.0.0-20240112132812-db7319d0e0e3 // indirect
golang.org/x/net v0.20.0 // indirect
golang.org/x/sys v0.16.0 // indirect
golang.org/x/text v0.14.0 // indirect
golang.org/x/time v0.5.0 // indirect
google.golang.org/protobuf v1.32.0 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)

192
go.sum Executable file
View file

@ -0,0 +1,192 @@
github.com/BurntSushi/toml v1.3.2 h1:o7IhLm0Msx3BaB+n3Ag7L8EVlByGnpq14C4YWiu/gL8=
github.com/BurntSushi/toml v1.3.2/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ=
github.com/CloudyKit/fastprinter v0.0.0-20200109182630-33d98a066a53 h1:sR+/8Yb4slttB4vD+b9btVEnWgL3Q00OBTzVT8B9C0c=
github.com/CloudyKit/fastprinter v0.0.0-20200109182630-33d98a066a53/go.mod h1:+3IMCy2vIlbG1XG/0ggNQv0SvxCAIpPM5b1nCz56Xno=
github.com/CloudyKit/jet/v6 v6.2.0 h1:EpcZ6SR9n28BUGtNJSvlBqf90IpjeFr36Tizxhn/oME=
github.com/CloudyKit/jet/v6 v6.2.0/go.mod h1:d3ypHeIRNo2+XyqnGA8s+aphtcVpjP5hPwP/Lzo7Ro4=
github.com/Joker/hpp v1.0.0 h1:65+iuJYdRXv/XyN62C1uEmmOx3432rNG/rKlX6V7Kkc=
github.com/Joker/hpp v1.0.0/go.mod h1:8x5n+M1Hp5hC0g8okX3sR3vFQwynaX/UgSOM9MeBKzY=
github.com/Joker/jade v1.1.3 h1:Qbeh12Vq6BxURXT1qZBRHsDxeURB8ztcL6f3EXSGeHk=
github.com/Joker/jade v1.1.3/go.mod h1:T+2WLyt7VH6Lp0TRxQrUYEs64nRc83wkMQrfeIQKduM=
github.com/Shopify/goreferrer v0.0.0-20220729165902-8cddb4f5de06 h1:KkH3I3sJuOLP3TjA/dfr4NAY8bghDwnXiU7cTKxQqo0=
github.com/Shopify/goreferrer v0.0.0-20220729165902-8cddb4f5de06/go.mod h1:7erjKLwalezA0k99cWs5L11HWOAPNjdUZ6RxH1BXbbM=
github.com/ajg/form v1.5.1 h1:t9c7v8JUKu/XxOGBU0yjNpaMloxGEJhUkqFRq0ibGeU=
github.com/ajg/form v1.5.1/go.mod h1:uL1WgH+h2mgNtvBq0339dVnzXdBETtL2LeUXaIv25UY=
github.com/andybalholm/brotli v1.1.0 h1:eLKJA0d02Lf0mVpIDgYnqXcUn0GqVmEFny3VuID1U3M=
github.com/andybalholm/brotli v1.1.0/go.mod h1:sms7XGricyQI9K10gOSf56VKKWS4oLer58Q+mhRPtnY=
github.com/aymerick/douceur v0.2.0 h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuPk=
github.com/aymerick/douceur v0.2.0/go.mod h1:wlT5vV2O3h55X9m7iVYN0TBM0NH/MmbLnd30/FjWUq4=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/fatih/color v1.15.0 h1:kOqh6YHBtK8aywxGerMG2Eq3H6Qgoqeo13Bk2Mv/nBs=
github.com/fatih/color v1.15.0/go.mod h1:0h5ZqXfHYED7Bhv2ZJamyIOUej9KtShiJESRwBDUSsw=
github.com/fatih/structs v1.1.0 h1:Q7juDM0QtcnhCpeyLGQKyg4TOIghuNXrkL32pHAUMxo=
github.com/fatih/structs v1.1.0/go.mod h1:9NiDSp5zOcgEDl+j00MP/WkGVPOlPRLejGD8Ga6PJ7M=
github.com/flosch/pongo2/v4 v4.0.2 h1:gv+5Pe3vaSVmiJvh/BZa82b7/00YUGm0PIyVVLop0Hw=
github.com/flosch/pongo2/v4 v4.0.2/go.mod h1:B5ObFANs/36VwxxlgKpdchIJHMvHB562PW+BWPhwZD8=
github.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=
github.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=
github.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM=
github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
github.com/gomarkdown/markdown v0.0.0-20231222211730-1d6d20845b47 h1:k4Tw0nt6lwro3Uin8eqoET7MDA4JnT8YgbCjc/g5E3k=
github.com/gomarkdown/markdown v0.0.0-20231222211730-1d6d20845b47/go.mod h1:JDGcbDT52eL4fju3sZ4TeHGsQwhG9nbDV21aMyhwPoA=
github.com/google/go-cmp v0.5.8 h1:e6P7q2lk1O+qJJb4BtCQXlK8vWEO8V1ZeuEdJNOqZyg=
github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/go-querystring v1.1.0 h1:AnCroh3fv4ZBgVIf1Iwtovgjaw/GiKJo8M8yD/fhyJ8=
github.com/google/go-querystring v1.1.0/go.mod h1:Kcdr2DB4koayq7X8pmAG4sNG59So17icRSOU623lUBU=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gorilla/css v1.0.0 h1:BQqNyPTi50JCFMTw/b67hByjMVXZRwGha6wxVGkeihY=
github.com/gorilla/css v1.0.0/go.mod h1:Dn721qIggHpt4+EFCcTLTU/vk5ySda2ReITrtgBl60c=
github.com/gorilla/websocket v1.5.1 h1:gmztn0JnHVt9JZquRuzLw3g4wouNVzKL15iLr/zn/QY=
github.com/gorilla/websocket v1.5.1/go.mod h1:x3kM2JMyaluk02fnUJpQuwD2dCS5NDG2ZHL0uE0tcaY=
github.com/imkira/go-interpol v1.1.0 h1:KIiKr0VSG2CUW1hl1jpiyuzuJeKUUpC8iM1AIE7N1Vk=
github.com/imkira/go-interpol v1.1.0/go.mod h1:z0h2/2T3XF8kyEPpRgJ3kmNv+C43p+I/CoI+jC3w2iA=
github.com/iris-contrib/httpexpect/v2 v2.15.2 h1:T9THsdP1woyAqKHwjkEsbCnMefsAFvk8iJJKokcJ3Go=
github.com/iris-contrib/httpexpect/v2 v2.15.2/go.mod h1:JLDgIqnFy5loDSUv1OA2j0mb6p/rDhiCqigP22Uq9xE=
github.com/iris-contrib/schema v0.0.6 h1:CPSBLyx2e91H2yJzPuhGuifVRnZBBJ3pCOMbOvPZaTw=
github.com/iris-contrib/schema v0.0.6/go.mod h1:iYszG0IOsuIsfzjymw1kMzTL8YQcCWlm65f3wX8J5iA=
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY=
github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=
github.com/kataras/blocks v0.0.8 h1:MrpVhoFTCR2v1iOOfGng5VJSILKeZZI+7NGfxEh3SUM=
github.com/kataras/blocks v0.0.8/go.mod h1:9Jm5zx6BB+06NwA+OhTbHW1xkMOYxahnqTN5DveZ2Yg=
github.com/kataras/golog v0.1.11 h1:dGkcCVsIpqiAMWTlebn/ZULHxFvfG4K43LF1cNWSh20=
github.com/kataras/golog v0.1.11/go.mod h1:mAkt1vbPowFUuUGvexyQ5NFW6djEgGyxQBIARJ0AH4A=
github.com/kataras/iris/v12 v12.2.10 h1:rEJVM7qMoyhv8wpgkA1yGxibFcONE0jkJ70LFLibTAA=
github.com/kataras/iris/v12 v12.2.10/go.mod h1:z4+E+kLMqZ7U4WtDsYfFnG7BjMTXLkdzMAXLVMLnMNs=
github.com/kataras/jwt v0.1.12 h1:FHPgTTj5UqjlBye4PA4/oxknCY+kQ9K34XAi8d37glA=
github.com/kataras/jwt v0.1.12/go.mod h1:xkimAtDhU/aGlQqjwvgtg+VyuPwMiyZHaY8LJRh0mYo=
github.com/kataras/pio v0.0.13 h1:x0rXVX0fviDTXOOLOmr4MUxOabu1InVSTu5itF8CXCM=
github.com/kataras/pio v0.0.13/go.mod h1:k3HNuSw+eJ8Pm2lA4lRhg3DiCjVgHlP8hmXApSej3oM=
github.com/kataras/sitemap v0.0.6 h1:w71CRMMKYMJh6LR2wTgnk5hSgjVNB9KL60n5e2KHvLY=
github.com/kataras/sitemap v0.0.6/go.mod h1:dW4dOCNs896OR1HmG+dMLdT7JjDk7mYBzoIRwuj5jA4=
github.com/kataras/tunnel v0.0.4 h1:sCAqWuJV7nPzGrlb0os3j49lk2JhILT0rID38NHNLpA=
github.com/kataras/tunnel v0.0.4/go.mod h1:9FkU4LaeifdMWqZu7o20ojmW4B7hdhv2CMLwfnHGpYw=
github.com/klauspost/compress v1.17.4 h1:Ej5ixsIri7BrIjBkRZLTo6ghwrEtHFk7ijlczPW4fZ4=
github.com/klauspost/compress v1.17.4/go.mod h1:/dCuZOvVtNoHsyb+cuJD3itjs3NbnF6KH9zAO4BDxPM=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/mailgun/raymond/v2 v2.0.48 h1:5dmlB680ZkFG2RN/0lvTAghrSxIESeu9/2aeDqACtjw=
github.com/mailgun/raymond/v2 v2.0.48/go.mod h1:lsgvL50kgt1ylcFJYZiULi5fjPBkkhNfj4KA0W54Z18=
github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0=
github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc=
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA=
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
github.com/microcosm-cc/bluemonday v1.0.26 h1:xbqSvqzQMeEHCqMi64VAs4d8uy6Mequs3rQ0k/Khz58=
github.com/microcosm-cc/bluemonday v1.0.26/go.mod h1:JyzOCs9gkyQyjs+6h10UEVSe02CGwkhd72Xdqh78TWs=
github.com/mitchellh/go-wordwrap v1.0.1 h1:TLuKupo69TCn6TQSyGxwI1EblZZEsQ0vMlAFQflz0v0=
github.com/mitchellh/go-wordwrap v1.0.1/go.mod h1:R62XHJLzvMFRBbcrT7m7WgmE1eOyTSsCt+hzestvNj0=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/robfig/cron/v3 v3.0.0 h1:kQ6Cb7aHOHTSzNVNEhmp8EcWKLb4CbiMW9h9VyIhO4E=
github.com/robfig/cron/v3 v3.0.0/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro=
github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/sanity-io/litter v1.5.5 h1:iE+sBxPBzoK6uaEP5Lt3fHNgpKcHXc/A2HGETy0uJQo=
github.com/sanity-io/litter v1.5.5/go.mod h1:9gzJgR2i4ZpjZHsKvUXIRQVk7P+yM3e+jAF7bU2UI5U=
github.com/schollz/closestmatch v2.1.0+incompatible h1:Uel2GXEpJqOWBrlyI+oY9LTiyyjYS17cCYRqP13/SHk=
github.com/schollz/closestmatch v2.1.0+incompatible/go.mod h1:RtP1ddjLong6gTkbtmuhtR2uUrrJOpYzYRvbcPAid+g=
github.com/sergi/go-diff v1.0.0 h1:Kpca3qRNrduNnOQeazBd0ysaKrUJiIuISHxogkT9RPQ=
github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo=
github.com/sirupsen/logrus v1.8.1 h1:dJKuHgqk1NNQlqoA6BTlM1Wf9DOH3NBjQyu0h9+AZZE=
github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/tdewolff/minify/v2 v2.20.14 h1:sktSuVixRwk0ryQjqvKBu/uYS+MWmkwEFMEWtFZ+TdE=
github.com/tdewolff/minify/v2 v2.20.14/go.mod h1:qnIJbnG2dSzk7LIa/UUwgN2OjS8ir6RRlqc0T/1q2xY=
github.com/tdewolff/parse/v2 v2.7.8 h1:1cnVqa8L63xFkc2vfRsZTM6Qy35nJpTvQ2Uvdv3vbvs=
github.com/tdewolff/parse/v2 v2.7.8/go.mod h1:3FbJWZp3XT9OWVN3Hmfp0p/a08v4h8J9W1aghka0soA=
github.com/tdewolff/test v1.0.11-0.20231101010635-f1265d231d52/go.mod h1:6DAvZliBAAnD7rhVgwaM7DE5/d9NMOAJ09SqYqeK4QE=
github.com/tdewolff/test v1.0.11-0.20240106005702-7de5f7df4739 h1:IkjBCtQOOjIn03u/dMQK9g+Iw9ewps4mCl1nB8Sscbo=
github.com/tdewolff/test v1.0.11-0.20240106005702-7de5f7df4739/go.mod h1:XPuWBzvdUzhCuxWO1ojpXsyzsA5bFoS3tO/Q3kFuTG8=
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
github.com/vmihailenco/msgpack/v5 v5.4.1 h1:cQriyiUvjTwOHg8QZaPihLWeRAAVoCpE00IUPn0Bjt8=
github.com/vmihailenco/msgpack/v5 v5.4.1/go.mod h1:GaZTsDaehaPpQVyxrf5mtQlH+pc21PIudVV/E3rRQok=
github.com/vmihailenco/tagparser/v2 v2.0.0 h1:y09buUbR+b5aycVFQs/g70pqKVZNBmxwAhO7/IwNM9g=
github.com/vmihailenco/tagparser/v2 v2.0.0/go.mod h1:Wri+At7QHww0WTrCBeu4J6bNtoV6mEfg5OIWRZA9qds=
github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f h1:J9EGpcZtP0E/raorCMxlFGSTBrsSlaDGf3jU/qvAE2c=
github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU=
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 h1:EzJWgHovont7NscjpAxXsDA8S8BMYve8Y5+7cuRE7R0=
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ=
github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17UxZ74=
github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y=
github.com/yalp/jsonpath v0.0.0-20180802001716-5cc68e5049a0 h1:6fRhSjgLCkTD3JnJxvaJ4Sj+TYblw757bqYgZaOq5ZY=
github.com/yalp/jsonpath v0.0.0-20180802001716-5cc68e5049a0/go.mod h1:/LWChgwKmvncFJFHJ7Gvn9wZArjbV5/FppcK2fKk/tI=
github.com/yosssi/ace v0.0.5 h1:tUkIP/BLdKqrlrPwcmH0shwEEhTRHoGnc1wFIWmaBUA=
github.com/yosssi/ace v0.0.5/go.mod h1:ALfIzm2vT7t5ZE7uoIZqF3TQ7SAOyupFZnkrF5id+K0=
github.com/yudai/gojsondiff v1.0.0 h1:27cbfqXLVEJ1o8I6v3y9lg8Ydm53EKqHXAOMxEGlCOA=
github.com/yudai/gojsondiff v1.0.0/go.mod h1:AY32+k2cwILAkW1fbgxQ5mUmMiZFgLIV+FBNExI05xg=
github.com/yudai/golcs v0.0.0-20170316035057-ecda9a501e82 h1:BHyfKlQyqbsFN5p3IfnEUduWvb9is428/nNb5L3U01M=
github.com/yudai/golcs v0.0.0-20170316035057-ecda9a501e82/go.mod h1:lgjkn3NuSvDfVJdfcVVdX+jpBxNmX4rDAzaS45IcYoM=
github.com/yuin/goldmark v1.4.1/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.18.0 h1:PGVlW0xEltQnzFZ55hkuX5+KLyrMYhHld1YHO4AKcdc=
golang.org/x/crypto v0.18.0/go.mod h1:R0j02AL6hcrfOiy9T4ZYp/rcWeMxM3L6QYxlOuEG1mg=
golang.org/x/exp v0.0.0-20240112132812-db7319d0e0e3 h1:hNQpMuAJe5CtcUqCXaWga3FHu+kQvCqcsoVaQgSV60o=
golang.org/x/exp v0.0.0-20240112132812-db7319d0e0e3/go.mod h1:idGWGoKP1toJGkd5/ig9ZLuPcZBC3ewk7SzmH0uou08=
golang.org/x/mod v0.5.1/go.mod h1:5OXOZSfqPIIbmVBIIKWRFfZjPR0E5r58TLhUjH0a2Ro=
golang.org/x/net v0.0.0-20190327091125-710a502c58a2/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.20.0 h1:aCL9BSgETF1k+blQaYUBx9hJ9LOGP3gAVemcZlf1Kpo=
golang.org/x/net v0.20.0/go.mod h1:z8BVo6PvndSri0LbOE3hAn0apkU+1YvI6E70E9jsnvY=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20211019181941-9d821ace8654/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.16.0 h1:xWw16ngr6ZMtmxDyKyIgsE93KNKz5HKmMa3b8ALHidU=
golang.org/x/sys v0.16.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/time v0.5.0 h1:o7cqy6amK/52YcAKIPlM3a+Fpj35zvRj2TP+e1xFSfk=
golang.org/x/time v0.5.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.1.9/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/protobuf v1.32.0 h1:pPC6BG5ex8PDFnkbrGU3EixyhKcQ2aDuBS36lqK/C7I=
google.golang.org/protobuf v1.32.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20200902074654-038fdea0a05b h1:QRR6H1YWRnHb4Y/HeNFCTJLFVxaq6wH4YuVdsUOr75U=
gopkg.in/check.v1 v1.0.0-20200902074654-038fdea0a05b/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA=
gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gorm.io/driver/sqlite v1.5.5 h1:7MDMtUZhV065SilG62E0MquljeArQZNfJnjd9i9gx3E=
gorm.io/driver/sqlite v1.5.5/go.mod h1:6NgQ7sQWAIFsPrJJl1lSNSu2TABh0ZZ/zm5fosATavE=
gorm.io/gorm v1.25.9 h1:wct0gxZIELDk8+ZqF/MVnHLkA1rvYlBWUMv2EdsK1g8=
gorm.io/gorm v1.25.9/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8=
moul.io/http2curl/v2 v2.3.0 h1:9r3JfDzWPcbIklMOs2TnIFzDYvfAZvjeavG6EzP7jYs=
moul.io/http2curl/v2 v2.3.0/go.mod h1:RW4hyBjTWSYDOxapodpNEtX0g5Eb16sxklBqmd2RHcE=

View file

@ -0,0 +1,99 @@
/*
ScheduleTogether Backend
Copyright (C) 2024, Zervó Zadachin
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation.
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 version 3 for more details.
This program incorporates external libraries for certain functionalities.
These libraries are covered by their respective licenses, and their usage
agreements are as outlined in their respective documentation or source
code.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package handlers
import (
"github.com/kataras/iris/v12"
"git.zervo.org/scheduletogether/scheduletogetherbackend/internal/api/middlewares"
"git.zervo.org/scheduletogether/scheduletogetherbackend/internal/api/services/accounts"
perms "git.zervo.org/scheduletogether/scheduletogetherbackend/pkg/permissions"
"git.zervo.org/scheduletogether/scheduletogetherbackend/pkg/types"
)
// AccountHandler_RegisterRoutes registers routes for the AccountHandler
func AccountHandler_RegisterRoutes(party iris.Party) {
party.Post("/register", AccountRegister_Handler)
party.Post("/signin", AccountSignin_Handler)
party.Post("/verify", AccountVerify_Handler)
party.Use(middlewares.Authenticate()) // only allow authenticated users for following endpoints
party.Post("/signout", middlewares.Authorize(perms.SignOut), AccountSignout_Handler)
}
// AccountRegister_Handler handles the POST /account/register endpoint
func AccountRegister_Handler(ctx iris.Context) {
var requestBody types.AccountRegisterRequest
// Validate the request body against the AccountRegisterRequest schema
if err := ctx.ReadJSON(&requestBody); err != nil {
ctx.StatusCode(iris.StatusBadRequest)
ctx.JSON(types.CommonErrorResponse{
Error: "Request validation failed, please check the request body and try again",
})
return
}
// Call the AccountRegister_Service function to register user
accounts.AccountRegister_Service(ctx, requestBody)
}
func AccountVerify_Handler(ctx iris.Context) {
var requestBody types.AccountVerifyRequest
// Validate the request body against the AccountRegisterRequest schema
if err := ctx.ReadJSON(&requestBody); err != nil {
ctx.StatusCode(iris.StatusBadRequest)
ctx.JSON(types.CommonErrorResponse{
Error: "Request validation failed, please check the request body and try again",
})
return
}
// Call the AccountRegister_Service function to register user
accounts.AccountVerify_Service(ctx, requestBody)
}
// AccountSignin_Handler handles the POST /account/signin endpoint
func AccountSignin_Handler(ctx iris.Context) {
var requestBody types.AccountLoginRequest
// Validate the request body against the AccountLoginRequest schema
if err := ctx.ReadJSON(&requestBody); err != nil {
ctx.StatusCode(iris.StatusBadRequest)
ctx.JSON(types.CommonErrorResponse{
Error: "Request validation failed, please check the request body and try again",
})
return
}
// Call the AccountSignin_Service function to signin user
accounts.AccountSignin_Service(ctx, requestBody)
}
// AccountSignout_Handler handles the POST /account/signout endpoint
func AccountSignout_Handler(ctx iris.Context) {
// Call the AccountSignout_Service function to signout user
accounts.AccountSignout_Service(ctx)
}

View file

@ -0,0 +1,103 @@
/*
ScheduleTogether Backend
Copyright (C) 2024, Zervó Zadachin
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation.
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 version 3 for more details.
This program incorporates external libraries for certain functionalities.
These libraries are covered by their respective licenses, and their usage
agreements are as outlined in their respective documentation or source
code.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package handlers
import (
"github.com/kataras/iris/v12"
"git.zervo.org/scheduletogether/scheduletogetherbackend/internal/api/middlewares"
"git.zervo.org/scheduletogether/scheduletogetherbackend/internal/api/services/friends"
"git.zervo.org/scheduletogether/scheduletogetherbackend/pkg/helpers/request"
perms "git.zervo.org/scheduletogether/scheduletogetherbackend/pkg/permissions"
"git.zervo.org/scheduletogether/scheduletogetherbackend/pkg/types"
)
// FriendHandler_RegisterRoutes registers routes for the AccountHandler
func FriendsHandler_RegisterRoutes(party iris.Party) {
party.Use(middlewares.Authenticate()) // only allow authenticated users for following endpoints
party.Post("/add", middlewares.Authorize(perms.SendFriendRequest), FriendAdd_Handler)
party.Post("/accept", middlewares.Authorize(perms.AcceptFriendRequest), FriendAccept_Handler)
party.Get("/", middlewares.Authorize(perms.GetOwnFriendRequests), FriendsGetRequests_Handler)
}
// FriendAdd_Handler handles the POST /friends/add endpoint
func FriendAdd_Handler(ctx iris.Context) {
var requestBody types.FriendsAddRequest
// Validate the request body against the FriendsAddRequest schema
if err := ctx.ReadJSON(&requestBody); err != nil {
ctx.StatusCode(iris.StatusBadRequest)
ctx.JSON(types.CommonErrorResponse{
Error: "Request validation failed, please check the request body and try again",
})
return
}
// Call the FriendsAdd_Service function to add a friend request to another user
friends.FriendAdd_Service(ctx, requestBody)
}
// FriendAccept_Handler handles the POST /friends/accept endpoint
func FriendAccept_Handler(ctx iris.Context) {
var requestBody types.FriendsAcceptRequest
// Validate the request body against the FriendsAcceptRequest schema
if err := ctx.ReadJSON(&requestBody); err != nil {
ctx.StatusCode(iris.StatusBadRequest)
ctx.JSON(types.CommonErrorResponse{
Error: "Request validation failed, please check the request body and try again",
})
return
}
// Call the FriendsAccept_Service function to accept a friend request
friends.FriendAccept_Service(ctx, requestBody)
}
// FriendsGetRequests_Handler handles the GET /friends endpoint
func FriendsGetRequests_Handler(ctx iris.Context) {
// Get sending user ID
claims := request.GetUserClaims(ctx)
id := claims.UserId
// Call the FriendsGetRequests_Service function to get pending friend requests for user
friends.FriendsGetRequests_Service(ctx, id)
}
// FriendsGetRequests_Handler handles the GET /friends/:id endpoint
func FriendsGetRequestsById_Handler(ctx iris.Context) {
// Get target user ID from URL
id, err := ctx.Params().GetUint64("id")
if err != nil {
ctx.StatusCode(iris.StatusBadRequest)
ctx.JSON(types.CommonErrorResponse{
Error: "Request validation failed, please check the request parameters and try again",
})
return
}
// Call the FriendsGetRequests_Service function to get pending friend requests for user
friends.FriendsGetRequests_Service(ctx, uint(id))
}

View file

@ -0,0 +1,52 @@
/*
ScheduleTogether Backend
Copyright (C) 2024, Zervó Zadachin
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation.
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 version 3 for more details.
This program incorporates external libraries for certain functionalities.
These libraries are covered by their respective licenses, and their usage
agreements are as outlined in their respective documentation or source
code.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package handlers
import (
"time"
"github.com/kataras/iris/v12"
"git.zervo.org/scheduletogether/scheduletogetherbackend/pkg/types"
)
// PingHandler_RegisterRoutes registers routes for the PingHandler
func PingHandler_RegisterRoutes(party iris.Party) {
party.Get("/", Ping_Handler)
}
// PingHandler handles the GET /ping endpoint and returns a "pong" response
func Ping_Handler(ctx iris.Context) {
now := time.Now().Format("2006-01-02 15:04:05")
response := types.PingResponse{
Message: "pong",
Time: now,
Ok: true,
}
ctx.JSON(response)
}

View file

@ -0,0 +1,66 @@
/*
ScheduleTogether Backend
Copyright (C) 2024, Zervó Zadachin
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation.
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 version 3 for more details.
This program incorporates external libraries for certain functionalities.
These libraries are covered by their respective licenses, and their usage
agreements are as outlined in their respective documentation or source
code.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package handlers
import (
"github.com/kataras/iris/v12"
"git.zervo.org/scheduletogether/scheduletogetherbackend/internal/api/middlewares"
"git.zervo.org/scheduletogether/scheduletogetherbackend/internal/api/services/users"
perms "git.zervo.org/scheduletogether/scheduletogetherbackend/pkg/permissions"
)
// UserHandler_RegisterRoutes registers routes for the UserHandler
func UsersHandler_RegisterRoutes(party iris.Party) {
party.Use(middlewares.Authenticate()) // only allow authenticated users for following endpoints
party.Get("/", middlewares.Authorize(perms.GetAllUsers), UsersGet_Handler)
party.Get("/:id", middlewares.Authorize(perms.GetUserById), UsersGetById_Handler)
party.Get("/uuid/:uuid", middlewares.Authorize(perms.GetUserByUuid), UsersGetByUuid_Handler)
party.Get("/self", middlewares.Authorize(perms.GetOwnUser), UsersGetSelf_Handler)
}
func UsersGet_Handler(ctx iris.Context) {
// Call the UsersGet_Service function to get all users
users.UsersGet_Service(ctx)
}
func UsersGetById_Handler(ctx iris.Context) {
// Call the UsersGetById_Service function to get a single user by id
users.UsersGetById_Service(ctx)
}
func UsersGetByUuid_Handler(ctx iris.Context) {
// Call the UsersGetByUuid_Service function to get a single user by uuid
users.UsersGetByUuid_Service(ctx)
}
func UsersGetSelf_Handler(ctx iris.Context) {
// Call the UsersGetSelf_Service function to get the current user
users.UsersGetSelf_Service(ctx)
}

View file

@ -0,0 +1,65 @@
/*
ScheduleTogether Backend
Copyright (C) 2024, Zervó Zadachin
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation.
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 version 3 for more details.
This program incorporates external libraries for certain functionalities.
These libraries are covered by their respective licenses, and their usage
agreements are as outlined in their respective documentation or source
code.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package middlewares
import (
"sync"
"github.com/kataras/iris/v12"
"github.com/kataras/iris/v12/middleware/jwt"
"git.zervo.org/scheduletogether/scheduletogetherbackend/pkg/helpers/cryptography"
"git.zervo.org/scheduletogether/scheduletogetherbackend/pkg/types"
)
var (
once sync.Once
Blocklist jwt.Blocklist
Verifier *jwt.Verifier
)
// Authenticate allows only authenticated (logged in) users
func Authenticate() iris.Handler {
// Use sync.Once to ensure that the blocklist and verifier is initialized once
once.Do(func() {
// Get JWT secret
secret := cryptography.GetJwtSecret()
// Create verifier
Verifier = jwt.NewVerifier(jwt.HS256, []byte(secret), jwt.Expected{Issuer: "scheduletogether"})
// Enable server-side token block feature (even before its expiration time)
Verifier.WithDefaultBlocklist()
Blocklist = Verifier.Blocklist
// Extract token from headers
Verifier.Extractors = []jwt.TokenExtractor{jwt.FromHeader}
})
// Handle token verification and add claims to request
return Verifier.Verify(func() interface{} {
return new(types.Claims)
})
}

View file

@ -0,0 +1,52 @@
/*
ScheduleTogether Backend
Copyright (C) 2024, Zervó Zadachin
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation.
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 version 3 for more details.
This program incorporates external libraries for certain functionalities.
These libraries are covered by their respective licenses, and their usage
agreements are as outlined in their respective documentation or source
code.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package middlewares
import (
"slices"
"github.com/kataras/iris/v12"
"git.zervo.org/scheduletogether/scheduletogetherbackend/pkg/helpers/request"
"git.zervo.org/scheduletogether/scheduletogetherbackend/pkg/permissions"
"git.zervo.org/scheduletogether/scheduletogetherbackend/pkg/types"
)
// Authorize checks users permissions to access a resource
func Authorize(perm types.PermissionKey) iris.Handler {
return func(ctx iris.Context) {
claims := request.GetUserClaims(ctx)
logboi.Info("claims role: " + claims.Role)
if !slices.Contains(permissions.Permissions[perm].Roles, claims.Role) {
ctx.StatusCode(iris.StatusUnauthorized)
ctx.JSON(types.CommonErrorResponse{
Error: "No permission",
})
return // Stop execution
}
// Continue to the next handler
ctx.Next()
}
}

View file

@ -0,0 +1,5 @@
package middlewares
import "git.zervo.org/scheduletogether/scheduletogetherbackend/pkg/helpers/logging"
var logboi = logging.NewLogger("api.middlewares")

96
internal/api/server.go Executable file
View file

@ -0,0 +1,96 @@
/*
ScheduleTogether Backend
Copyright (C) 2024, Zervó Zadachin
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation.
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 version 3 for more details.
This program incorporates external libraries for certain functionalities.
These libraries are covered by their respective licenses, and their usage
agreements are as outlined in their respective documentation or source
code.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package api
import (
"time"
"github.com/kataras/iris/v12"
"github.com/kataras/iris/v12/middleware/jwt"
"github.com/kataras/iris/v12/middleware/logger"
"github.com/kataras/iris/v12/middleware/recover"
"git.zervo.org/scheduletogether/scheduletogetherbackend/internal/api/handlers"
"git.zervo.org/scheduletogether/scheduletogetherbackend/internal/database"
"git.zervo.org/scheduletogether/scheduletogetherbackend/internal/workers"
"git.zervo.org/scheduletogether/scheduletogetherbackend/pkg/helpers/config"
"git.zervo.org/scheduletogether/scheduletogetherbackend/pkg/helpers/logging"
)
var logboi = logging.NewLogger("api.server")
// GlobalSigner and GlobalVerifier are used to store global jwt signer and verifier
var JwtSigner *jwt.Signer
var JwtVerifier *jwt.Verifier
// InitDb initializes the database
func InitDb() {
err := database.Init()
if err != nil {
logboi.Fatal("Failed to initialize database: " + err.Error())
}
}
// NewServer creates a new Iris server instance
func NewServer() *iris.Application {
// Load configuration
cfg, err := config.LoadConfig()
if err != nil {
logboi.Fatal(err.Error())
}
// Initialize database
InitDb()
// Create Iris server instance
app := iris.New()
// Create JWT signer
JwtSigner = jwt.NewSigner(jwt.HS256, []byte(cfg.JWTSecret), time.Duration(cfg.JWTExpiration)*time.Minute)
// Create JWT verifier
JwtVerifier = jwt.NewVerifier(jwt.HS256, cfg.JWTSecret)
// Schedule workers
workers.ScheduleWorkers()
// Apply common middleware
app.Use(recover.New())
app.Use(logger.New())
// Configure routes (handlers)
pingRoutes := app.Party("/ping")
accountRoutes := app.Party("/account")
friendRoutes := app.Party("/friends")
userRoutes := app.Party("/users")
// Register routes (handlers)
handlers.PingHandler_RegisterRoutes(pingRoutes)
handlers.AccountHandler_RegisterRoutes(accountRoutes)
handlers.FriendsHandler_RegisterRoutes(friendRoutes)
handlers.UsersHandler_RegisterRoutes(userRoutes)
return app
}

View file

@ -0,0 +1,140 @@
/*
ScheduleTogether Backend
Copyright (C) 2024, Zervó Zadachin
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation.
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 version 3 for more details.
This program incorporates external libraries for certain functionalities.
These libraries are covered by their respective licenses, and their usage
agreements are as outlined in their respective documentation or source
code.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package accounts
import (
"github.com/kataras/iris/v12"
db "git.zervo.org/scheduletogether/scheduletogetherbackend/internal/database"
"git.zervo.org/scheduletogether/scheduletogetherbackend/pkg/helpers/cryptography"
"git.zervo.org/scheduletogether/scheduletogetherbackend/pkg/types"
)
// AccountRegister_Service registers a new user
func AccountRegister_Service(ctx iris.Context, req types.AccountRegisterRequest) {
// Validate user properties
err := validateUserProperties(ctx, req)
if err != nil {
return
}
// Hash password
hashedPassword, err := cryptography.HashString(req.Password)
if err != nil {
ctx.StatusCode(iris.StatusInternalServerError)
ctx.JSON(types.CommonErrorResponse{
Error: "An error occured while registering your account, please try again later",
})
logboi.Warn("Failed to hash password: " + err.Error())
return
}
// Generate uuid
userid, err := generateUUID()
if err != nil {
ctx.StatusCode(iris.StatusInternalServerError)
ctx.JSON(types.CommonErrorResponse{
Error: "An error occured while registering your account, please try again later",
})
logboi.Warn("Failed to generate UUID: " + err.Error())
return
}
// Create new user record in database
newUser := db.User{
FirstName: req.FirstName,
LastName: req.LastName,
Email: req.Email,
Username: req.Username,
Role: "user", // TODO: implement proper roles?
Uuid: userid,
Hash: string(hashedPassword),
Verified: false,
}
// Start a transaction
tx := db.Db.Begin()
err = tx.Create(&newUser).Error
if err != nil {
tx.Rollback()
ctx.StatusCode(iris.StatusInternalServerError)
ctx.JSON(types.CommonErrorResponse{
Error: "An error occured while registering your account, please try again later",
})
logboi.Warn("An error occured while creating account in database: " + err.Error())
return
}
// Generate token
token, err := cryptography.GenerateToken(7)
if err != nil {
tx.Rollback()
ctx.StatusCode(iris.StatusInternalServerError)
ctx.JSON(types.CommonErrorResponse{
Error: "An error occured while registering your account, please try again later",
})
logboi.Warn("Failed to generate token: " + err.Error())
return
}
// Create verification req record in database
newVerify := db.RegisterVerification{
Uuid: userid,
Token: token,
}
err = tx.Create(&newVerify).Error
if err != nil {
tx.Rollback()
ctx.StatusCode(iris.StatusInternalServerError)
ctx.JSON(types.CommonErrorResponse{
Error: "An error occured while registering your account, please try again later",
})
logboi.Warn("An error occured while adding account verification req to database: " + err.Error())
return
}
// TODO: Send verification email thingy
// Commit the transaction if everything is successful
err = tx.Commit().Error
if err != nil {
tx.Rollback()
ctx.StatusCode(iris.StatusInternalServerError)
ctx.JSON(types.CommonErrorResponse{
Error: "Something went wrong, please try again later",
})
return
}
logboi.Info("Registered new user! Username: " + req.Username + ", Verification token: " + token)
ctx.JSON(types.AccountRegisterResponse{
Message: "User registered successfully",
Uuid: newUser.Uuid,
MustVerify: true,
})
}

View file

@ -0,0 +1,117 @@
/*
ScheduleTogether Backend
Copyright (C) 2024, Zervó Zadachin
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation.
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 version 3 for more details.
This program incorporates external libraries for certain functionalities.
These libraries are covered by their respective licenses, and their usage
agreements are as outlined in their respective documentation or source
code.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package accounts
import (
"time"
"github.com/google/uuid"
"github.com/kataras/iris/v12"
"github.com/kataras/iris/v12/middleware/jwt"
"golang.org/x/crypto/bcrypt"
db "git.zervo.org/scheduletogether/scheduletogetherbackend/internal/database"
"git.zervo.org/scheduletogether/scheduletogetherbackend/pkg/helpers/config"
"git.zervo.org/scheduletogether/scheduletogetherbackend/pkg/types"
)
// AccountSignin_Service signs in a user and returns a jwt token
func AccountSignin_Service(ctx iris.Context, req types.AccountLoginRequest) {
cfg, err := config.LoadConfig()
if err != nil {
ctx.StatusCode(iris.StatusInternalServerError)
ctx.JSON(types.CommonErrorResponse{
Error: "An error occured while registering your account, please try again later",
})
return
}
// Create signer
signer := jwt.NewSigner(jwt.HS256, []byte(cfg.JWTSecret), time.Duration(cfg.JWTExpiration)*time.Minute)
// Check if user exists
var user db.User
err = db.Db.Where("username = ?", req.Username).First(&user).Error
if err != nil {
ctx.StatusCode(iris.StatusUnauthorized)
ctx.JSON(types.CommonErrorResponse{
Error: "Invalid username or password",
})
return
}
// Check if user is verified
if !user.Verified {
ctx.StatusCode(iris.StatusUnauthorized)
ctx.JSON(types.CommonErrorResponse{
Error: "Please verify your account",
})
return
}
// Check if password is correct
err = bcrypt.CompareHashAndPassword([]byte(user.Hash), []byte(req.Password))
if err != nil {
ctx.StatusCode(iris.StatusUnauthorized)
ctx.JSON(types.CommonErrorResponse{
Error: "Invalid username or password",
})
return
}
// Generate a JWT Id
generated_jti, err := uuid.NewRandom()
if err != nil {
ctx.StopWithError(iris.StatusInternalServerError, err)
return
}
jti := generated_jti.String()
// Create claims
claims := &types.Claims{
UserId: user.ID,
Role: user.Role,
Username: user.Username,
Email: user.Email,
}
// Sign token
token, err := signer.Sign(claims, jwt.Claims{
ID: jti,
Issuer: "scheduletogether",
})
if err != nil {
ctx.StatusCode(iris.StatusInternalServerError)
ctx.JSON(types.CommonErrorResponse{
Error: "An error occured, please try again later",
})
return
}
// Return token
ctx.JSON(types.AccountSigninResponse{
Token: string(token),
})
}

View file

@ -0,0 +1,49 @@
/*
ScheduleTogether Backend
Copyright (C) 2024, Zervó Zadachin
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation.
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 version 3 for more details.
This program incorporates external libraries for certain functionalities.
These libraries are covered by their respective licenses, and their usage
agreements are as outlined in their respective documentation or source
code.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package accounts
import (
"github.com/kataras/iris/v12"
"git.zervo.org/scheduletogether/scheduletogetherbackend/pkg/types"
)
// AccountSignout_Service signs out a user by invalidating the jwt token
func AccountSignout_Service(ctx iris.Context) {
// Invalidate the token using the obtained claims
err := ctx.Logout()
if err != nil {
ctx.StatusCode(iris.StatusInternalServerError)
ctx.JSON(types.CommonErrorResponse{
Error: "An error occured while signing out: " + err.Error(),
})
logboi.Warn("Couldn't sign out user: " + err.Error())
return
}
ctx.JSON(types.CommonMessageResponse{
Message: "Successfully signed out",
})
}

View file

@ -0,0 +1,100 @@
/*
ScheduleTogether Backend
Copyright (C) 2024, Zervó Zadachin
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation.
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 version 3 for more details.
This program incorporates external libraries for certain functionalities.
These libraries are covered by their respective licenses, and their usage
agreements are as outlined in their respective documentation or source
code.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package accounts
import (
"github.com/kataras/iris/v12"
db "git.zervo.org/scheduletogether/scheduletogetherbackend/internal/database"
"git.zervo.org/scheduletogether/scheduletogetherbackend/pkg/types"
)
// AccountVerify_Service verifies an account
func AccountVerify_Service(ctx iris.Context, req types.AccountVerifyRequest) {
// Start a transaction
tx := db.Db.Begin()
// Search for UUID in pending register verification table
var registerVerificationRecord db.RegisterVerification
err := tx.Model(&db.RegisterVerification{}).Where("uuid = ?", req.Uuid).First(&registerVerificationRecord).Error
if err != nil {
tx.Rollback()
ctx.StatusCode(iris.StatusBadRequest)
ctx.JSON(types.CommonErrorResponse{
Error: "Invalid UUID or verification token",
})
return
}
// Check if provided token matches token in DB
if registerVerificationRecord.Token != req.Token {
ctx.StatusCode(iris.StatusBadRequest)
ctx.JSON(types.CommonErrorResponse{
Error: "Invalid verification token",
})
return
}
// Delete the record once verified
err = tx.Delete(&registerVerificationRecord).Error
if err != nil {
tx.Rollback()
ctx.StatusCode(iris.StatusInternalServerError)
ctx.JSON(types.CommonErrorResponse{
Error: "Something went wrong, please try again",
})
logboi.Warn("Failed to delete register verification record: " + err.Error())
return
}
// Update user record in database
var userRecord db.User
err = tx.Model(&db.User{}).Where("uuid = ?", req.Uuid).Update("verified", true).First(&userRecord).Error
if err != nil {
tx.Rollback()
ctx.StatusCode(iris.StatusInternalServerError)
ctx.JSON(types.CommonErrorResponse{
Error: "Something went wrong, please try again",
})
logboi.Warn("Failed to update user record: " + err.Error())
return
}
// Commit the transaction if everything is successful
err = tx.Commit().Error
if err != nil {
ctx.StatusCode(iris.StatusInternalServerError)
ctx.JSON(types.CommonErrorResponse{
Error: "Something went wrong, please try again",
})
return
}
logboi.Info("Verified user with UUID: " + req.Uuid)
ctx.JSON(types.CommonMessageResponse{
Message: "Account verified",
})
}

View file

@ -0,0 +1,203 @@
/*
ScheduleTogether Backend
Copyright (C) 2024, Zervó Zadachin
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation.
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 version 3 for more details.
This program incorporates external libraries for certain functionalities.
These libraries are covered by their respective licenses, and their usage
agreements are as outlined in their respective documentation or source
code.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package accounts
import (
"errors"
"regexp"
"github.com/google/uuid"
"github.com/kataras/iris/v12"
"github.com/kataras/iris/v12/middleware/jwt"
"gorm.io/gorm"
db "git.zervo.org/scheduletogether/scheduletogetherbackend/internal/database"
"git.zervo.org/scheduletogether/scheduletogetherbackend/pkg/helpers/logging"
"git.zervo.org/scheduletogether/scheduletogetherbackend/pkg/helpers/validation"
"git.zervo.org/scheduletogether/scheduletogetherbackend/pkg/types"
)
var logboi = logging.NewLogger("api.services.accounts")
// Reusable user account register/update request validation function
func validateUserProperties(ctx iris.Context, request types.AccountRegisterRequest) error {
// Validate email
if err := validation.ValidateEmail(request.Email); err != nil {
ctx.StatusCode(iris.StatusBadRequest)
ctx.JSON(types.UserRegisterFieldValidationErrorResponse{
ValidationFailed: true,
Email: "Provided email address is not valid",
})
return errors.New("validation failed")
}
// Check if email already exists in database
var existingEmailUser db.User
err := db.Db.Where("email = ?", request.Email).First(&existingEmailUser).Error
if err != gorm.ErrRecordNotFound {
ctx.StatusCode(iris.StatusBadRequest)
ctx.JSON(types.UserRegisterFieldValidationErrorResponse{
ValidationFailed: true,
Email: "This email address is already in use by another account",
})
return errors.New("validation failed")
}
// Validate firstName
if len(request.FirstName) > 50 {
ctx.StatusCode(iris.StatusBadRequest)
ctx.JSON(types.UserRegisterFieldValidationErrorResponse{
ValidationFailed: true,
FirstName: "First name is too long",
})
return errors.New("validation failed")
}
// Validate lastName
if len(request.LastName) > 50 {
ctx.StatusCode(iris.StatusBadRequest)
ctx.JSON(types.UserRegisterFieldValidationErrorResponse{
ValidationFailed: true,
LastName: "Last name is too long",
})
return errors.New("validation failed")
}
// Validate username
if len(request.Username) < 5 {
ctx.StatusCode(iris.StatusBadRequest)
ctx.JSON(types.UserRegisterFieldValidationErrorResponse{
ValidationFailed: true,
Username: "Username is too short",
})
return errors.New("validation failed")
}
if len(request.Username) > 15 {
ctx.StatusCode(iris.StatusBadRequest)
ctx.JSON(types.UserRegisterFieldValidationErrorResponse{
ValidationFailed: true,
Username: "Username is too long",
})
return errors.New("validation failed")
}
// Check if username already exists in database
var existingUsernameUser db.User
err = db.Db.Where("username = ?", request.Username).First(&existingUsernameUser).Error
if err != gorm.ErrRecordNotFound {
ctx.StatusCode(iris.StatusBadRequest)
ctx.JSON(types.UserRegisterFieldValidationErrorResponse{
ValidationFailed: true,
Username: "This username is already in use by another account",
})
return errors.New("validation failed")
}
// Validate password
if len(request.Password) < 8 {
ctx.StatusCode(iris.StatusBadRequest)
ctx.JSON(types.UserRegisterFieldValidationErrorResponse{
ValidationFailed: true,
Password: "Password is too short (minimum 8 characters)",
})
return errors.New("validation failed")
}
if len(request.Password) > 128 {
ctx.StatusCode(iris.StatusBadRequest)
ctx.JSON(types.UserRegisterFieldValidationErrorResponse{
ValidationFailed: true,
Password: "Password is too long (maximum 128 characters)",
})
return errors.New("validation failed")
}
// Check that password contains a lowercase letter
if !regexp.MustCompile(`[a-z]`).MatchString(request.Password) {
ctx.StatusCode(iris.StatusBadRequest)
ctx.JSON(types.UserRegisterFieldValidationErrorResponse{
ValidationFailed: true,
Password: "Password must contain a lowercase letter",
})
return errors.New("validation failed")
}
// Check that password contains an uppercase letter
if !regexp.MustCompile(`[A-Z]`).MatchString(request.Password) {
ctx.StatusCode(iris.StatusBadRequest)
ctx.JSON(types.UserRegisterFieldValidationErrorResponse{
ValidationFailed: true,
Password: "Password must contain an uppercase letter",
})
return errors.New("validation failed")
}
// Check that password contains a number
if !regexp.MustCompile(`[0-9]`).MatchString(request.Password) {
ctx.StatusCode(iris.StatusBadRequest)
ctx.JSON(types.UserRegisterFieldValidationErrorResponse{
ValidationFailed: true,
Password: "Password must contain a number",
})
return errors.New("validation failed")
}
return nil
}
// generateUUID generates a new unused uuid
func generateUUID() (string, error) {
for {
// generate a new uuid
uuid, err := uuid.NewRandom()
if err != nil {
return "", err
}
// check if the uuid already exists in the users table
var user db.User
err = db.Db.Where("uuid = ?", uuid.String()).First(&user).Error
if err != nil && err != gorm.ErrRecordNotFound {
return "", err
}
// if the uuid does not already exist in the users table, return it
if err == gorm.ErrRecordNotFound {
return uuid.String(), nil
}
}
}
// GetClaims returns the current authorized client claims
func GetClaims(ctx iris.Context) *types.Claims {
claims := jwt.Get(ctx).(*types.Claims)
return claims
}
// GetUserID returns the current authorized client's user id extracted from claims
func GetUserID(ctx iris.Context) uint {
return GetClaims(ctx).UserId
}

View file

@ -0,0 +1,143 @@
/*
ScheduleTogether Backend
Copyright (C) 2024, Zervó Zadachin
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation.
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 version 3 for more details.
This program incorporates external libraries for certain functionalities.
These libraries are covered by their respective licenses, and their usage
agreements are as outlined in their respective documentation or source
code.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package friends
import (
"slices"
"github.com/kataras/iris/v12"
db "git.zervo.org/scheduletogether/scheduletogetherbackend/internal/database"
"git.zervo.org/scheduletogether/scheduletogetherbackend/pkg/helpers/request"
"git.zervo.org/scheduletogether/scheduletogetherbackend/pkg/types"
)
func FriendAccept_Service(ctx iris.Context, req types.FriendsAcceptRequest) {
// Start a transaction
tx := db.Db.Begin()
// Get requesting user's ID from claims
claims := request.GetUserClaims(ctx)
id := claims.UserId
// Make sure target user exists
// Here target user refers to the user that *created* the friendrequest, opposite to friends_add
var targetUser db.User
err := tx.Where("uuid = ?", req.Uuid).First(&targetUser).Error
if err != nil {
tx.Rollback()
ctx.StatusCode(iris.StatusBadRequest)
ctx.JSON(types.CommonErrorResponse{
Error: "User does not exist",
})
return
}
// Get user from database
// Here source user refers to the user *recieving* (accepting) the friendrequest, opposite to friends_add
var sourceUser db.User
err = tx.Where("id = ?", id).First(&sourceUser).Error
if err != nil {
tx.Rollback()
ctx.StatusCode(iris.StatusInternalServerError)
ctx.JSON(types.CommonErrorResponse{
Error: "Something went wrong, please try again later",
})
logboi.Warn("Failed to retrieve user from the database: " + err.Error())
return
}
// Make sure users are not already friends
if slices.Contains(sourceUser.Friends, targetUser.Uuid) {
tx.Rollback()
ctx.StatusCode(iris.StatusBadRequest)
ctx.JSON(types.CommonErrorResponse{
Error: "You are already friends with this user",
})
}
// Make sure friend request exists
var friendRequest db.FriendRequest
err = tx.Where("target = ? AND source = ?", sourceUser.Uuid, targetUser.Uuid).First(&friendRequest).Error
if err == nil {
tx.Rollback()
ctx.StatusCode(iris.StatusBadRequest)
ctx.JSON(types.CommonErrorResponse{
Error: "Friend request already sent",
})
return
}
// Add friend to source (receiving) user
err = tx.Model(&db.User{}).Where("id = ?", id).Update("friends", append(sourceUser.Friends, targetUser.Uuid)).Error
if err != nil {
tx.Rollback()
ctx.StatusCode(iris.StatusInternalServerError)
ctx.JSON(types.CommonErrorResponse{
Error: "Something went wrong, please try again later",
})
logboi.Warn("Failed to update user on the database: " + err.Error())
return
}
// Add friend to target (accepting) user
err = tx.Model(&db.User{}).Where("id = ?", targetUser.ID).Update("friends", append(targetUser.Friends, sourceUser.Uuid)).Error
if err != nil {
tx.Rollback()
ctx.StatusCode(iris.StatusInternalServerError)
ctx.JSON(types.CommonErrorResponse{
Error: "Something went wrong, please try again later",
})
logboi.Warn("Failed to update user on the database: " + err.Error())
return
}
// Remove friend request
err = tx.Where("target = ? AND source = ?", targetUser.Uuid, sourceUser.Uuid).Delete(&db.FriendRequest{}).Error
if err != nil {
tx.Rollback()
ctx.StatusCode(iris.StatusInternalServerError)
ctx.JSON(types.CommonErrorResponse{
Error: "Something went wrong, please try again later",
})
logboi.Warn("Failed to delete friend request from the database: " + err.Error())
return
}
// Commit the transaction if everything is successful
err = tx.Commit().Error
if err != nil {
tx.Rollback()
ctx.StatusCode(iris.StatusInternalServerError)
ctx.JSON(types.CommonErrorResponse{
Error: "Something went wrong, please try again later",
})
return
}
ctx.JSON(types.CommonMessageResponse{
Message: "Friend request accepted",
})
}

View file

@ -0,0 +1,121 @@
/*
ScheduleTogether Backend
Copyright (C) 2024, Zervó Zadachin
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation.
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 version 3 for more details.
This program incorporates external libraries for certain functionalities.
These libraries are covered by their respective licenses, and their usage
agreements are as outlined in their respective documentation or source
code.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package friends
import (
"slices"
"github.com/kataras/iris/v12"
db "git.zervo.org/scheduletogether/scheduletogetherbackend/internal/database"
"git.zervo.org/scheduletogether/scheduletogetherbackend/pkg/helpers/request"
"git.zervo.org/scheduletogether/scheduletogetherbackend/pkg/types"
)
func FriendAdd_Service(ctx iris.Context, req types.FriendsAddRequest) {
// Start a transaction
tx := db.Db.Begin()
// Get requesting user's ID from claims
claims := request.GetUserClaims(ctx)
id := claims.UserId
// Make sure target user exists
// Here target refers to the user *receiving* the request
var targetUser db.User
err := tx.Where("username = ?", req.Username).First(&targetUser).Error
if err != nil {
tx.Rollback()
ctx.StatusCode(iris.StatusBadRequest)
ctx.JSON(types.CommonErrorResponse{
Error: "User does not exist",
})
return
}
// Get user from database
// Here source user refers to the user *sending* the request
var sourceUser db.User
err = tx.Where("id = ?", id).First(&sourceUser).Error
if err != nil {
tx.Rollback()
ctx.StatusCode(iris.StatusInternalServerError)
ctx.JSON(types.CommonErrorResponse{
Error: "Failed to retrieve user from the database",
})
logboi.Warn("Failed to retrieve user from the database: " + err.Error())
return
}
// Make sure users are not already friends
if slices.Contains(sourceUser.Friends, targetUser.Uuid) {
tx.Rollback()
ctx.StatusCode(iris.StatusBadRequest)
ctx.JSON(types.CommonErrorResponse{
Error: "You are already friends with this user",
})
}
// Make sure friend request has not already been sent
var friendRequest db.FriendRequest
err = tx.Where("target = ? AND source = ?", targetUser.Uuid, sourceUser.Uuid).First(&friendRequest).Error
if err == nil {
tx.Rollback()
ctx.StatusCode(iris.StatusBadRequest)
ctx.JSON(types.CommonErrorResponse{
Error: "Friend request already sent",
})
return
}
// Add friend request
err = tx.Create(&db.FriendRequest{
Source: sourceUser.Uuid,
Target: targetUser.Uuid,
}).Error
if err != nil {
tx.Rollback()
ctx.StatusCode(iris.StatusInternalServerError)
ctx.JSON(types.CommonErrorResponse{
Error: "Something went wrong, please try again later",
})
return
}
// Commit the transaction if everything is successful
err = tx.Commit().Error
if err != nil {
tx.Rollback()
ctx.StatusCode(iris.StatusInternalServerError)
ctx.JSON(types.CommonErrorResponse{
Error: "Something went wrong, please try again later",
})
return
}
ctx.JSON(types.CommonMessageResponse{
Message: "Friend request sent",
})
}

View file

@ -0,0 +1,143 @@
/*
ScheduleTogether Backend
Copyright (C) 2024, Zervó Zadachin
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation.
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 version 3 for more details.
This program incorporates external libraries for certain functionalities.
These libraries are covered by their respective licenses, and their usage
agreements are as outlined in their respective documentation or source
code.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package friends
import (
"slices"
"github.com/kataras/iris/v12"
db "git.zervo.org/scheduletogether/scheduletogetherbackend/internal/database"
"git.zervo.org/scheduletogether/scheduletogetherbackend/pkg/helpers/request"
"git.zervo.org/scheduletogether/scheduletogetherbackend/pkg/types"
)
func FriendCancel_Service(ctx iris.Context, req types.FriendsAcceptRequest) {
// Start a transaction
tx := db.Db.Begin()
// Get requesting user's ID from claims
claims := request.GetUserClaims(ctx)
id := claims.UserId
// Make sure target user exists
// Here target user refers to the user that *created* the friendrequest, opposite to friends_add
var targetUser db.User
err := tx.Where("uuid = ?", req.Uuid).First(&targetUser).Error
if err != nil {
tx.Rollback()
ctx.StatusCode(iris.StatusBadRequest)
ctx.JSON(types.CommonErrorResponse{
Error: "User does not exist",
})
return
}
// Get user from database
// Here source user refers to the user *recieving* (accepting) the friendrequest, opposite to friends_add
var sourceUser db.User
err = tx.Where("id = ?", id).First(&sourceUser).Error
if err != nil {
tx.Rollback()
ctx.StatusCode(iris.StatusInternalServerError)
ctx.JSON(types.CommonErrorResponse{
Error: "Something went wrong, please try again later",
})
logboi.Warn("Failed to retrieve user from the database: " + err.Error())
return
}
// Make sure users are not already friends
if slices.Contains(sourceUser.Friends, targetUser.Uuid) {
tx.Rollback()
ctx.StatusCode(iris.StatusBadRequest)
ctx.JSON(types.CommonErrorResponse{
Error: "You are already friends with this user",
})
}
// Make sure friend request exists
var friendRequest db.FriendRequest
err = tx.Where("target = ? AND source = ?", sourceUser.Uuid, targetUser.Uuid).First(&friendRequest).Error
if err == nil {
tx.Rollback()
ctx.StatusCode(iris.StatusBadRequest)
ctx.JSON(types.CommonErrorResponse{
Error: "Friend request already sent",
})
return
}
// Add friend to source (receiving) user
err = tx.Model(&db.User{}).Where("id = ?", id).Update("friends", append(sourceUser.Friends, targetUser.Uuid)).Error
if err != nil {
tx.Rollback()
ctx.StatusCode(iris.StatusInternalServerError)
ctx.JSON(types.CommonErrorResponse{
Error: "Something went wrong, please try again later",
})
logboi.Warn("Failed to update user on the database: " + err.Error())
return
}
// Add friend to target (accepting) user
err = tx.Model(&db.User{}).Where("id = ?", targetUser.ID).Update("friends", append(targetUser.Friends, sourceUser.Uuid)).Error
if err != nil {
tx.Rollback()
ctx.StatusCode(iris.StatusInternalServerError)
ctx.JSON(types.CommonErrorResponse{
Error: "Something went wrong, please try again later",
})
logboi.Warn("Failed to update user on the database: " + err.Error())
return
}
// Remove friend request
err = tx.Where("target = ? AND source = ?", targetUser.Uuid, sourceUser.Uuid).Delete(&db.FriendRequest{}).Error
if err != nil {
tx.Rollback()
ctx.StatusCode(iris.StatusInternalServerError)
ctx.JSON(types.CommonErrorResponse{
Error: "Something went wrong, please try again later",
})
logboi.Warn("Failed to delete friend request from the database: " + err.Error())
return
}
// Commit the transaction if everything is successful
err = tx.Commit().Error
if err != nil {
tx.Rollback()
ctx.StatusCode(iris.StatusInternalServerError)
ctx.JSON(types.CommonErrorResponse{
Error: "Something went wrong, please try again later",
})
return
}
ctx.JSON(types.CommonMessageResponse{
Message: "Friend request accepted",
})
}

View file

@ -0,0 +1,97 @@
/*
ScheduleTogether Backend
Copyright (C) 2024, Zervó Zadachin
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation.
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 version 3 for more details.
This program incorporates external libraries for certain functionalities.
These libraries are covered by their respective licenses, and their usage
agreements are as outlined in their respective documentation or source
code.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package friends
import (
"github.com/kataras/iris/v12"
db "git.zervo.org/scheduletogether/scheduletogetherbackend/internal/database"
"git.zervo.org/scheduletogether/scheduletogetherbackend/pkg/types"
)
func FriendsGetRequests_Service(ctx iris.Context, id uint) {
// Make sure a userId was passed
if id == 0 {
ctx.StatusCode(iris.StatusBadRequest)
ctx.JSON(types.CommonErrorResponse{
Error: "Something went wrong, please try again later",
})
logboi.Warn("Got userId 0 in FriendsGetRequests_Service, which is not expected behaviour")
return
}
// Get target user's information
var user db.User
err := db.Db.Where("id = ?", id).First(&user).Error
if err != nil {
ctx.StatusCode(iris.StatusBadRequest)
ctx.JSON(types.CommonErrorResponse{
Error: "Something went wrong, please try again later",
})
return
}
// Get friend requests targeted at user
var friendRequests []db.FriendRequest
err = db.Db.Where("target = ?", user.Uuid).Find(&friendRequests).Error
if err == nil {
ctx.StatusCode(iris.StatusBadRequest)
ctx.JSON(types.CommonErrorResponse{
Error: "Something went wrong, please try again later",
})
return
}
length := len(friendRequests)
var response []types.FriendRequest
// Loop over friend requests to rewrite to response format
for _, request := range friendRequests {
// Get source user information
var sourceUser db.User
err = db.Db.Where("uuid = ?", request.Source).First(&sourceUser).Error
if err != nil {
ctx.StatusCode(iris.StatusInternalServerError)
ctx.JSON(types.CommonErrorResponse{
Error: "Something went wrong, please try again later",
})
return
}
// Add to response slice
response = append(response, types.FriendRequest{
CreatedAt: request.CreatedAt.String(),
SourceUsername: sourceUser.Username,
SourceUuid: request.Source,
TargetUuid: request.Target,
})
}
// Write response
ctx.JSON(types.FriendsGetRequestsResponse{
Amount: length,
Requests: response,
})
}

View file

@ -0,0 +1,31 @@
/*
ScheduleTogether Backend
Copyright (C) 2024, Zervó Zadachin
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation.
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 version 3 for more details.
This program incorporates external libraries for certain functionalities.
These libraries are covered by their respective licenses, and their usage
agreements are as outlined in their respective documentation or source
code.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package friends
import (
"git.zervo.org/scheduletogether/scheduletogetherbackend/pkg/helpers/logging"
)
var logboi = logging.NewLogger("api.services.friends")

View file

@ -0,0 +1,31 @@
/*
ScheduleTogether Backend
Copyright (C) 2024, Zervó Zadachin
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation.
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 version 3 for more details.
This program incorporates external libraries for certain functionalities.
These libraries are covered by their respective licenses, and their usage
agreements are as outlined in their respective documentation or source
code.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package users
import (
"git.zervo.org/scheduletogether/scheduletogetherbackend/pkg/helpers/logging"
)
var logboi = logging.NewLogger("api.services.users")

View file

@ -0,0 +1,49 @@
/*
ScheduleTogether Backend
Copyright (C) 2024, Zervó Zadachin
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation.
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 version 3 for more details.
This program incorporates external libraries for certain functionalities.
These libraries are covered by their respective licenses, and their usage
agreements are as outlined in their respective documentation or source
code.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package users
import (
"github.com/kataras/iris/v12"
db "git.zervo.org/scheduletogether/scheduletogetherbackend/internal/database"
"git.zervo.org/scheduletogether/scheduletogetherbackend/pkg/types"
)
// UsersGet_Service gets all users from the database
func UsersGet_Service(ctx iris.Context) {
var users []db.User
err := db.Db.Model(&db.User{}).Select("id", "username", "email", "uuid", "role", "first_name", "last_name", "verified", "friends").Find(&users).Error
if err != nil {
ctx.StatusCode(iris.StatusInternalServerError)
ctx.JSON(types.CommonErrorResponse{
Error: "Failed to retrieve users from the database",
})
logboi.Warn("Failed to retrieve users from the database: " + err.Error())
return
}
// Return users
ctx.JSON(users)
}

View file

@ -0,0 +1,68 @@
/*
ScheduleTogether Backend
Copyright (C) 2024, Zervó Zadachin
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation.
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 version 3 for more details.
This program incorporates external libraries for certain functionalities.
These libraries are covered by their respective licenses, and their usage
agreements are as outlined in their respective documentation or source
code.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package users
import (
"github.com/kataras/iris/v12"
db "git.zervo.org/scheduletogether/scheduletogetherbackend/internal/database"
"git.zervo.org/scheduletogether/scheduletogetherbackend/pkg/types"
)
// UsersGetById_Service gets a single user from the database by id
func UsersGetById_Service(ctx iris.Context) {
// Get user ID from URL parameters
id, err := ctx.Params().GetUint64("id")
if err != nil {
ctx.StatusCode(iris.StatusBadRequest)
ctx.JSON(types.CommonErrorResponse{
Error: "Invalid id parameter",
})
return
}
// Get user from database
var user db.User
err = db.Db.Model(&db.User{}).Where("id = ?", id).Select("id", "username", "email", "uuid", "role", "first_name", "last_name", "verified", "friends").Find(&user).Error
if err != nil {
ctx.StatusCode(iris.StatusInternalServerError)
ctx.JSON(types.CommonErrorResponse{
Error: "Failed to retrieve user from the database",
})
logboi.Warn("Failed to retrieve user from the database: " + err.Error())
return
}
if user.ID == 0 {
ctx.StatusCode(iris.StatusNotFound)
ctx.JSON(types.CommonErrorResponse{
Error: "User not found",
})
return
}
// Return user
ctx.JSON(user)
}

View file

@ -0,0 +1,68 @@
/*
ScheduleTogether Backend
Copyright (C) 2024, Zervó Zadachin
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation.
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 version 3 for more details.
This program incorporates external libraries for certain functionalities.
These libraries are covered by their respective licenses, and their usage
agreements are as outlined in their respective documentation or source
code.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package users
import (
"github.com/kataras/iris/v12"
db "git.zervo.org/scheduletogether/scheduletogetherbackend/internal/database"
"git.zervo.org/scheduletogether/scheduletogetherbackend/pkg/types"
)
// UsersGetByUuid_Service gets all users from the database by uuid
func UsersGetByUuid_Service(ctx iris.Context) {
// Get user ID from URL parameters
uuid, err := ctx.Params().GetUint64("uuid")
if err != nil {
ctx.StatusCode(iris.StatusBadRequest)
ctx.JSON(types.CommonErrorResponse{
Error: "Invalid uuid parameter",
})
return
}
// Get user from database
var user db.User
err = db.Db.Model(&db.User{}).Where("uuid = ?", uuid).Select("id", "username", "email", "uuid", "role", "first_name", "last_name", "verified", "friends").Find(&user).Error
if err != nil {
ctx.StatusCode(iris.StatusInternalServerError)
ctx.JSON(types.CommonErrorResponse{
Error: "Failed to retrieve user from the database",
})
logboi.Warn("Failed to retrieve user from the database: " + err.Error())
return
}
if user.ID == 0 {
ctx.StatusCode(iris.StatusNotFound)
ctx.JSON(types.CommonErrorResponse{
Error: "User not found",
})
return
}
// Return user
ctx.JSON(user)
}

View file

@ -0,0 +1,55 @@
/*
ScheduleTogether Backend
Copyright (C) 2024, Zervó Zadachin
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation.
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 version 3 for more details.
This program incorporates external libraries for certain functionalities.
These libraries are covered by their respective licenses, and their usage
agreements are as outlined in their respective documentation or source
code.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package users
import (
"github.com/kataras/iris/v12"
db "git.zervo.org/scheduletogether/scheduletogetherbackend/internal/database"
"git.zervo.org/scheduletogether/scheduletogetherbackend/pkg/helpers/request"
"git.zervo.org/scheduletogether/scheduletogetherbackend/pkg/types"
)
// UsersGetSelf_Service gets all users from the database
func UsersGetSelf_Service(ctx iris.Context) {
// Get requesting user's ID from JWT claims
claims := request.GetUserClaims(ctx)
id := claims.UserId
// Get user from database
var user []db.User
err := db.Db.Model(&db.User{}).Where("id = ?", id).Select("id", "username", "email", "uuid", "role", "first_name", "last_name", "verified", "friends").Find(&user).Error
if err != nil {
ctx.StatusCode(iris.StatusInternalServerError)
ctx.JSON(types.CommonErrorResponse{
Error: "Failed to retrieve user from the database",
})
logboi.Warn("Failed to retrieve user from the database: " + err.Error())
return
}
// Return users
ctx.JSON(user)
}

71
internal/database/database.go Executable file
View file

@ -0,0 +1,71 @@
/*
ScheduleTogether Backend
Copyright (C) 2024, Zervó Zadachin
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation.
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 version 3 for more details.
This program incorporates external libraries for certain functionalities.
These libraries are covered by their respective licenses, and their usage
agreements are as outlined in their respective documentation or source
code.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package database
import (
"fmt"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"git.zervo.org/scheduletogether/scheduletogetherbackend/pkg/helpers/config"
"git.zervo.org/scheduletogether/scheduletogetherbackend/pkg/helpers/logging"
)
var logboi = logging.NewLogger("database")
var Db *gorm.DB
// Init initializes the database
func Init() error {
// Load configuration
cfg, err := config.LoadConfig()
if err != nil {
logboi.Err("Failed to read configuration: " + err.Error())
return err
}
// Connect to database
switch dialect := cfg.DatabaseDialect; dialect {
case "sqlite":
Db, err = gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
default:
logboi.Err("Unsupported database dialect: " + dialect)
return fmt.Errorf("unsupported database dialect: %s", dialect)
}
if err != nil {
logboi.Err("Failed to connect to database: " + err.Error())
return err
}
// Migrate database models
Db.AutoMigrate(&User{})
Db.AutoMigrate(&FriendRequest{})
Db.AutoMigrate(&RegisterVerification{})
Db.AutoMigrate(&Schedule{})
Db.AutoMigrate(&Gateway{})
return nil
}

70
internal/database/models.go Executable file
View file

@ -0,0 +1,70 @@
/*
ScheduleTogether Backend
Copyright (C) 2024, Zervó Zadachin
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation.
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 version 3 for more details.
This program incorporates external libraries for certain functionalities.
These libraries are covered by their respective licenses, and their usage
agreements are as outlined in their respective documentation or source
code.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package database
import (
"gorm.io/gorm"
)
type User struct {
gorm.Model
FirstName string `json:"firstName"`
LastName string `json:"lastName"`
Username string `json:"username"`
Email string `json:"email"`
Uuid string `json:"uuid"`
Role string `json:"role"`
Friends Friends `gorm:"type:VARCHAR(255)" json:"friends"`
Hash string `json:"hash"`
Verified bool `json:"verified"`
}
type FriendRequest struct {
gorm.Model
Target string `json:"target"`
Source string `json:"source"`
}
type RegisterVerification struct {
gorm.Model
Uuid string `json:"uuid"`
Token string `json:"token"`
}
type Schedule struct {
gorm.Model
Uuid string `json:"uuid"`
Data string `json:"data"`
}
type Gateway struct {
gorm.Model
Address string `json:"address"`
Port int `json:"port"`
Protocol string `json:"protocol"`
Priority int `json:"priority"`
Health string `json:"health"`
Key string `json:"key"`
}

55
internal/database/types.go Executable file
View file

@ -0,0 +1,55 @@
/*
ScheduleTogether Backend
Copyright (C) 2024, Zervó Zadachin
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation.
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 version 3 for more details.
This program incorporates external libraries for certain functionalities.
These libraries are covered by their respective licenses, and their usage
agreements are as outlined in their respective documentation or source
code.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package database
import (
"database/sql/driver"
"errors"
"strings"
)
// CUSTOM DATABASE TYPES IMPLEMENTATIONS
// Friends: string slice
type Friends []string
func (o *Friends) Scan(src any) error {
bytes, ok := src.([]byte)
if !ok {
return errors.New("src value cannot cast to []byte")
}
*o = strings.Split(string(bytes), ",")
return nil
}
func (o Friends) Value() (driver.Value, error) {
if len(o) == 0 {
return nil, nil
}
return strings.Join(o, ","), nil
}

78
internal/workers/coordinator.go Executable file
View file

@ -0,0 +1,78 @@
/*
ScheduleTogether Backend
Copyright (C) 2024, Zervó Zadachin
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation.
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 version 3 for more details.
This program incorporates external libraries for certain functionalities.
These libraries are covered by their respective licenses, and their usage
agreements are as outlined in their respective documentation or source
code.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package workers
import (
"time"
"github.com/robfig/cron/v3"
"git.zervo.org/scheduletogether/scheduletogetherbackend/pkg/helpers/logging"
)
var logboi = logging.NewLogger("workers")
// Reporter is a wrapper of Logger customized for workers
type Reporter struct {
workerName string
jobName string
startTime time.Time
}
// NewReporter creates a new Reporter instance
func NewReporter(workerName string, jobName string) *Reporter {
logboi.Info("<" + workerName + "/" + jobName + "> " + "[ " + logging.Yellow + logging.Bold + "START " + logging.Reset + " ]")
return &Reporter{workerName: workerName, jobName: jobName, startTime: time.Now()}
}
// Info wraps logboi.Info and reports job progress
func (l *Reporter) Status(msg string) {
logboi.Info("<" + l.workerName + "/" + l.jobName + "> " + "[ " + logging.Cyan + logging.Bold + "STATUS" + logging.Reset + " ] " + msg)
}
// Fail wraps logboi.Err and reports job failure
func (l *Reporter) Fail(msg string) {
logboi.Info("<" + l.workerName + "/" + l.jobName + "> " + "[ " + logging.Red + logging.Bold + "FAIL " + logging.Reset + " ] " + msg)
logboi.Err("Job failed! Task took " + time.Since(l.startTime).String() + ".")
}
// Finish wraps logboi.Info and announces end of a job
func (l *Reporter) Finish() {
logboi.Info("<" + l.workerName + "/" + l.jobName + "> " + "[ " + logging.Green + logging.Bold + "OK " + logging.Reset + " ]")
logboi.Info("Job took \"" + l.jobName + "\" " + time.Since(l.startTime).String() + " to complete.")
}
// Schedule workers with cron
func ScheduleWorkers() {
c := cron.New()
logboi.Info("Scheduling worker jobs...")
// Add functions / jobs
c.AddFunc("@every 30m", workerFriends_PurgeAbandonedRequests)
c.AddFunc("@every 30m", workerSchedules_PurgeAbandonedData)
c.Start()
logboi.Info("Worker jobs scheduled")
}

View file

@ -0,0 +1,79 @@
package workers
import (
"fmt"
"gorm.io/gorm"
db "git.zervo.org/scheduletogether/scheduletogetherbackend/internal/database"
)
func workerFriends_PurgeAbandonedRequests() {
reporter := NewReporter("Friends", "PurgeAbandonedRequests")
// Start a transaction
tx := db.Db.Begin()
// Get all friend requests
reporter.Status("1/2: Get all friend requests")
var friendRequests []db.FriendRequest
err := tx.Model(&db.FriendRequest{}).Find(&friendRequests).Error
if err != nil {
tx.Rollback()
reporter.Fail("Failed to retrieve friend requests from the database: " + err.Error())
return
}
reporter.Status(fmt.Sprintf("Found %d pending requests", len(friendRequests)))
// Loop over friend requests
reporter.Status("2/2: Purge abandoned friend requests")
var purged int
for _, request := range friendRequests {
// Get source user
var sourceUser db.User
err = tx.Where("uuid = ?", request.Source).First(&sourceUser).Error
// If error, assume user doesn't exist anymore
if err != nil {
reporter.Status("Deleting abandoned friend request with source user " + request.Source)
purged += 1
err := tx.Model(&db.FriendRequest{}).Delete(&request).Error
if err != nil {
tx.Rollback()
reporter.Fail("Failed to delete friend request from the database: " + err.Error())
return
}
continue
}
reporter.Status(fmt.Sprintf("Purged %d abandoned requests", purged))
// Get target user
var targetUser db.User
err = tx.Where("uuid = ?", request.Source).First(&targetUser).Error
// If error, assume user doesn't exist anymore
if err != nil {
if err == gorm.ErrRecordNotFound {
reporter.Status("Deleting abandoned friend request with target user " + request.Target)
err := tx.Model(&db.FriendRequest{}).Delete(&request).Error
if err != nil {
tx.Rollback()
reporter.Fail("Failed to delete friend request from the database: " + err.Error())
return
}
continue
}
}
}
// Commit the transaction if everything is successful
err = tx.Commit().Error
if err != nil {
tx.Rollback()
reporter.Fail("Failed to commit transaction: " + err.Error())
return
}
// Finish job
reporter.Finish()
}

View file

@ -0,0 +1,63 @@
package workers
import (
"fmt"
"gorm.io/gorm"
db "git.zervo.org/scheduletogether/scheduletogetherbackend/internal/database"
)
func workerSchedules_PurgeAbandonedData() {
reporter := NewReporter("Schedules", "PurgeAbandonedData")
// Start a transaction
tx := db.Db.Begin()
// Get all schedule entries
reporter.Status("1/2: Get all schedule entries")
var schedules []db.Schedule
err := tx.Model(&db.Schedule{}).Find(&schedules).Error
if err != nil {
tx.Rollback()
reporter.Fail("Failed to retrieve schedule entries from the database: " + err.Error())
return
}
reporter.Status(fmt.Sprintf("Found %d schedule entries", len(schedules)))
// Loop over schedule entries
reporter.Status("2/2: Purge abandoned schedule entries")
var purged int
for _, schedule := range schedules {
// Get source user
var sourceUser db.User
err = tx.Where("uuid = ?", schedule.Uuid).First(&sourceUser).Error
// If error, check if error is user not found
if err != nil {
if err == gorm.ErrRecordNotFound { // If error is "not found", delete schedule data entry
reporter.Status("Deleting abandoned schedule data for source user " + sourceUser.Username + " (" + schedule.Uuid + ")")
purged += 1
err := tx.Model(&db.Schedule{}).Delete(&schedule).Error
if err != nil {
tx.Rollback()
reporter.Fail("Failed to delete schedule data from the database: " + err.Error())
return
}
continue
}
}
reporter.Status(fmt.Sprintf("Purged %d abandoned schedule entries", purged))
}
// Commit the transaction if everything is successful
err = tx.Commit().Error
if err != nil {
tx.Rollback()
reporter.Fail("Failed to commit transaction: " + err.Error())
return
}
// Finish job
reporter.Finish()
}

84
pkg/helpers/config/config.go Executable file
View file

@ -0,0 +1,84 @@
/*
ScheduleTogether Backend
Copyright (C) 2024, Zervó Zadachin
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation.
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 version 3 for more details.
This program incorporates external libraries for certain functionalities.
These libraries are covered by their respective licenses, and their usage
agreements are as outlined in their respective documentation or source
code.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package config
import (
"fmt"
"os"
"strconv"
"git.zervo.org/scheduletogether/scheduletogetherbackend/pkg/types"
)
// Required environment variables
var requiredEnvVars = []string{
"DATABASE_URL",
"DATABASE_DIALECT",
"JWT_SECRET",
// Add other required environment variables here
}
// LoadConfig reads configuration values from environment variables
func LoadConfig() (*types.Config, error) {
// Check if all required environment variables are set
for _, envVar := range requiredEnvVars {
if os.Getenv(envVar) == "" {
return nil, fmt.Errorf("required environment variable %s is not set", envVar)
}
}
// Load configuration values
cfg := &types.Config{
ServerPort: getEnvInt("SERVER_PORT", 8080),
DatabaseDialect: os.Getenv("DATABASE_DIALECT"),
DatabaseURL: os.Getenv("DATABASE_URL"),
DatabaseDebug: getEnvBool("DATABASE_DEBUG", false),
JWTSecret: os.Getenv("JWT_SECRET"),
JWTExpiration: getEnvInt("JWT_EXPIRATION", 15),
}
// Return config object
return cfg, nil
}
// getEnvInt returns an int from an environment variable, or a default value if it is not set or invalid
func getEnvInt(key string, def int) int {
if v := os.Getenv(key); v != "" {
if i, err := strconv.Atoi(v); err == nil {
return i
}
}
return def
}
// getEnvBool returns a bool from an environment variable, or a default value if it is not set or invalid
func getEnvBool(key string, def bool) bool {
if v := os.Getenv(key); v != "" {
if b, err := strconv.ParseBool(v); err == nil {
return b
}
}
return def
}

View file

@ -0,0 +1,74 @@
/*
ScheduleTogether Backend
Copyright (C) 2024, Zervó Zadachin
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation.
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 version 3 for more details.
This program incorporates external libraries for certain functionalities.
These libraries are covered by their respective licenses, and their usage
agreements are as outlined in their respective documentation or source
code.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package cryptography
import (
"crypto/rand"
"golang.org/x/crypto/bcrypt"
"git.zervo.org/scheduletogether/scheduletogetherbackend/pkg/helpers/config"
"git.zervo.org/scheduletogether/scheduletogetherbackend/pkg/helpers/logging"
)
var logboi = logging.NewLogger("crypto")
var lettersAndNumbers = []byte("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
// HashString hashes a string
func HashString(raw string) (string, error) {
hashed, err := bcrypt.GenerateFromPassword([]byte(raw), bcrypt.DefaultCost) // replace with safer seed?
if err != nil {
return "", err
}
return string(hashed), nil
}
// GenerateToken generates a random token of the specified length.
func GenerateToken(length int) (string, error) {
bytes := make([]byte, length)
_, err := rand.Read(bytes)
if err != nil {
return "", err
}
for k, v := range bytes {
bytes[k] = lettersAndNumbers[v%byte(len(lettersAndNumbers))]
}
return string(bytes), nil
}
func GetJwtSecret() string {
// Load configuration
cfg, err := config.LoadConfig()
if err != nil {
logboi.Fatal(err.Error())
}
// Get JWT Secret
secret := cfg.JWTSecret
return secret
}

84
pkg/helpers/logging/logging.go Executable file
View file

@ -0,0 +1,84 @@
/*
ScheduleTogether Backend
Copyright (C) 2024, Zervó Zadachin
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation.
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 version 3 for more details.
This program incorporates external libraries for certain functionalities.
These libraries are covered by their respective licenses, and their usage
agreements are as outlined in their respective documentation or source
code.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package logging
import (
"fmt"
"os"
"time"
)
type Logger struct {
moduleName string
}
// NewLogger creates a new Logger instance
func NewLogger(moduleName string) *Logger {
return &Logger{moduleName: moduleName}
}
// Log logs a raw message with specified color coding
func (l *Logger) logRaw(prefix string, msg string, color string) {
now := time.Now().Format("2006-01-02 15:04:05") // Format for date and time (seconds)
fmt.Printf("%s[\033[1m%s\033[0m] %s <%s> %s"+Reset+Newline, color, prefix, now, l.moduleName, msg)
}
// wraps logRaw for general information logs
func (l *Logger) Info(msg string) {
l.logRaw("INFO", msg, White)
}
// wraps logRaw for warning logs
func (l *Logger) Warn(msg string) {
l.logRaw("WARN", msg, Yellow)
}
// wraps logRaw for error logs
func (l *Logger) Err(msg string) {
l.logRaw("ERRO", msg, Red)
}
// wraps logRaw for error logs
func (l *Logger) Fatal(msg string) {
l.logRaw("FATAL", msg, Red)
os.Exit(1)
}
// ANSI color codes
const (
Reset string = "\033[0m"
Bold string = "\033[1m"
Underline string = "\033[4m"
Newline string = "\n"
Black string = "\033[30m"
Red string = "\033[31m"
Green string = "\033[32m"
Yellow string = "\033[33m"
Blue string = "\033[34m"
Magenta string = "\033[35m"
Cyan string = "\033[36m"
White string = "\033[37m"
)

37
pkg/helpers/request/jwt.go Executable file
View file

@ -0,0 +1,37 @@
/*
ScheduleTogether Backend
Copyright (C) 2024, Zervó Zadachin
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation.
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 version 3 for more details.
This program incorporates external libraries for certain functionalities.
These libraries are covered by their respective licenses, and their usage
agreements are as outlined in their respective documentation or source
code.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package request
import (
"github.com/kataras/iris/v12"
"github.com/kataras/iris/v12/middleware/jwt"
"git.zervo.org/scheduletogether/scheduletogetherbackend/pkg/types"
)
func GetUserClaims(ctx iris.Context) *types.Claims {
claims := jwt.Get(ctx).(*types.Claims)
return claims
}

View file

@ -0,0 +1,48 @@
/*
ScheduleTogether Backend
Copyright (C) 2024, Zervó Zadachin
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation.
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 version 3 for more details.
This program incorporates external libraries for certain functionalities.
These libraries are covered by their respective licenses, and their usage
agreements are as outlined in their respective documentation or source
code.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package validation
import (
"fmt"
"regexp"
)
// ValidateEmail checks if the provided email address is valid
func ValidateEmail(email string) error {
// regex from https://golangcode.com/validate-email-address/
emailRegex := `^[a-zA-Z0-9.!#$%&'*+/=?^_` + "`" + `{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$`
// compile the regex
emailRegexCompiled, err := regexp.Compile(emailRegex)
if err != nil {
return err
}
if !emailRegexCompiled.MatchString(email) {
return fmt.Errorf("provided email address is not valid")
}
return nil
}

109
pkg/permissions/core.go Executable file
View file

@ -0,0 +1,109 @@
package permissions
import (
"git.zervo.org/scheduletogether/scheduletogetherbackend/pkg/types"
)
const (
SignOut types.PermissionKey = iota
GetAllUsers
GetUserById
GetUserByUuid
GetOwnUser
DeleteUserById
DeleteOwnUser
UpdateUserById
UpdateOwnUser
SendFriendRequest
AcceptFriendRequest
GetOwnFriendRequests
GetFriendRequestsById
OverrideInteractionPreferences
)
var Permissions = map[types.PermissionKey]types.Permission{
SignOut: {
Key: "sign_out",
Name: "Sign Out",
Description: "Allows user to manually sign out",
Roles: []string{"admin", "user", "member"},
},
GetAllUsers: {
Key: "get_all_users",
Name: "Get All Users",
Description: "Allows retrieving all instance users",
Roles: []string{"admin"},
},
GetUserById: {
Key: "get_user_by_id",
Name: "Get User By ID",
Description: "Allows retrieving specific user by ID",
Roles: []string{"admin"},
},
GetUserByUuid: {
Key: "get_user_by_uuid",
Name: "Get User By UUID",
Description: "Allows retrieving simple specific user data by UUID",
Roles: []string{"admin", "user", "member"},
},
GetOwnUser: {
Key: "get_own_user",
Name: "Get Own User",
Description: "Allows retrieving own user by payload data",
Roles: []string{"admin", "user", "member"},
},
DeleteUserById: {
Key: "delete_user_by_id",
Name: "Delete User By ID",
Description: "Allows deleting specific user by ID",
Roles: []string{"admin"},
},
DeleteOwnUser: {
Key: "delete_own_user",
Name: "Delete Own User",
Description: "Allows deleting own user by payload data",
Roles: []string{"user", "member"},
},
UpdateUserById: {
Key: "update_user_by_id",
Name: "Update User By ID",
Description: "Allows updating specific user by ID",
Roles: []string{"admin"},
},
UpdateOwnUser: {
Key: "update_own_user",
Name: "Update Own User",
Description: "Allows updating own user by payload data",
Roles: []string{"admin", "user", "member"},
},
SendFriendRequest: {
Key: "send_friend_request",
Name: "Send Friend Request",
Description: "Allows user to send friend requests",
Roles: []string{"admin", "user", "member"},
},
AcceptFriendRequest: {
Key: "accept_friend_request",
Name: "Accept Friend Request",
Description: "Allows user to accept incoming friend requests",
Roles: []string{"admin", "user", "member"},
},
GetOwnFriendRequests: {
Key: "get_own_friend_requests",
Name: "Get Own Friend Requests",
Description: "Allows user to list their incoming friend requests",
Roles: []string{"admin", "user", "member"},
},
GetFriendRequestsById: {
Key: "get_friend_requests_by_id",
Name: "Get Friend Requests By ID",
Description: "Allows user to list others incoming friend requests",
Roles: []string{"admin"},
},
OverrideInteractionPreferences: {
Key: "override_interaction_preferences",
Name: "Override Interaction Preferences",
Description: "Allows user to interact with other users no matter their interaction preferences",
Roles: []string{"admin"},
},
}

64
pkg/types/core.go Executable file
View file

@ -0,0 +1,64 @@
/*
ScheduleTogether Backend
Copyright (C) 2024, Zervó Zadachin
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation.
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 version 3 for more details.
This program incorporates external libraries for certain functionalities.
These libraries are covered by their respective licenses, and their usage
agreements are as outlined in their respective documentation or source
code.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package types
import "github.com/kataras/iris/v12/middleware/jwt"
// Config holds configuration values for the application read from environment variables
type Config struct {
ServerPort int `json:"serverPort"`
DatabaseURL string `json:"databaseURL"`
DatabaseDialect string `json:"databaseDialect"`
DatabaseDebug bool `json:"databaseDebug"`
JWTSecret string `json:"jwtSecret"`
JWTExpiration int `json:"jwtExpiration"`
}
type Role string
type Claims struct {
jwt.Claims // Embedding the jwt.Claims standard properties
UserId uint `json:"user_id"`
Role string `json:"role"`
Username string `json:"username"`
Email string `json:"email"`
Token string `json:"token"`
}
type PermissionKey int
type Permission struct {
Key string `json:"key"`
Name string `json:"name"`
Description string `json:"description"`
Roles []string `json:"roles"`
}
type FriendRequest struct {
CreatedAt string `json:"created_at"`
SourceUsername string `json:"source_username"`
SourceUuid string `json:"source_uuid"`
TargetUuid string `json:"target_uuid"`
}

51
pkg/types/requests.go Executable file
View file

@ -0,0 +1,51 @@
/*
ScheduleTogether Backend
Copyright (C) 2024, Zervó Zadachin
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation.
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 version 3 for more details.
This program incorporates external libraries for certain functionalities.
These libraries are covered by their respective licenses, and their usage
agreements are as outlined in their respective documentation or source
code.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package types
type AccountRegisterRequest struct {
FirstName string `json:"firstName"`
LastName string `json:"lastName"`
Username string `json:"username"`
Email string `json:"email"`
Password string `json:"password"`
}
type AccountLoginRequest struct {
Username string `json:"username"`
Password string `json:"password"`
}
type AccountVerifyRequest struct {
Uuid string `json:"uuid"`
Token string `json:"token"`
}
type FriendsAddRequest struct {
Username string `json:"username"`
}
type FriendsAcceptRequest struct {
Uuid string `json:"uuid"`
}

63
pkg/types/responses.go Executable file
View file

@ -0,0 +1,63 @@
/*
ScheduleTogether Backend
Copyright (C) 2024, Zervó Zadachin
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation.
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 version 3 for more details.
This program incorporates external libraries for certain functionalities.
These libraries are covered by their respective licenses, and their usage
agreements are as outlined in their respective documentation or source
code.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package types
type CommonMessageResponse struct {
Message string `json:"message"`
}
type CommonErrorResponse struct {
Error string `json:"error"`
}
type PingResponse struct {
Message string `json:"message"`
Time string `json:"time"`
Ok bool `json:"ok"`
}
type AccountRegisterResponse struct {
Message string `json:"message"`
Uuid string `json:"uuid"`
MustVerify bool `json:"mustVerify"`
}
type AccountSigninResponse struct {
Token string `json:"token"`
}
type UserRegisterFieldValidationErrorResponse struct {
ValidationFailed bool `json:"validationFailed"`
FirstName string `json:"firstName"`
LastName string `json:"lastName"`
Username string `json:"username"`
Email string `json:"email"`
Password string `json:"password"`
}
type FriendsGetRequestsResponse struct {
Amount int `json:"amount"`
Requests []FriendRequest `json:"requests"`
}