Compare commits

..

No commits in common. "master" and "legacy" have entirely different histories.

91 changed files with 6263 additions and 8959 deletions

View file

@ -3,10 +3,7 @@
# Server files
/server/target
**/target
# Client files
/client/node_modules
/client/dist
**/node_modules
**/dist

3
.gitignore vendored
View file

@ -22,6 +22,3 @@ dist-ssr
*.njsproj
*.sln
*.sw?
*.env
*.db*

View file

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

View file

@ -7,7 +7,8 @@ A simple forum written in Rust and Typescript.
## Structure
- `server`: Contains the web server code
- `client-solid`: Contains the frontend client written in SolidJS
- `client`: Contains the frontend client
- `client-solid`: Contains the frontend client written in SolidJS (WIP)
## Setup

View file

@ -1,27 +0,0 @@
/* eslint-env node */
module.exports = {
extends: [
"eslint:recommended",
"plugin:@typescript-eslint/recommended",
"plugin:solid/typescript",
"plugin:prettier/recommended",
"plugin:import/recommended",
"plugin:import/typescript",
],
parser: "@typescript-eslint/parser",
plugins: ["@typescript-eslint", "solid", "prettier", "import"],
root: true,
settings: {
"import/resolver": {
typescript: {
project: "./tsconfig.json",
},
},
},
rules: {
"@typescript-eslint/explicit-function-return-type": "error",
"no-duplicate-imports": ["error", { includeExports: true }],
"import/no-unresolved": "error",
"import/no-named-as-default-member": "off",
},
};

View file

@ -1,18 +0,0 @@
{
"plugins": [
"@trivago/prettier-plugin-sort-imports",
"prettier-plugin-tailwindcss"
],
"trailingComma": "es5",
"tabWidth": 2,
"semi": true,
"singleQuote": false,
"bracketSameLine": false,
"importOrder": [
"<THIRD_PARTY_MODULES>",
"^(@api|@assets|@ui)(/.*)$",
"^[.]"
],
"importOrderSeparation": true,
"importOrderSortSpecifiers": true
}

View file

@ -1,18 +1,15 @@
<!doctype html>
<html lang="en">
<html lang="en" data-theme="dracula">
<head>
<meta charset="UTF-8" />
<meta name="darkreader-lock">
<link rel="shortcut icon"
href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' class='MuiSvgIcon-root MuiSvgIcon-fontSizeLarge css-1756clo' focusable='false' aria-hidden='true' viewBox='0 0 24 24' data-testid='AcUnitIcon'%3E%3Cpath d='M22 11h-4.17l3.24-3.24-1.41-1.42L15 11h-2V9l4.66-4.66-1.42-1.41L13 6.17V2h-2v4.17L7.76 2.93 6.34 4.34 11 9v2H9L4.34 6.34 2.93 7.76 6.17 11H2v2h4.17l-3.24 3.24 1.41 1.42L9 13h2v2l-4.66 4.66 1.42 1.41L11 17.83V22h2v-4.17l3.24 3.24 1.42-1.41L13 15v-2h2l4.66 4.66 1.41-1.42L17.83 13H22z'%3E%3C/path%3E%3C/svg%3E" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="description"
content="FrostByte is a platform where you can share your thoughts and ideas anonymously. It is a place where you can express yourself with a sense of freedom." />
<title>FrostByte - Share your thoughts and ideas anonymously</title>
<title>FrostByteSolid</title>
</head>
<body>
<body class="min-h-screen">
<div id="root"></div>
<script type="module" src="/src/index.tsx"></script>
</body>

File diff suppressed because it is too large Load diff

View file

@ -6,33 +6,20 @@
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"preview": "vite preview",
"format": "prettier --config .prettierrc '**/*.ts' '**/*.tsx' '**/*.js' '**/*.json' --write",
"fmt": "prettier --config .prettierrc 'src/**/*.ts' 'src/**/*.tsx' --write && npx eslint --fix 'src/**/*.ts' 'src/**/*.tsx'",
"lint": "eslint --ext .ts,.tsx src"
"preview": "vite preview"
},
"dependencies": {
"@solidjs/router": "^0.15.2",
"solid-js": "^1.9.3"
"@solidjs/router": "^0.8.3",
"solid-js": "^1.7.8"
},
"devDependencies": {
"@trivago/prettier-plugin-sort-imports": "^5.2.0",
"@typescript-eslint/eslint-plugin": "^8.18.2",
"@typescript-eslint/parser": "^8.18.2",
"autoprefixer": "^10.4.20",
"daisyui": "^4.12.22",
"eslint": "^9.17.0",
"eslint-config-prettier": "^9.1.0",
"eslint-import-resolver-typescript": "^3.7.0",
"eslint-plugin-import": "^2.31.0",
"eslint-plugin-prettier": "^5.2.1",
"eslint-plugin-solid": "^0.14.5",
"postcss": "^8.4.49",
"prettier": "^3.4.2",
"prettier-plugin-tailwindcss": "^0.6.9",
"tailwindcss": "^3.4.17",
"typescript": "^5.7.2",
"vite": "^6.0.6",
"vite-plugin-solid": "^2.11.0"
"autoprefixer": "^10.4.16",
"daisyui": "^3.9.3",
"postcss": "^8.4.31",
"tailwindcss": "^3.3.3",
"typescript": "^5.0.2",
"vite": "^4.4.5",
"vite-plugin-qrcode": "^0.2.2",
"vite-plugin-solid": "^2.7.0"
}
}

View file

@ -3,4 +3,4 @@ export default {
tailwindcss: {},
autoprefixer: {},
},
};
}

View file

@ -1,75 +0,0 @@
import { JSXElement, Show, createSignal, useContext } from "solid-js";
import { LoginContext, ModalContext } from "../Context/GlobalState";
import { AuthResponse, submitLogin } from "../Util/api";
export function LoginForm(): JSXElement {
const modal_ctx = useContext(ModalContext)!;
const login_ctx = useContext(LoginContext)!;
const [username, setUsername] = createSignal<string>("");
const [password, setPassword] = createSignal<string>("");
const [waiting, setWaiting] = createSignal(false);
const [error, setError] = createSignal(false);
async function loginFailed(): Promise<void> {
setError(true);
setWaiting(false);
setTimeout(() => {
setError(false);
}, 1000);
}
const clearFields = (): void => {
setUsername("");
setPassword("");
};
const success = (response: AuthResponse): void => {
setWaiting(false);
setError(false);
clearFields();
login_ctx.logIn(response.username, response.token);
modal_ctx.setOpen(false);
};
async function loginPress(e: Event): Promise<void> {
e.preventDefault();
setWaiting(true);
const data = await submitLogin(username(), password());
if (data) success(data as AuthResponse);
else loginFailed();
}
return (
<form class="form-control space-y-2">
<input
type="text"
placeholder="Username"
value={username()}
class="input input-bordered"
onChange={(e): void => {
setUsername(e.target.value);
}}
/>
<input
type="password"
placeholder="Password"
value={password()}
class="input input-bordered"
onChange={(e): void => {
setPassword(e.target.value);
}}
/>
<button
classList={{ "btn btn-primary": !error(), "btn btn-error": error() }}
onClick={loginPress}
>
<Show when={waiting()} fallback="Login">
Logging in...
</Show>
</button>
</form>
);
}

View file

@ -1,23 +0,0 @@
import { JSXElement, Show, useContext } from "solid-js";
import { LoginContext, ModalContext } from "../Context/GlobalState";
import { UserCircle } from "../Util/Icons";
export function LoginButton(): JSXElement {
const modal_ctx = useContext(ModalContext)!;
const login_ctx = useContext(LoginContext)!;
const clickHandler = (): void => {
if (login_ctx.loggedIn()) login_ctx.logOut();
else modal_ctx.setOpen(true);
};
return (
<div class="btn btn-ghost text-sm capitalize" onClick={clickHandler}>
<Show when={login_ctx.loggedIn()} fallback="Login">
{login_ctx.username()}
</Show>
<UserCircle />
</div>
);
}

View file

@ -1,36 +0,0 @@
import { A } from "@solidjs/router";
import { JSXElement, Show, useContext } from "solid-js";
import { LoginContext } from "../Context/GlobalState";
import { Home, Plus } from "../Util/Icons";
// Represents a single list item in the menu bar
export function MenuItem(props: {
href: string;
children: JSXElement;
}): JSXElement {
return (
<li>
<A class="justify-center" href={props.href} end>
{props.children}
</A>
</li>
);
}
// Represents the menu bar at the top of the page
export function Menu(): JSXElement {
const login_ctx = useContext(LoginContext)!;
return (
<Show when={login_ctx.loggedIn()}>
<ul class="menu space-y-2 rounded-box md:menu-horizontal md:space-x-2 md:space-y-0">
<MenuItem href="/">
<Home />
</MenuItem>
<MenuItem href="/new">
<Plus />
</MenuItem>
</ul>
</Show>
);
}

View file

@ -1,64 +0,0 @@
import { useNavigate } from "@solidjs/router";
import { JSXElement, Show, createSignal, onMount, useContext } from "solid-js";
import { LoginContext } from "../Context/GlobalState";
import { NewPost, createPost } from "../Util/api";
export function NewPostInputArea(): JSXElement {
const [content, setContent] = createSignal("");
const [waiting, setWaiting] = createSignal(false);
// We assumte this context is always available
const login_ctx = useContext(LoginContext)!;
const nav = useNavigate();
const sendPost = (): void => {
setWaiting(true);
const response = createPost({
content: content(),
token: login_ctx.token(),
} as NewPost);
if (response) {
response.then(() => {
setWaiting(false);
setContent("");
nav("/");
});
}
};
// Bail out if not logged in
onMount(() => {
if (!login_ctx.loggedIn()) nav("/");
});
return (
<Show
when={!waiting()}
fallback={<span class="loading loading-spinner loading-lg self-center" />}
>
<div class="flex w-full flex-col space-y-2">
<textarea
class="textarea textarea-bordered h-32"
placeholder="Speak your mind..."
maxLength={500}
onInput={(input): void => {
setContent(input.target.value);
}}
/>
<button
class={
"btn btn-primary btn-sm self-end" +
(content() == "" ? " btn-disabled" : "")
}
onClick={sendPost}
>
Submit
</button>
</div>
</Show>
);
}

View file

@ -1,45 +0,0 @@
import { useNavigate } from "@solidjs/router";
import { For, JSXElement, Show, createSignal } from "solid-js";
import { Arrow, loadSpinner } from "../Util/Icons";
import { Post, getPosts } from "../Util/api";
export function Posts(): JSXElement {
const [posts, setPosts] = createSignal([] as Post[]);
const [loading, setLoading] = createSignal(true);
getPosts().then((posts) => {
setPosts(posts);
setLoading(false);
});
return (
<Show when={!loading()} fallback={loadSpinner()}>
<For each={posts()}>
{(post): JSXElement => <PostSegment post={post} />}
</For>
</Show>
);
}
// This is the card container for a post
export function PostSegment(props: { post: Post }): JSXElement {
const nav = useNavigate();
return (
<div class="card compact w-full flex-grow border-b-2 border-b-base-300 bg-base-200 text-base-content transition-all hover:bg-base-300">
<div class="card-body">
<p class="break-words text-base-content md:px-6 md:pt-2">
{props.post?.content}
</p>
<div class="card-actions justify-end">
<button
onClick={(): void => nav("/post/" + props.post?.id)}
class="btn btn-xs"
>
<Arrow />
</button>
</div>
</div>
</div>
);
}

View file

@ -1,87 +0,0 @@
import { JSXElement, Show, createSignal, useContext } from "solid-js";
import { LoginContext, ModalContext } from "../Context/GlobalState";
import { AuthResponse, submitRegistration } from "../Util/api";
export function RegisterForm(): JSXElement {
const modal_ctx = useContext(ModalContext)!;
const login_ctx = useContext(LoginContext)!;
const [username, setUsername] = createSignal<string>("");
const [password, setPassword] = createSignal<string>("");
const [captcha, setCaptcha] = createSignal<string>("");
const [waiting, setWaiting] = createSignal(false);
const [error, setError] = createSignal(false);
async function loginFailed(): Promise<void> {
setError(true);
setWaiting(false);
setTimeout(() => {
setError(false);
}, 1000);
}
const clearFields = (): void => {
setUsername("");
setPassword("");
setCaptcha("");
};
const success = (response: AuthResponse): void => {
setWaiting(false);
setError(false);
clearFields();
login_ctx.logIn(response.username, response.token);
modal_ctx.setOpen(false);
};
async function regPress(e: Event): Promise<void> {
e.preventDefault();
setWaiting(true);
const data = await submitRegistration(username(), password(), captcha());
if (data) success(data as AuthResponse);
else loginFailed();
}
return (
<form class="form-control space-y-2">
<input
type="text"
placeholder="Username"
value={username()}
class="input input-bordered"
onChange={(e): void => {
setUsername(e.target.value);
}}
/>
<input
type="password"
placeholder="Password"
value={password()}
class="input input-bordered"
onChange={(e): void => {
setPassword(e.target.value);
}}
/>
<input
type="text"
placeholder="Captcha"
value={captcha()}
class="input input-bordered"
onChange={(e): void => {
setCaptcha(e.target.value);
}}
/>
<button
classList={{ "btn btn-primary": !error(), "btn btn-error": error() }}
onClick={regPress}
>
<Show when={waiting()} fallback="Register">
Registering...
</Show>
</button>
</form>
);
}

View file

@ -1,30 +0,0 @@
import { useParams } from "@solidjs/router";
import { For, JSXElement, Show, Suspense, createResource } from "solid-js";
import { loadSpinner } from "../Util/Icons";
import { getComments, getPost } from "../Util/api";
import { PostSegment } from "./Posts";
export function SinglePost(): JSXElement {
const params = useParams();
const [post] = createResource(params.postid, getPost);
const [comments] = createResource(params.postid, () =>
getComments(params.postid, 0, 10)
);
return (
<Suspense fallback={loadSpinner()}>
<Show when={post()}>
<PostSegment post={post()!} />
<For each={comments()!}>
{(comment) => (
// TODO: This should be a separate component
<div class="comment">
<p>{comment.content}</p>
</div>
)}
</For>
</Show>
</Suspense>
);
}

View file

@ -1,54 +0,0 @@
import { JSXElement } from "solid-js";
export function Footer(): JSXElement {
return (
<footer class="footer footer-center mt-auto rounded bg-base-200 p-10 text-base-content">
<nav class="grid grid-flow-col gap-4">
<a class="link-hover link">About us</a>
<a class="link-hover link">Contact</a>
</nav>
<nav>
<div class="grid grid-flow-col gap-4">
<a>
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
class="fill-current"
>
<path d="M24 4.557c-.883.392-1.832.656-2.828.775 1.017-.609 1.798-1.574 2.165-2.724-.951.564-2.005.974-3.127 1.195-.897-.957-2.178-1.555-3.594-1.555-3.179 0-5.515 2.966-4.797 6.045-4.091-.205-7.719-2.165-10.148-5.144-1.29 2.213-.669 5.108 1.523 6.574-.806-.026-1.566-.247-2.229-.616-.054 2.281 1.581 4.415 3.949 4.89-.693.188-1.452.232-2.224.084.626 1.956 2.444 3.379 4.6 3.419-2.07 1.623-4.678 2.348-7.29 2.04 2.179 1.397 4.768 2.212 7.548 2.212 9.142 0 14.307-7.721 13.995-14.646.962-.695 1.797-1.562 2.457-2.549z" />
</svg>
</a>
<a>
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
class="fill-current"
>
<path d="M19.615 3.184c-3.604-.246-11.631-.245-15.23 0-3.897.266-4.356 2.62-4.385 8.816.029 6.185.484 8.549 4.385 8.816 3.6.245 11.626.246 15.23 0 3.897-.266 4.356-2.62 4.385-8.816-.029-6.185-.484-8.549-4.385-8.816zm-10.615 12.816v-8l8 3.993-8 4.007z" />
</svg>
</a>
<a>
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
class="fill-current"
>
<path d="M9 8h-3v4h3v12h5v-12h3.642l.358-4h-4v-1.667c0-.955.192-1.333 1.115-1.333h2.885v-5h-3.808c-3.596 0-5.192 1.583-5.192 4.615v3.385z" />
</svg>
</a>
</div>
</nav>
<aside>
<p>
<b>{new Date().getFullYear()} FrostByte</b>
</p>
</aside>
</footer>
);
}

View file

@ -1,71 +0,0 @@
import { JSXElement, Show, onCleanup, splitProps, useContext } from "solid-js";
import { LoginForm } from "../Components/Login";
import { RegisterForm } from "../Components/Register";
import { ModalContext } from "../Context/GlobalState";
export function LoginModal(): JSXElement {
const modal_ctx = useContext(ModalContext)!;
const closeModal = (): void => {
modal_ctx.setOpen(false);
};
// Close the modal when the component is unmounted
onCleanup(() => {
modal_ctx.setOpen(false);
});
return (
<Show when={modal_ctx.isOpen()}>
<dialog class="modal modal-open">
<div class="modal-box p-4 md:p-6">
<form method="dialog">
<button
onClick={closeModal}
class="btn btn-circle btn-ghost btn-sm absolute right-2 top-2"
>
</button>
</form>
<h3 class="mb-2 text-lg font-bold">Welcome!</h3>
<div class="tabs tabs-lifted">
<input
type="radio"
name="login_tabs"
class="tab"
aria-label="Login"
checked
/>
<FormContainer>
<LoginForm />
</FormContainer>
<input
type="radio"
name="login_tabs"
class="tab"
aria-label="Register"
/>
<FormContainer>
<RegisterForm />
</FormContainer>
</div>
</div>
<form method="dialog" class="modal-backdrop">
<button onClick={closeModal}>close</button>
</form>
</dialog>
</Show>
);
}
// Local wrapper component for the login and register forms
function FormContainer(props: { children: JSXElement }): JSXElement {
const [local] = splitProps(props, ["children"]);
return (
<div class="tab-content rounded-box border-base-300 bg-base-100 p-2 md:p-10">
<span class="label-text">{local.children}</span>
</div>
);
}

View file

@ -1,25 +0,0 @@
import { A } from "@solidjs/router";
import { JSXElement } from "solid-js";
import { LoginButton } from "../Components/LoginButton";
import { Menu } from "../Components/Menu";
import { Flake } from "../Util/Icons";
export function Navbar(): JSXElement {
return (
<div class="max-w navbar max-w-3xl rounded-box text-neutral-content md:my-4">
<div class="flex-1">
<A href={"/"} class="btn btn-ghost text-xl normal-case">
<Flake />
<h1>FrostByte</h1>
</A>
</div>
<div class="flex">
<Menu />
</div>
<div class="flex flex-1 justify-end">
<LoginButton />
</div>
</div>
);
}

View file

@ -1,8 +0,0 @@
import { JSXElement } from "solid-js";
// MainContainer is the main container for the page.
export function PageContainer(props: { children: JSXElement }): JSXElement {
return (
<div class="flex min-h-screen flex-col items-center">{props.children}</div>
);
}

View file

@ -1,22 +0,0 @@
import { Route, Router } from "@solidjs/router";
import { JSXElement } from "solid-js";
import { NewPostInputArea } from "../Components/NewPost";
import { Posts } from "../Components/Posts";
import { SinglePost } from "../Components/SinglePost";
function NotFound(): JSXElement {
return <h1>404</h1>;
}
// Primary is the section of the page that holds the main content
export function Primary(): JSXElement {
return (
<Router>
<Route path="/" component={Posts} />
<Route path="/post/:postid" component={SinglePost} />
<Route path="/new" component={NewPostInputArea} />
<Route path="*" component={NotFound} />
</Router>
);
}

View file

@ -1,10 +0,0 @@
import { JSXElement } from "solid-js";
// PrimaryContainer is the main container for the content section of the page.
export function PrimaryContainer(props: { children: JSXElement }): JSXElement {
return (
<div class="mb-8 flex w-full flex-col items-center space-y-2 px-2 md:max-w-3xl">
{props.children}
</div>
);
}

View file

@ -1,37 +0,0 @@
import { JSXElement } from "solid-js";
import { GlobalStateProvider } from "../Context/GlobalState";
import { Footer } from "./Footer";
import { LoginModal } from "./LoginModal";
import { Navbar } from "./Navbar";
import { PageContainer } from "./PageContainer";
import { Primary } from "./Primary";
import { PrimaryContainer } from "./PrimaryContainer";
function Root(): JSXElement {
return (
<>
<GlobalStateProvider>
<FancyBackground />
<PageContainer>
<Navbar />
<LoginModal />
<PrimaryContainer>
<Primary />
</PrimaryContainer>
<Footer />
</PageContainer>
</GlobalStateProvider>
</>
);
}
function FancyBackground(): JSXElement {
return (
<div class="bg-container">
<div class="bg-fancy bg-cover bg-center" />
</div>
);
}
export default Root;

View file

@ -1,85 +0,0 @@
import {
Accessor,
JSXElement,
createContext,
createSignal,
onMount,
} from "solid-js";
// Representing the state of varoious modals.
// So far we only have one modal, but we can add more later
// by adding more fields to this interface, or maybe an enum
interface ModalContextType {
isOpen: Accessor<boolean>;
setOpen: (value: boolean) => void;
}
interface LoginContextType {
token: Accessor<string>;
setToken: (value: string) => void;
username: Accessor<string>;
setUsername: (value: string) => void;
loggedIn: () => boolean;
logOut: () => void;
logIn: (username: string, token: string) => void;
}
// It is unclear to me if this is the idiomatic way to do this in Solid
export const ModalContext = createContext<ModalContextType>();
export const LoginContext = createContext<LoginContextType>();
export function GlobalStateProvider(props: {
children: JSXElement;
}): JSXElement {
// All of these are passed into context providers
const [loginModalOpen, setLoginModalOpen] = createSignal(false);
const [token, setToken] = createSignal("");
const [username, setUsername] = createSignal("");
onMount(() => {
// This may not be the best place to do this.
localStorage.getItem("token") && setToken(localStorage.getItem("token")!);
localStorage.getItem("username") &&
setUsername(localStorage.getItem("username")!);
});
function loggedIn(): boolean {
return token() != "" && username() != "";
}
function logIn(username: string, token: string): void {
setUsername(username);
setToken(token);
localStorage.setItem("token", token);
localStorage.setItem("username", username);
}
function logOut(): void {
localStorage.removeItem("token");
localStorage.removeItem("username");
setToken("");
setUsername("");
}
return (
<>
<ModalContext.Provider
value={{ isOpen: loginModalOpen, setOpen: setLoginModalOpen }}
>
<LoginContext.Provider
value={{
token,
setToken,
username,
setUsername,
loggedIn,
logOut,
logIn,
}}
>
{props.children}
</LoginContext.Provider>
</ModalContext.Provider>
</>
);
}

144
client-solid/src/Root.tsx Normal file
View file

@ -0,0 +1,144 @@
import { createSignal } from "solid-js";
import { createContext } from "solid-js";
import { Route, Routes, A } from "@solidjs/router";
import { createPost, getPosts } from "./api";
import { Post, NewPost } from "./api";
export const TestContext = createContext("Test123");
function Root() {
return (
<>
<TestContext.Provider value="Test123">
<div class="flex flex-col items-center my-2">
<Navbar />
<div class="flex flex-col items-center md:w-96 space-y-2">
<Primary />
</div>
</div>
</TestContext.Provider>
</>
);
}
function Navbar() {
return (
<div class="navbar bg-base-100 max-w-3xl max-w flex justify-evenly">
<a class="btn btn-ghost normal-case text-xl">hello</a>
<Menu />
<A href="/login" class="btn btn-ghost normal-case text-sm">
Login
</A>
</div>
);
}
function Menu() {
return (
<ul class="menu menu-horizontal bg-base-200 rounded-box space-x-2 justify-end">
<li>
<A href="/" end>
Home
</A>
</li>
<li>
<A href="/new" end>
New
</A>
</li>
<li>
<A href="/boards" end>
Boards
</A>
</li>
<li>
<A href="/login" end>
Login
</A>
</li>
</ul>
);
}
function NewPostInputArea() {
const [content, setContent] = createSignal("");
return (
<div class="flex flex-col space-y-2">
<textarea
class="textarea textarea-bordered"
placeholder="Speak your mind..."
oninput={(input) => {
setContent(input.target.value);
}}
></textarea>
<button
class={
"btn btn-primary self-end btn-sm" +
(content() == "" ? " btn-disabled" : "")
}
onclick={() => {
if (content() == "") return;
createPost({ content: content(), token: "" } as NewPost);
}}
>
Submit
</button>
</div>
);
}
function Posts() {
const [posts, setPosts] = createSignal([] as Post[]);
const [loading, setLoading] = createSignal(true);
getPosts().then((posts) => {
setPosts(posts as any);
setLoading(false)
});
return (
<div class="flex flex-col space-y-2 w-full md:w-96">
{ loading() ? <span class="loading loading-spinner loading-lg self-center"></span> : <></> }
{posts().map((post) => {
if (post.content == "") return; // Filtering out empty posts, remove this later
return <PostSegment post={post}></PostSegment>;
})}
</div>
);
}
function PostSegment({ post }: { post: Post }) {
return (
<div class="card bg-base-200 shadow-lg compact text-base-content w-full">
<div class="card-body">
<p class="text-base-content">{post.content}</p>
{/* <p>{post.votes.up}</p>
<p>{post.votes.down}</p> */}
</div>
</div>
);
}
function Primary() {
return (
<Routes>
<Route path="/" element={<Posts />} />
<Route path="/new" element={<NewPostInputArea />} />
<Route path="/boards" element={<div>Boards</div>} />
<Route path="/login" element={<Login />} />
</Routes>
);
}
function Login() {
return (
<div>
Login
<input class="input input-bordered" type="text" />
</div>
);
}
export default Root;

View file

@ -1,173 +0,0 @@
import { JSXElement } from "solid-js";
export function Arrow(): JSXElement {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke-width="1.5"
stroke="currentColor"
class="h-6 w-6"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
d="M17.25 8.25L21 12m0 0l-3.75 3.75M21 12H3"
/>
</svg>
);
}
export function loadSpinner(): JSXElement {
return <span class="loading loading-spinner loading-lg self-center" />;
}
// Hamburger menu icon
export function Bars(): JSXElement {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke-width="1.5"
stroke="currentColor"
class="h-6 w-6"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
d="M3.75 6.75h16.5M3.75 12h16.5m-16.5 5.25h16.5"
/>
</svg>
);
}
export function UserCircle(): JSXElement {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke-width="1.5"
stroke="currentColor"
class="h-6 w-6"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
d="M17.982 18.725A7.488 7.488 0 0012 15.75a7.488 7.488 0 00-5.982 2.975m11.963 0a9 9 0 10-11.963 0m11.963 0A8.966 8.966 0 0112 21a8.966 8.966 0 01-5.982-2.275M15 9.75a3 3 0 11-6 0 3 3 0 016 0z"
/>
</svg>
);
}
export function Flake(): JSXElement {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
stroke-width="1"
stroke="currentColor"
viewBox="0 0 24 24"
class="h-8 w-8"
data-testid="AcUnitIcon"
>
<path d="M22 11h-4.17l3.24-3.24-1.41-1.42L15 11h-2V9l4.66-4.66-1.42-1.41L13 6.17V2h-2v4.17L7.76 2.93 6.34 4.34 11 9v2H9L4.34 6.34 2.93 7.76 6.17 11H2v2h4.17l-3.24 3.24 1.41 1.42L9 13h2v2l-4.66 4.66 1.42 1.41L11 17.83V22h2v-4.17l3.24 3.24 1.42-1.41L13 15v-2h2l4.66 4.66 1.41-1.42L17.83 13H22z" />
</svg>
);
}
export function Plus(): JSXElement {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke-width="1.5"
stroke="currentColor"
class="h-6 w-6"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
d="M12 4.5v15m7.5-7.5h-15"
/>
</svg>
);
}
export function Home(): JSXElement {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke-width="1.5"
stroke="currentColor"
class="h-6 w-6"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
d="M2.25 12l8.954-8.955c.44-.439 1.152-.439 1.591 0L21.75 12M4.5 9.75v10.125c0 .621.504 1.125 1.125 1.125H9.75v-4.875c0-.621.504-1.125 1.125-1.125h2.25c.621 0 1.125.504 1.125 1.125V21h4.125c.621 0 1.125-.504 1.125-1.125V9.75M8.25 21h8.25"
/>
</svg>
);
}
export function ThumbUp(): JSXElement {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke-width="1.5"
stroke="currentColor"
class="h-6 w-6"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
d="M6.633 10.5c.806 0 1.533-.446 2.031-1.08a9.041 9.041 0 012.861-2.4c.723-.384 1.35-.956 1.653-1.715a4.498 4.498 0 00.322-1.672V3a.75.75 0 01.75-.75A2.25 2.25 0 0116.5 4.5c0 1.152-.26 2.243-.723 3.218-.266.558.107 1.282.725 1.282h3.126c1.026 0 1.945.694 2.054 1.715.045.422.068.85.068 1.285a11.95 11.95 0 01-2.649 7.521c-.388.482-.987.729-1.605.729H13.48c-.483 0-.964-.078-1.423-.23l-3.114-1.04a4.501 4.501 0 00-1.423-.23H5.904M14.25 9h2.25M5.904 18.75c.083.205.173.405.27.602.197.4-.078.898-.523.898h-.908c-.889 0-1.713-.518-1.972-1.368a12 12 0 01-.521-3.507c0-1.553.295-3.036.831-4.398C3.387 10.203 4.167 9.75 5 9.75h1.053c.472 0 .745.556.5.96a8.958 8.958 0 00-1.302 4.665c0 1.194.232 2.333.654 3.375z"
/>
</svg>
);
}
export function ThumbDown(): JSXElement {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke-width="1.5"
stroke="currentColor"
class="h-6 w-6"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
d="M7.5 15h2.25m8.024-9.75c.011.05.028.1.052.148.591 1.2.924 2.55.924 3.977a8.96 8.96 0 01-.999 4.125m.023-8.25c-.076-.365.183-.75.575-.75h.908c.889 0 1.713.518 1.972 1.368.339 1.11.521 2.287.521 3.507 0 1.553-.295 3.036-.831 4.398C20.613 14.547 19.833 15 19 15h-1.053c-.472 0-.745-.556-.5-.96a8.95 8.95 0 00.303-.54m.023-8.25H16.48a4.5 4.5 0 01-1.423-.23l-3.114-1.04a4.5 4.5 0 00-1.423-.23H6.504c-.618 0-1.217.247-1.605.729A11.95 11.95 0 002.25 12c0 .434.023.863.068 1.285C2.427 14.306 3.346 15 4.372 15h3.126c.618 0 .991.724.725 1.282A7.471 7.471 0 007.5 19.5a2.25 2.25 0 002.25 2.25.75.75 0 00.75-.75v-.633c0-.573.11-1.14.322-1.672.304-.76.93-1.33 1.653-1.715a9.04 9.04 0 002.86-2.4c.498-.634 1.226-1.08 2.032-1.08h.384"
/>
</svg>
);
}
export function CheckMark(): JSXElement {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke-width="1.5"
stroke="currentColor"
class="h-6 w-6"
>
<path
stroke-linecape="round"
stroke-linejoin="round"
d="m4.5 12.75 6 6 9-13.5"
/>
</svg>
);
}

View file

@ -1,100 +0,0 @@
// This file contains types and functions related to interacting with the API.
export interface NewPost {
content: string;
token: string;
}
interface Votes {
up: number;
down: number;
}
export interface Post extends NewPost {
id: string;
createdAt: string;
votes: Votes;
}
// This is what the login and registration responses look like
export interface AuthResponse {
username: string;
token: string;
}
// This is what a public comment looks like, as it arrives from the server
export interface PublicComment {
id: number;
parent_post_id: number;
parent_comment_id: number | null;
upvotes: number;
downvotes: number;
content: string;
created_at: string;
updated_at: string;
}
export async function getPosts(): Promise<Post[]> {
const res = await fetch("/api/posts");
const data = await res.json();
return data;
}
export async function getPost(id: string): Promise<Post> {
const res = await fetch(`/api/posts/${id}`);
const data = await res.json();
return data;
}
export async function createPost(post: NewPost): Promise<void> {
await fetch("/api/posts", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(post),
});
}
// Gets the comments for a specific post
export async function getComments(
postId: string,
limit: number,
offset: number
): Promise<PublicComment[]> {
const res = await fetch(
`/api/comments?post_id=${postId}&limit=${limit}&offset=${offset}`
);
const data = await res.json();
return data;
}
// Send the registration request to the server
export async function submitRegistration(
username: string,
password: string,
captcha: string
): Promise<AuthResponse | undefined> {
const response = await fetch("/api/register", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username, password, captcha }),
});
if (response.ok) return await response.json();
}
// Send the login request to the server
export async function submitLogin(
username: string,
password: string
): Promise<AuthResponse | undefined> {
if (username == "" || password == "") return;
const response = await fetch("/api/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username, password }),
});
if (response.ok) return await response.json();
}

43
client-solid/src/api.ts Normal file
View file

@ -0,0 +1,43 @@
// const PORT = 3000;
// const API_URL = `http://localhost:${PORT}/api/`;
// const API_URL2 = new URL(API_URL);
export interface NewPost {
content: string;
token: string;
}
interface Votes {
up: number;
down: number;
}
export interface Post extends NewPost {
uuid: string;
createdAt: string;
votes: Votes;
}
export async function getPosts(): Promise<Post[]> {
// const res = await fetch(`${API_URL}/posts`);
const res = await fetch("/api/");
const data = await res.json();
return data;
}
export async function getPost(id: string): Promise<Post> {
const res = await fetch(`/api/${id}`);
const data = await res.json();
return data;
}
export async function createPost(post: NewPost): Promise<void> {
// await fetch(`${API_URL}`, {
await fetch("/api/", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(post),
});
}

View file

@ -1,27 +1,3 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
.bg-container {
z-index: -1;
position: fixed;
overflow: hidden;
height: 100%;
width: 100%;
}
.bg-fancy {
position: absolute;
left: -40rem;
height: 200vh;
width: 200vw;
opacity: 0.02;
background-image:
linear-gradient(#ffffff 2px, transparent 2px),
linear-gradient(90deg, #ffffff 2px, transparent 2px),
linear-gradient(#ffffff 1px, transparent 1px),
linear-gradient(90deg, #ffffff 1px, transparent 1px);
background-size: 200px 200px, 200px 200px, 40px 40px, 40px 40px;
background-position: -8px -8px, -8px -8px, -4px -4px, -4px -4px;
transform: matrix(1.5, 0.2, -1, 1.2, 0, 0);
}
@tailwind utilities;

View file

@ -1,9 +1,18 @@
import { Router } from "@solidjs/router";
/* @refresh reload */
import { render } from "solid-js/web";
import Root from "./Containers/Root";
import "./index.css";
import Root from "./Root";
import { Router } from "@solidjs/router";
const root = document.getElementById("root");
render(() => <Router root={Root} />, root!);
render(
() => (
<Router>
<Root />
</Router>
),
root!
);

View file

@ -1,27 +1,31 @@
/** @type {import('tailwindcss').Config} */
export default {
content: ["./index.html", "./src/**/*.{js,ts,jsx,tsx}"],
content: [
"./index.html",
"./src/**/*.{js,ts,jsx,tsx}",
],
daisyui: {
themes: [
{
mytheme: {
primary: "#64279e",
secondary: "#9454af",
accent: "#6ff7c5",
neutral: "#1f2329",
"base-100": "#2a3a47",
info: "#8b9be5",
success: "#79e2b4",
warning: "#efb261",
error: "#e1604c",
"primary": "#86e8d9",
"secondary": "#b5385d",
"accent": "#88ed5a",
"neutral": "#14171f",
"base-100": "#343154",
"info": "#9bc3e9",
"success": "#1f9363",
"warning": "#f2ce4a",
"error": "#e77d6a",
},
},
],
},
theme: {
extend: {},
},
// eslint-disable-next-line no-undef
plugins: [require("daisyui")],
};
}

View file

@ -3,7 +3,11 @@
"target": "ES2020",
"useDefineForClassFields": true,
"module": "ESNext",
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"lib": [
"ES2020",
"DOM",
"DOM.Iterable"
],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
@ -19,10 +23,12 @@
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src"],
"include": [
"src"
],
"references": [
{
"path": "./tsconfig.node.json"
}
]
}
}

View file

@ -1,22 +1,23 @@
import { defineConfig } from "vite";
import solid from "vite-plugin-solid";
import { defineConfig } from 'vite'
import solid from 'vite-plugin-solid'
import { qrcode } from 'vite-plugin-qrcode'
// https://vitejs.dev/config/
export default defineConfig({
// build: {
// outDir: '../server/public' // Override default outDir('dist')
// },
plugins: [solid()],
plugins: [solid(), qrcode()],
server: {
port: 3000,
open: true,
proxy: {
"/api": {
target: "http://localhost:8080/api",
'/api': {
target: 'http://localhost:8080/api',
changeOrigin: true,
secure: false,
rewrite: (path): string => path.replace(/^\/api/, ""),
},
},
},
});
rewrite: (path): string => path.replace(/^\/api/, '')
}
}
}
})

19
client/.eslintrc.cjs Normal file
View file

@ -0,0 +1,19 @@
module.exports = {
root: true,
env: { browser: true, es2020: true },
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'plugin:react-hooks/recommended',
],
ignorePatterns: ['dist', '.eslintrc.cjs'],
parser: '@typescript-eslint/parser',
plugins: ['react-refresh'],
rules: {
'react-refresh/only-export-components': [
'warn',
{ allowConstantExport: true },
],
"@typescript-eslint/explicit-function-return-type": ["error", { "allowTypedFunctionExpressions": false }],
},
}

18
client/index.html Normal file
View file

@ -0,0 +1,18 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<!-- <link rel="icon" type="image/svg+xml" href="/vite.svg" /> -->
<link rel="shortcut icon"
href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' class='MuiSvgIcon-root MuiSvgIcon-fontSizeLarge css-1756clo' focusable='false' aria-hidden='true' viewBox='0 0 24 24' data-testid='AcUnitIcon'%3E%3Cpath d='M22 11h-4.17l3.24-3.24-1.41-1.42L15 11h-2V9l4.66-4.66-1.42-1.41L13 6.17V2h-2v4.17L7.76 2.93 6.34 4.34 11 9v2H9L4.34 6.34 2.93 7.76 6.17 11H2v2h4.17l-3.24 3.24 1.41 1.42L9 13h2v2l-4.66 4.66 1.42 1.41L11 17.83V22h2v-4.17l3.24 3.24 1.42-1.41L13 15v-2h2l4.66 4.66 1.41-1.42L17.83 13H22z'%3E%3C/path%3E%3C/svg%3E" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>FrostByte</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

3448
client/package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

35
client/package.json Normal file
View file

@ -0,0 +1,35 @@
{
"name": "mui-practice",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite --host",
"build": "tsc && vite build",
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
"preview": "vite preview",
"clean": "rm -r node_modules"
},
"dependencies": {
"@emotion/react": "^11.11.1",
"@emotion/styled": "^11.11.0",
"@mui/icons-material": "^5.14.11",
"@mui/material": "^5.14.11",
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"@types/react": "^18.2.15",
"@types/react-dom": "^18.2.7",
"@typescript-eslint/eslint-plugin": "^6.0.0",
"@typescript-eslint/parser": "^6.0.0",
"@vitejs/plugin-react-swc": "^3.3.2",
"eslint": "^8.45.0",
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-react-refresh": "^0.4.3",
"sass": "^1.68.0",
"typescript": "^5.0.2",
"vite": "^4.4.5",
"vite-plugin-qrcode": "^0.2.2"
}
}

41
client/src/App.tsx Normal file
View file

@ -0,0 +1,41 @@
import Box from '@mui/material/Box'
import { useState } from 'react'
import Header from './Header.tsx'
import Primary from './Primary.tsx';
import Footer from './Footer.tsx';
import LoginDialog from './LoginDialog.tsx';
import { LoginContext } from './Context.tsx';
// JSX.Element is the return type of every React component
function App(): JSX.Element {
const [loginModalOpen, setLoginModalOpen] = useState(false);
const [currentUser, setCurrentUser] = useState<string | undefined>(undefined);
const [userToken, setUserToken] = useState<string | undefined>(undefined);
const loginContextData = {
loginModalOpen: loginModalOpen,
currentUser: currentUser,
userToken: userToken,
setOpen: setLoginModalOpen,
setCurrentUser: setCurrentUser,
setUserToken: setUserToken,
};
// const loginContextData = { open, setOpen };
// const loginContext = createContext(loginContextData);
return (
<LoginContext.Provider value={loginContextData} >
<Box flexDirection={"column"} display={"flex"} sx={{ width: "100%", minHeight: "100vh", backgroundColor:"background.default"}}>
<Header />
<LoginDialog />
<Primary />
<Footer />
</Box>
</LoginContext.Provider>
)
}
export default App;

23
client/src/Context.tsx Normal file
View file

@ -0,0 +1,23 @@
import { createContext } from "react"
export const TestContext = createContext("Test123")
interface LoginCTX {
loginModalOpen: boolean;
currentUser?: string;
userToken?: string;
setOpen?: (open: boolean) => void;
setCurrentUser?: (username: string) => void;
setUserToken?: (token: string) => void;
}
const loginContextData = {
loginModalOpen: false,
currentUser: undefined,
userToken: undefined,
setOpen: undefined,
setCurrentUser: undefined,
setUserToken: undefined,
};
export const LoginContext = createContext<LoginCTX>(loginContextData);

36
client/src/Footer.tsx Normal file
View file

@ -0,0 +1,36 @@
// import React from "react";
import Typography from "@mui/material/Typography";
import Container from "@mui/material/Container";
import Box from "@mui/material/Box";
import { Grid } from "@mui/material";
function Footer(): JSX.Element {
return (
<Box sx={{
flexGrow: "1",
display: "flex",
flexDirection: "column",
backgroundColor: "#242424",
// backgroundColor: "background.paper",
color: "text.secondary"
}}>
<Grid container sx={{ mt: 6, maxWidth: "1000px", width: "100%", mx: "auto" }}>
<Container sx={{textAlign: "center"}}>
<Typography color="text.secondary" gutterBottom sx={{userSelect: "none",opacity:"40%"}}>
Δ DeltaLabs {new Date().getFullYear()}
</Typography>
</Container>
{/* { ["Tasteful", "Looking", "Footer"].map((letter): JSX.Element => {
return (
<Grid key={letter} item xs={12} sm={6} md={4} lg={4} sx={{textAlign: "center"}}>
<Typography>{letter}</Typography>
</Grid>
)
}) } */}
</Grid>
</Box>
)
}
export default Footer;

172
client/src/Header.tsx Normal file
View file

@ -0,0 +1,172 @@
import {
AppBar,
Button,
ButtonGroup,
Grid,
Link,
Typography,
} from "@mui/material";
import Box from "@mui/material/Box";
import AcUnitIcon from "@mui/icons-material/AcUnit";
import { cyan } from "@mui/material/colors";
import { useContext } from "react";
import { LoginContext } from "./Context";
import AccountCircleIcon from "@mui/icons-material/AccountCircle";
import HomeIcon from "@mui/icons-material/Home";
import PostAddIcon from "@mui/icons-material/PostAdd";
function LoginDisplay({ sx }: { sx?: React.CSSProperties }): JSX.Element {
const loginCtx = useContext(LoginContext);
const handleLogin = (): void => {
console.log("Login button pressed");
if (loginCtx.currentUser == undefined) {
loginCtx.setOpen?.(true); // If the loginCtx.setOpen is defined, call it with true as the argument
} else {
loginCtx.setCurrentUser?.("");
loginCtx.setUserToken?.("");
}
};
if (loginCtx.currentUser != undefined) {
return (
<Box sx={{ textAlign: "right", ...sx }}>
<Typography color={"#808080"} sx={{ textAlign: "right" }}>
Logged in as:
</Typography>
<Typography sx={{ textAlign: "right" }}>
<Link href="#" underline="hover" onClick={(): void => handleLogin()}>
{loginCtx.currentUser}
</Link>
</Typography>
</Box>
);
}
return (
<Box sx={{ textAlign: "right", ...sx }}>
<Button
variant="text"
startIcon={<AccountCircleIcon />}
onClick={(): void => handleLogin()}
>
Login
</Button>
</Box>
);
}
function Header({ sx }: { sx?: React.CSSProperties }): JSX.Element {
return (
<AppBar
position="static"
sx={{
p: 1,
px: 3,
display: "flex",
flexDirection: "row",
justifyContent: "space-evenly",
...sx,
}}
>
<Grid
container
px={2}
spacing={2}
sx={{
flexGrow: 1,
display: "flex",
maxWidth: "1200px",
flexDirection: "row",
alignItems: "center",
justifyContent: "space-between",
}}
>
<Grid item xs={12} sm={6} md={4} lg={4}>
<HeaderLogo clickable />
</Grid>
<Grid item xs={12} sm={6} md={4} lg={4}>
<NavButtons />
</Grid>
<Grid item xs={12} sm={6} md={4} lg={4}>
<LoginDisplay />
</Grid>
</Grid>
</AppBar>
);
}
function HeaderLogo({
clickable,
sx,
}: {
clickable?: boolean;
sx?: React.CSSProperties;
}): JSX.Element {
const clickStyle = {
transition: "0.3s all ease-in-out",
":hover": { textShadow: "0 0px 15px" + cyan[400] },
};
return (
<Box
sx={{
width: "fit-content",
// height: "fit-content",
// display: "flex",
// flexDirection: "row",
// alignItems: "center",
// justifyContent: "center",
userSelect: "none",
cursor: "pointer",
...(clickable ? clickStyle : {}),
...sx,
}}
>
<Typography
fontSize={"2rem"}
sx={{ display: "flex", flexDirection: "row", alignItems: "center" }}
>
<AcUnitIcon
fontSize="inherit"
sx={{ height: "100%", color: cyan[400], mr: 1, mb: 1.1 }}
></AcUnitIcon>
FrostByte
</Typography>
</Box>
);
}
function NavButtons({ sx }: { sx?: React.CSSProperties }): JSX.Element {
return (
<Box
sx={{
display: "flex",
flexDirection: "row",
maxWidth: "400px",
width: 1,
...sx,
}}
>
<ButtonGroup
variant="text"
aria-label="text button group"
sx={{ width: "100%" }}
>
{["Home", "New"].map((typename): JSX.Element => {
return (
<Button
startIcon={typename === "Home" ? <HomeIcon /> : <PostAddIcon />}
key={typename}
sx={{ px: 2, bgcolor: "#FFFFFF15", width: 1 }}
>
{typename}
</Button>
);
})}
</ButtonGroup>
</Box>
);
}
export default Header;

132
client/src/LoginDialog.tsx Normal file
View file

@ -0,0 +1,132 @@
import { Dialog } from "@mui/material";
import { DialogTitle } from "@mui/material";
import { DialogContent } from "@mui/material";
import { DialogContentText } from "@mui/material";
import { DialogActions } from "@mui/material";
import { Button } from "@mui/material";
import { TextField } from "@mui/material";
import { useEffect, useState } from "react";
import { useContext } from "react";
import { LoginContext } from "./Context";
// import { TestContext } from "./Context";
interface RegisterData {
username: string,
password: string,
captcha: string,
}
interface LoginData {
username: string,
password: string,
}
function sendRegister(data: RegisterData): void {
console.log(JSON.stringify(data));
fetch("/api/register", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data)
});
}
interface LoginResponse {
username: string,
token: string,
}
async function sendLogin(data: LoginData): Promise<LoginResponse> {
// console.log(JSON.stringify(data));
const response_promise = await fetch("/api/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data)
});
const logindata = await response_promise.json();
return (logindata as LoginResponse);
}
function LoginDialog(): JSX.Element {
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const loginCTX = useContext(LoginContext);
const setLoggedInAs = (username: string, token: string): void => {
loginCTX.setCurrentUser?.(username);
loginCTX.setUserToken?.(token);
handleClose();
}
// const setLogOut = (): void => {
// loginCTX.setCurrentUser?.(undefined);
// loginCTX.setUserToken?.(undefined);
// localStorage.removeItem("loginState");
// }
const handleClose = (): void => {
loginCTX.setOpen?.(false);
setUsername("");
setPassword("");
};
// Check for localStorage login state
useEffect((): void => {
const loginState = JSON.parse(localStorage.getItem("loginState")||"{}");
if (loginState.username && loginState.token) {
setLoggedInAs(loginState.username, loginState.token);
}
}, []);
const handleLogin = async (): Promise<void> => {
const response = await sendLogin({ username: username, password: password });
if (response && response.username && response.token) {
setLoggedInAs(response.username, response.token);
localStorage.setItem("loginState", JSON.stringify(response));
}
};
const handleRegister = (): void => {
sendRegister({ username: username, password: password, captcha: "test" });
}
return (
<Dialog open={loginCTX.loginModalOpen} onClose={handleClose} sx={{ p: 2, top: "-40%" }}>
<DialogTitle>Login</DialogTitle>
<DialogContent>
<DialogContentText>
Please enter your username and password.
</DialogContentText>
<TextField
autoFocus
margin="dense"
id="username"
label="Username"
type="text"
fullWidth
value={username}
onChange={(e): void => setUsername(e.target.value)}
/>
<TextField
margin="dense"
id="password"
label="Password"
type="password"
fullWidth
value={password}
onChange={(e): void => setPassword(e.target.value)}
/>
</DialogContent>
<DialogActions>
<Button onClick={handleLogin}>Login</Button>
</DialogActions>
<DialogActions>
<Button onClick={handleRegister}>Register</Button>
</DialogActions>
</Dialog>
);
}
export default LoginDialog;

100
client/src/Post.tsx Normal file
View file

@ -0,0 +1,100 @@
import { Card, CardActions, CardContent, IconButton, Typography } from "@mui/material";
import { ArrowDownward, ArrowUpward, Comment, Share } from "@mui/icons-material";
import { useState } from "react";
export interface Post {
uuid: string,
title: string,
content: string,
votes: { up: number, down: number },
}
// const URL = "http://localhost:8080/api/";
function sendVote(post: Post, direction: string): void {
fetch('/api/vote/' + post.uuid + '/' + direction, { method: 'POST' });
}
enum VoteDirection { UP = 1, DOWN = -1, NONE = 0 }
// // Single post
export function PostCard({ post }: { post: Post }): JSX.Element {
// const [myVote, setMyVote] = useState({ up: 0, down: 0 });
const [myVote, setMyVote] = useState(VoteDirection.NONE);
const [voteCount, setVoteCount] = useState({
upvotes: post.votes.up,
downvotes: post.votes.down
});
setVoteCount; // To silence the linter, peak coding right here
// Atrocious code
const votePress = (vote: VoteDirection): void => {
console.log(vote);
if (vote === VoteDirection.UP) {
if (myVote === VoteDirection.NONE) { // Upvote
sendVote(post, 'up');
setMyVote(VoteDirection.UP);
}
else if (myVote === VoteDirection.UP) { // Unvote
sendVote(post, 'unupvote');
setMyVote(VoteDirection.NONE);
}
else if (myVote === VoteDirection.DOWN) { // Change vote
sendVote(post, 'undownvote');
sendVote(post, 'up');
setMyVote(VoteDirection.UP);
}
}
if (vote === VoteDirection.DOWN) {
if (myVote === VoteDirection.NONE) { // Downvote
sendVote(post, 'down');
setMyVote(VoteDirection.DOWN);
}
else if (myVote === VoteDirection.DOWN) { // Unvote
sendVote(post, 'undownvote');
setMyVote(VoteDirection.NONE);
}
else if (myVote === VoteDirection.UP) { // Change vote
sendVote(post, 'unupvote');
sendVote(post, 'down');
setMyVote(VoteDirection.DOWN);
}
}
}
return (
<>
<Card key={post.uuid} sx={{ width: 1, bgcolor: "background.default" }}>
<CardContent>
<Typography variant="h6">
{post.title}
</Typography>
<Typography sx={{ overflowWrap: 'break-word' }} variant="body2">
{post.content ? post.content : "No content"}
</Typography>
</CardContent>
<CardActions>
<IconButton size='small' color='primary' aria-label="Comment"><Comment /></IconButton>
<IconButton color={myVote > 0 ? 'success' : 'default'}
onClick={(): void => votePress(VoteDirection.UP)} size='small' aria-label="Upvote"><ArrowUpward />
{voteCount.upvotes + Math.max(myVote, 0)}
</IconButton>
<IconButton color={myVote < 0 ? 'secondary' : 'default'}
onClick={(): void => votePress(VoteDirection.DOWN)} size='small' aria-label="Downvote"><ArrowDownward />
{voteCount.downvotes + Math.max(-myVote, 0)}
</IconButton>
<div style={{ marginLeft: 'auto' }}>
<IconButton size='small' aria-label="Share"><Share /></IconButton>
</div>
</CardActions>
</Card>
</>
)
}

88
client/src/Primary.tsx Normal file
View file

@ -0,0 +1,88 @@
import { Box, Container, Grid, Button, Paper, TextField, FormControl } from "@mui/material";
import { useEffect, useState } from "react";
import SendIcon from '@mui/icons-material/Send';
import CancelIcon from '@mui/icons-material/Cancel';
import { Post, PostCard } from "./Post";
function Primary(): JSX.Element {
const [posts, setPosts] = useState<Post[]>([]);
const refreshPosts = (): void => {
fetch("/api/").then((response): void => {
response.json().then((data): void => {
setPosts(data);
})
})
}
useEffect((): void => {
refreshPosts();
}, [])
return (
<Container sx={{ p: 2, display: "flex", flexDirection: "column", alignItems: "center", backgroundColor: "background.default", minHeight: "60vh" }}>
<PostInput newPostCallback={refreshPosts} />
<PostContainer posts={posts} />
</Container>
)
}
function PostContainer({ posts }: { posts: Post[] }): JSX.Element {
return (
<Grid container justifyContent={"center"} spacing={2} pb={2}>
{posts.map((p): JSX.Element => {
return (
<Grid item xs={12} sm={12} md={6} lg={6} xl={6} key={p.uuid}>
<PostCard key={p.uuid} post={p} />
</Grid>
)
})}
</Grid>
)
}
interface NewPost {
content: string,
token: string,
}
function PostInput({ newPostCallback }: { newPostCallback: () => void }): JSX.Element {
const [currentInput, setCurrentInput] = useState("");
const handleSubmit = (): void => {
if (currentInput) submitPostToServer();
}
const submitPostToServer = async (): Promise<void> => {
const newPost: NewPost = { content: currentInput, token: "" }
const response = await fetch("/api/", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(newPost)
})
const data = await response.json();
console.log(data);
newPostCallback();
setCurrentInput("");
}
return (
<Box py={2} display={"flex"} flexDirection={"column"} width={1}>
<Paper sx={{ p: 2, display: "flex", flexDirection: "column", alignContent: "center", alignItems: "center" }} elevation={4}>
<FormControl fullWidth>
{/* <TextField sx={{pb:1}} size="small" id="outlined-basic" label="Title" variant="outlined" value={title} fullWidth onChange={(a): void => setTitle(a.target.value)} /> */}
<TextField multiline id="outlined-basic" label="Share your thoughts" variant="outlined" minRows={4} value={currentInput} fullWidth onChange={(a): void => setCurrentInput(a.target.value)} />
<Container disableGutters sx={{ mt:1, display: "flex", flexDirection: "row", justifyContent: "flex-end", alignItems: "center", width: "100%" }}>
<Button sx={{mr:1}} type="reset" startIcon={<CancelIcon/>} variant="outlined" onClick={handleSubmit}>Cancel</Button>
<Button type="submit" startIcon={<SendIcon />} variant="contained" onClick={handleSubmit}>Send</Button>
</Container>
</FormControl>
</Paper>
</Box>
)
}
export default Primary;

24
client/src/Theme.tsx Normal file
View file

@ -0,0 +1,24 @@
import { createTheme } from "@mui/material";
const theme = createTheme({
palette: {
mode: "dark",
// primary: {
// main: "#ff0000",
// },
// secondary: {
// main: "#00ff00",
// },
},
typography: {
fontFamily: "Roboto, sans-serif",
// h1: {
// fontSize: "3.5rem",
// },
// h3: {
// fontSize: "2rem",
// },
},
});
export default theme;

22
client/src/main.tsx Normal file
View file

@ -0,0 +1,22 @@
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.tsx'
import './style/index.scss'
import theme from './Theme.tsx'
import { ThemeProvider } from '@mui/material'
import { CssBaseline } from '@mui/material'
import { TestContext } from './Context.tsx'
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<CssBaseline />
<ThemeProvider theme={theme}>
<TestContext.Provider value="Test123">
<App />
</TestContext.Provider>
</ThemeProvider>
<CssBaseline />
</React.StrictMode>,
)

View file

@ -0,0 +1 @@
// No free standing CSS

1
client/src/vite-env.d.ts vendored Normal file
View file

@ -0,0 +1 @@
// / <reference types="vite/client" />

25
client/tsconfig.json Normal file
View file

@ -0,0 +1,25 @@
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src"],
"references": [{ "path": "./tsconfig.node.json" }]
}

10
client/tsconfig.node.json Normal file
View file

@ -0,0 +1,10 @@
{
"compilerOptions": {
"composite": true,
"skipLibCheck": true,
"module": "ESNext",
"moduleResolution": "bundler",
"allowSyntheticDefaultImports": true
},
"include": ["vite.config.ts"]
}

23
client/vite.config.ts Normal file
View file

@ -0,0 +1,23 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react-swc'
import { qrcode } from 'vite-plugin-qrcode'
// https://vitejs.dev/config/
export default defineConfig({
build: {
// outDir: '../server/public' // Override default outDir('dist')
},
plugins: [react(), qrcode()],
server: {
port: 3000,
open: true,
proxy: {
'/api': {
target: 'http://localhost:8080/api',
changeOrigin: true,
secure: false,
rewrite: (path): string => path.replace(/^\/api/, '')
}
}
}
})

View file

@ -2,7 +2,7 @@
# We use node:latest as the base image.
# Essentially we build the frontend SPA with vite and
# make it available in the public directory.
FROM docker.io/node:alpine as client
FROM docker.io/node:latest as client
WORKDIR /build
ADD client-solid /build
RUN npm install
@ -12,22 +12,11 @@ RUN npm run build
# We use musl to get a truly static binary
# that runs cleanly without depending on glibc.
FROM docker.io/rust:latest as builder
WORKDIR /build
ADD server /build
RUN apt update
RUN apt install musl musl-dev musl-tools -y
RUN rustup target add x86_64-unknown-linux-musl
# Some hacks to make podman cache build deps, see:
# https://whitfin.io/blog/speeding-up-rust-docker-builds/
RUN cargo new build-container
WORKDIR /build-container
COPY server/Cargo.toml server/Cargo.lock ./
RUN cargo build --target x86_64-unknown-linux-musl --release
RUN rm src/*.rs
ADD server /build-container
# Make sure sqlx reads from .sqlx directory
ENV SQLX_OFFLINE true
RUN cargo build --target x86_64-unknown-linux-musl --release
# Final stage, copy the server binary and the frontend build
@ -40,7 +29,7 @@ RUN addgroup -S user && adduser -S user -G user
WORKDIR /runner
# Copy the server binary and the public directory
COPY --from=builder /build-container/target/x86_64-unknown-linux-musl/release/server /runner/server
COPY --from=builder /build/target/x86_64-unknown-linux-musl/release/server /runner/server
# Copy the frontend SPA build into public
COPY --from=client /build/dist /runner/public

View file

@ -9,22 +9,11 @@
# We use musl to get a truly static binary
# that runs cleanly without depending on glibc.
FROM docker.io/rust:latest as builder
WORKDIR /build
ADD server /build
RUN apt update
RUN apt install musl musl-dev musl-tools -y
RUN rustup target add x86_64-unknown-linux-musl
# Some hacks to make podman cache build deps, see:
# https://whitfin.io/blog/speeding-up-rust-docker-builds/
RUN cargo new build-container
WORKDIR /build-container
COPY server/Cargo.toml server/Cargo.lock ./
RUN cargo build --target x86_64-unknown-linux-musl
RUN rm src/*.rs
ADD server /build-container
# Make sure sqlx reads from .sqlx directory
ENV SQLX_OFFLINE true
# Note that '--release' is missing here, so we build in debug mode
RUN cargo build --target x86_64-unknown-linux-musl
@ -38,9 +27,7 @@ RUN addgroup -S user && adduser -S user -G user
WORKDIR /runner
# Copy the server binary and the public directory, note the debug binary
COPY --from=builder /build-container/target/x86_64-unknown-linux-musl/debug/server /runner/server
RUN mkdir /runner/public
RUN echo "Debug build!" > /runner/public/index.html
COPY --from=builder /build/target/x86_64-unknown-linux-musl/debug/server /runner/server
# Make sure the user can access the files
RUN chown -R user:user /runner

13
container/compose.yml Normal file
View file

@ -0,0 +1,13 @@
version: '3.3'
services:
frostbyte:
container_name: frostbyte
build:
dockerfile: Containerfile
ports:
- '8080:8080'
restart: always
logging:
options:
max-size: 10m
image: frostbyte

View file

@ -1,31 +0,0 @@
# This composefile is not yet ready for use.
# This is because the application assumes the database to be migrated, which happens manually.
version: "3.8"
services:
frostbyte:
build:
context: ..
dockerfile: ./container/Containerfile
container_name: fb-server
environment:
DATABASE_URL: "postgres://CHANGEME:CHANGEME@fb-database:5432/frostbyte"
networks:
- fb_network
depends_on:
- postgres
postgres:
image: docker.io/postgres:16.1-alpine
container_name: fb-database
environment:
POSTGRES_DB: CHANGEME
POSTGRES_USER: CHANGEME
POSTGRES_PASSWORD: CHANGEME
networks:
- fb_network
networks:
fb_network:
driver: bridge

16
container/kube.yml Normal file
View file

@ -0,0 +1,16 @@
# This is not working
apiVersion: v1
kind: Pod
metadata:
labels:
app: frostbyte-pod
name: fbpod
spec:
containers:
- image: "."
name: frostbyte
ports:
- containerPort: 8080
hostPort: 8080
securityContext: {}

109
justfile
View file

@ -1,98 +1,65 @@
pg_pass := "password"
pg_user := "postgres"
pg_container := "postgres-frostbyte" # This is the name of the postgres container
pg_port := "5432"
network := "fb_network"
db_name := "frostbyte" # This is the name of the database
conn_string := "postgres://" + pg_user + ":" + pg_pass + "@" + pg_container + ":" + pg_port / db_name
conn_local := "postgres://" + pg_user + ":" + pg_pass + "@" + "localhost" + ":" + pg_port / db_name
env_string := "DATABASE_URL=" + conn_string
env_local := "DATABASE_URL=" + conn_local
runtime := "podman"
# Builds a debug container and runs it
dev: start-debug
@echo "Cd into client and run 'npm run dev' to start the client in dev mode."
# Builds the client with npm (result in client/dist
npm-install directory:
cd {{directory}} && npm install
# Builds the client with npm (result in client/dist)
[private]
npm-build: (npm-install "client-solid")
cd client && npm run build
# Builds a debug container
[private]
build-container-server-debug:
podman build -t fb-server-debug -f container/ContainerfileDebug .
{{runtime}} build -t fb-server-debug -f container/ContainerfileDebug .
# Builds a debug container and runs it
[private]
start-debug: start-postgres-dev clean-podman init-sqlx build-container-server-debug
podman network create {{network}} --ignore
podman run -d --network {{network}} -e {{env_string}} -p 8080:8080 --name frostbyte-debug fb-server-debug
podman ps | grep frostbyte-debug
start-debug: build-container-server-debug remove-podman-containers
{{runtime}} run -d -p 8080:8080 --name frostbyte-debug fb-server-debug
@echo "Debug server started."
# Builds a release container
[private]
build-container-release:
podman build -t fb-server -f container/Containerfile .
{{runtime}} build -t fb-server -f container/Containerfile .
# Builds a release container and runs it
start-release: start-postgres-dev clean-podman init-sqlx build-container-release create-network
podman run -d --network {{network}} -e {{env_string}} -p 8080:8080 --name frostbyte fb-server
start-release: build-container-release remove-podman-containers
{{runtime}} run -d -p 8080:8080 --name frostbyte fb-server
# Initializes the database, runs migrations and then prepares sqlx
# Removes and stops any containers related to the project
[private]
init-sqlx: install-sqlx
echo {{env_local}} > server/.env
cd server && sqlx database create --connect-timeout 40 # Postgres takes a while to start up
cd server && sqlx migrate run
cd server && cargo sqlx prepare # If this fails, try running just clean
remove-podman-containers:
{{runtime}} container rm -f frostbyte
{{runtime}} container rm -f frostbyte-debug
# Shorthand for installing sqlx
# Deletes everything podman related (even unrelated to the project)
[private]
install-sqlx:
cargo install sqlx-cli
# Starts a postgres container for development
[private]
start-postgres-dev: create-network
podman rm -f {{pg_container}}
podman run --network {{network}} --name {{pg_container}} -e POSTGRES_PASSWORD={{pg_pass}} -d -p {{pg_port}}:5432 docker.io/postgres:16.1-alpine
[private]
create-network:
podman network create {{network}} --ignore
# Forcefully stops and removes the frostbyte container
[private]
clean-podman:
podman container rm -f frostbyte
podman container rm -f frostbyte-debug
# Removes the database container
[private]
clean-db:
podman container rm -f {{pg_container}}
# Removes the network
[private]
clean-network:
podman network rm -f {{network}}
# Forcefully removes the frostbyte images
[private]
clean-images:
podman image rm -f fb-server
podman image rm -f fb-server-debug
podman image rm -f postgres
podman image prune -af
prune-podman:
{{runtime}} stop -a
{{runtime}} rm -af
{{runtime}} image rm -af
{{runtime}} system prune -af
{{runtime}} system reset --force
# Cleans up everything related to the project
clean: clean-podman clean-db clean-images clean-network && state
rm -rf client-solid/dist
rm -rf client-solid/node_modules
clean:
{{runtime}} container rm -f frostbyte
{{runtime}} container rm -f frostbyte-debug
{{runtime}} image rm -f fb-server
{{runtime}} image rm -f fb-server-debug
rm -rf client/dist
rm -rf client/node_modules
rm -rf server/public
rm -rf server/target
@echo "Cleaned up! Make sure to clean up podman volumes and networks."
@echo "Cleaned up! Make sure to run 'just nuke' to nuke everything podman related."
state:
podman ps -a
podman images ls -a
podman network ls
du -sch client* server
# Nukes everything. No mercy. Leave no trace.
nuke: clean prune-podman
@echo "Nuked everything! You're starting from scratch now."

View file

@ -1,22 +0,0 @@
{
"db_name": "PostgreSQL",
"query": "SELECT username FROM users WHERE username = $1",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "username",
"type_info": "Text"
}
],
"parameters": {
"Left": [
"Text"
]
},
"nullable": [
false
]
},
"hash": "16e84d577155f3c47fcb736bbad4dcaf05b21c79d47fe008e209191157f5697e"
}

View file

@ -1,56 +0,0 @@
{
"db_name": "PostgreSQL",
"query": "SELECT * FROM posts WHERE id = (SELECT MAX(id) FROM posts)",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Int8"
},
{
"ordinal": 1,
"name": "user_id",
"type_info": "Int8"
},
{
"ordinal": 2,
"name": "content",
"type_info": "Text"
},
{
"ordinal": 3,
"name": "upvotes",
"type_info": "Int4"
},
{
"ordinal": 4,
"name": "downvotes",
"type_info": "Int4"
},
{
"ordinal": 5,
"name": "created_at",
"type_info": "Timestamp"
},
{
"ordinal": 6,
"name": "updated_at",
"type_info": "Timestamp"
}
],
"parameters": {
"Left": []
},
"nullable": [
false,
false,
false,
false,
false,
false,
false
]
},
"hash": "1cff76615ce5fb26bd9fbb23cbe4a204ddf3d75be6666fca3624deb35c0aaa97"
}

View file

@ -1,44 +0,0 @@
{
"db_name": "PostgreSQL",
"query": "SELECT * FROM users",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Int8"
},
{
"ordinal": 1,
"name": "username",
"type_info": "Text"
},
{
"ordinal": 2,
"name": "password",
"type_info": "Text"
},
{
"ordinal": 3,
"name": "created_at",
"type_info": "Timestamp"
},
{
"ordinal": 4,
"name": "updated_at",
"type_info": "Timestamp"
}
],
"parameters": {
"Left": []
},
"nullable": [
false,
false,
false,
false,
false
]
},
"hash": "26e7e05427bc7dabcd7815d27764fda2baf4cfe60a2d2d6ee2a1f773dccbbce2"
}

View file

@ -1,53 +0,0 @@
{
"db_name": "PostgreSQL",
"query": "SELECT id, content, upvotes, downvotes, created_at, updated_at FROM posts ORDER BY created_at DESC LIMIT $1 OFFSET $2",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Int8"
},
{
"ordinal": 1,
"name": "content",
"type_info": "Text"
},
{
"ordinal": 2,
"name": "upvotes",
"type_info": "Int4"
},
{
"ordinal": 3,
"name": "downvotes",
"type_info": "Int4"
},
{
"ordinal": 4,
"name": "created_at",
"type_info": "Timestamp"
},
{
"ordinal": 5,
"name": "updated_at",
"type_info": "Timestamp"
}
],
"parameters": {
"Left": [
"Int8",
"Int8"
]
},
"nullable": [
false,
false,
false,
false,
false,
false
]
},
"hash": "2ec6780ea09d3cd14aeb87aeb97d93ff9a46e71d75f7e00d6c990fd3585ed866"
}

View file

@ -1,66 +0,0 @@
{
"db_name": "PostgreSQL",
"query": "SELECT id, parent_post_id, parent_comment_id, upvotes, downvotes, content, created_at, updated_at FROM comments WHERE parent_post_id = $1 ORDER BY created_at DESC LIMIT $2 OFFSET $3",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Int8"
},
{
"ordinal": 1,
"name": "parent_post_id",
"type_info": "Int8"
},
{
"ordinal": 2,
"name": "parent_comment_id",
"type_info": "Int8"
},
{
"ordinal": 3,
"name": "upvotes",
"type_info": "Int4"
},
{
"ordinal": 4,
"name": "downvotes",
"type_info": "Int4"
},
{
"ordinal": 5,
"name": "content",
"type_info": "Text"
},
{
"ordinal": 6,
"name": "created_at",
"type_info": "Timestamp"
},
{
"ordinal": 7,
"name": "updated_at",
"type_info": "Timestamp"
}
],
"parameters": {
"Left": [
"Int8",
"Int8",
"Int8"
]
},
"nullable": [
false,
false,
true,
false,
false,
false,
false,
false
]
},
"hash": "361a0590e46d138eba4973962c5f527ea86dc3c8640a5dc556523ff336be470e"
}

View file

@ -1,46 +0,0 @@
{
"db_name": "PostgreSQL",
"query": "SELECT * FROM users WHERE username = $1",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Int8"
},
{
"ordinal": 1,
"name": "username",
"type_info": "Text"
},
{
"ordinal": 2,
"name": "password",
"type_info": "Text"
},
{
"ordinal": 3,
"name": "created_at",
"type_info": "Timestamp"
},
{
"ordinal": 4,
"name": "updated_at",
"type_info": "Timestamp"
}
],
"parameters": {
"Left": [
"Text"
]
},
"nullable": [
false,
false,
false,
false,
false
]
},
"hash": "606364c79e0990deb07dfbe6c32b3d302d083ec5333f3a5ce04113c38a041100"
}

View file

@ -1,15 +0,0 @@
{
"db_name": "PostgreSQL",
"query": "INSERT INTO posts (user_id, content) VALUES ($1, $2)",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Int8",
"Text"
]
},
"nullable": []
},
"hash": "a2835289cba16d38401e5324876508b8397ef7fbb9eb521ac3c5e57206eeecf7"
}

View file

@ -1,14 +0,0 @@
{
"db_name": "PostgreSQL",
"query": "INSERT INTO posts (user_id, content) VALUES (1, $1)",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Text"
]
},
"nullable": []
},
"hash": "a700af019c69280cb9a0d199cc59a751a0ce16ccf2d94950219505764cc176e9"
}

View file

@ -1,15 +0,0 @@
{
"db_name": "PostgreSQL",
"query": "INSERT INTO users (username, password) VALUES ($1, $2)",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Text",
"Text"
]
},
"nullable": []
},
"hash": "c936f44864dafe4660a736babd5f93050b7d35c66c0fe0c86f7b2dcdb7a1e3eb"
}

View file

@ -1,22 +0,0 @@
{
"db_name": "PostgreSQL",
"query": "SELECT id FROM users WHERE username = $1",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Int8"
}
],
"parameters": {
"Left": [
"Text"
]
},
"nullable": [
false
]
},
"hash": "dd99e48b1572e25db38f03da95984fda1072913b29bb6b3753a0d351583dfff6"
}

View file

@ -1,52 +0,0 @@
{
"db_name": "PostgreSQL",
"query": "SELECT id, content, upvotes, downvotes, created_at, updated_at FROM posts WHERE id = $1",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Int8"
},
{
"ordinal": 1,
"name": "content",
"type_info": "Text"
},
{
"ordinal": 2,
"name": "upvotes",
"type_info": "Int4"
},
{
"ordinal": 3,
"name": "downvotes",
"type_info": "Int4"
},
{
"ordinal": 4,
"name": "created_at",
"type_info": "Timestamp"
},
{
"ordinal": 5,
"name": "updated_at",
"type_info": "Timestamp"
}
],
"parameters": {
"Left": [
"Int8"
]
},
"nullable": [
false,
false,
false,
false,
false,
false
]
},
"hash": "f2463f3ff911698f3e841c631e8b8609408eaa32f0dcc7fb70c029339613cd07"
}

View file

@ -1,17 +0,0 @@
{
"db_name": "PostgreSQL",
"query": "INSERT INTO comments (parent_post_id, parent_comment_id, author_user_id, content) VALUES ($1, $2, $3, $4)",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Int8",
"Int8",
"Int8",
"Text"
]
},
"nullable": []
},
"hash": "fe72509852c87463cea9775d9606e89a9851b372b39d68a10c16961acd968eef"
}

1318
server/Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -6,24 +6,16 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
actix-cors = "0.7.0"
actix-files = "0.6.6"
actix-web = "4.9.0"
argon2 = { version = "0.5.3", features = ["zeroize"] }
biosvg = "0.1.7"
chrono = { version = "0.4.39", features = ["serde"] }
clap = { version = "4.5.23", features = ["derive"] }
dotenvy = "0.15.7"
env_logger = "0.11.6"
jsonwebtoken = "9.3.0"
lipsum = "0.9.1"
log = "0.4.22"
rand = "0.8.5"
serde = { version = "1.0.216", features = ["derive"] }
serde_json = "1.0.134"
actix-files = "0.6.2"
actix-web = "4.4.0"
argon2 = { version = "0.5.2", features = ["zeroize"] }
chrono = { version = "0.4.31", features = ["serde"] }
clap = { version = "4.4.5", features = ["derive"] }
env_logger = "0.10.0"
jsonwebtoken = "8.3.0"
log = "0.4.20"
serde = { version = "1.0.188", features = ["derive"] }
serde_json = "1.0.107"
sled = { version = "0.34.7" }
sqlx = { version = "0.8.2", features = ["runtime-tokio", "chrono", "uuid", "postgres", "tls-rustls"] }
uuid = { version = "1.11.0", features = ["serde", "v4"] }
[profile.dev.package.sqlx-macros]
opt-level = 3
sqlx = { version = "0.7.2", features = ["sqlite", "runtime-tokio"] }
uuid = { version = "1.4.1", features = ["serde", "v4"] }

View file

@ -1,38 +1,9 @@
CREATE TABLE IF NOT EXISTS users (
id BIGSERIAL PRIMARY KEY,
username TEXT NOT NULL UNIQUE,
id SERIAL PRIMARY KEY,
username TEXT NOT NULL,
password TEXT NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
-- Create a function to set created_at and updated_at on INSERT
CREATE OR REPLACE FUNCTION set_timestamps_on_insert() RETURNS TRIGGER AS $$
BEGIN
NEW.created_at = NOW();
NEW.updated_at = NOW();
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
-- Create a trigger to call the function after INSERT
CREATE TRIGGER set_timestamps_on_insert
BEFORE INSERT ON users
FOR EACH ROW
EXECUTE FUNCTION set_timestamps_on_insert();
-- Create a function to set updated_at on UPDATE
CREATE OR REPLACE FUNCTION set_updated_at() RETURNS TRIGGER AS $$
BEGIN
NEW.updated_at = NOW();
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
-- Create a trigger to call the function after UPDATE
CREATE TRIGGER set_updated_at
BEFORE UPDATE ON users
FOR EACH ROW
EXECUTE FUNCTION set_updated_at();
CREATE INDEX users_username_index ON users (username);
create index users_username_index on users (username);

View file

@ -1,43 +1,10 @@
CREATE TABLE IF NOT EXISTS posts (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT NOT NULL,
id SERIAL PRIMARY KEY,
user_id SERIAL NOT NULL,
content TEXT NOT NULL,
upvotes INTEGER NOT NULL DEFAULT 0,
downvotes INTEGER NOT NULL DEFAULT 0,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users (id)
);
-- Create a function to set created_at and updated_at on INSERT
CREATE OR REPLACE FUNCTION set_timestamps_on_insert() RETURNS TRIGGER AS $$
BEGIN
NEW.created_at = NOW();
NEW.updated_at = NOW();
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
-- Create a trigger to call the function after INSERT
CREATE TRIGGER set_timestamps_on_insert
BEFORE INSERT ON posts
FOR EACH ROW
EXECUTE FUNCTION set_timestamps_on_insert();
-- Create a function to set updated_at on UPDATE
CREATE OR REPLACE FUNCTION set_updated_at() RETURNS TRIGGER AS $$
BEGIN
NEW.updated_at = NOW();
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
-- Create a trigger to call the function after UPDATE
CREATE TRIGGER set_updated_at
BEFORE UPDATE ON posts
FOR EACH ROW
EXECUTE FUNCTION set_updated_at();
CREATE INDEX posts_user_id_index ON posts (user_id);
CREATE INDEX posts_id_index ON posts (id);
CREATE INDEX idx_created_at_desc ON posts (created_at DESC);
create index IF NOT EXISTS posts_user_id_index on posts (user_id);
create index IF NOT EXISTS posts_id_index on posts (id);

View file

@ -1,47 +0,0 @@
CREATE TABLE IF NOT EXISTS comments (
id BIGSERIAL PRIMARY KEY,
parent_post_id BIGINT NOT NULL,
parent_comment_id BIGINT,
author_user_id BIGINT NOT NULL,
content TEXT NOT NULL,
upvotes INTEGER NOT NULL DEFAULT 0,
downvotes INTEGER NOT NULL DEFAULT 0,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (parent_post_id) REFERENCES posts (id),
FOREIGN KEY (parent_comment_id) REFERENCES comments (id),
FOREIGN KEY (author_user_id) REFERENCES users (id)
);
-- Create a function to set created_at and updated_at on INSERT
CREATE OR REPLACE FUNCTION comments_set_timestamps_on_insert() RETURNS TRIGGER AS $$
BEGIN
NEW.created_at = NOW();
NEW.updated_at = NOW();
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
-- Create a trigger to call the function after INSERT
CREATE TRIGGER comments_set_timestamps_on_insert
BEFORE INSERT ON posts
FOR EACH ROW
EXECUTE FUNCTION set_timestamps_on_insert();
-- Create a function to set updated_at on UPDATE
CREATE OR REPLACE FUNCTION comments_set_updated_at() RETURNS TRIGGER AS $$
BEGIN
NEW.updated_at = NOW();
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
-- Create a trigger to call the function after UPDATE
CREATE TRIGGER comments_set_updated_at
BEFORE UPDATE ON posts
FOR EACH ROW
EXECUTE FUNCTION comments_set_updated_at();
CREATE INDEX comments_parent_post_id_index ON comments (parent_post_id);
CREATE INDEX comments_parent_comment_id_index ON comments (parent_comment_id);
CREATE INDEX comments_user_id_index ON comments (author_user_id);

View file

@ -1,189 +0,0 @@
use crate::types::{Post, PublicComment, PublicPost, User};
use argon2::{
password_hash::{rand_core::OsRng, SaltString},
Argon2, PasswordHasher, PasswordVerifier,
};
use log::{info, warn};
use sqlx::PgPool;
pub async fn db_new_comment(
pool: &PgPool,
parent_post_id: i64,
parent_comment_id: Option<i64>,
user_id: i64,
content: &str,
) -> bool {
let insert_query = sqlx::query!(
"INSERT INTO comments (parent_post_id, parent_comment_id, author_user_id, content) VALUES ($1, $2, $3, $4)",
parent_post_id,
parent_comment_id,
user_id,
content
)
.execute(pool)
.await;
if insert_query.is_err() {
let s = insert_query.err().unwrap();
warn!("Error inserting comment into database: {}", s);
return false;
}
true
}
pub async fn db_get_comments(
pool: &PgPool,
parent_post_id: i64,
limit: i64,
offset: i64,
) -> Vec<PublicComment> {
sqlx::query_as!(
PublicComment,
"SELECT id, parent_post_id, parent_comment_id, upvotes, downvotes, content, created_at, updated_at FROM comments WHERE parent_post_id = $1 ORDER BY created_at DESC LIMIT $2 OFFSET $3",
parent_post_id,
limit,
offset
)
.fetch_all(pool)
.await
.unwrap()
}
/// Gets the latest posts from the database, ordered by created_at
pub async fn db_get_latest_posts(pool: &PgPool, limit: i64, offset: i64) -> Vec<PublicPost> {
sqlx::query_as!(
PublicPost,
"SELECT id, content, upvotes, downvotes, created_at, updated_at FROM posts ORDER BY created_at DESC LIMIT $1 OFFSET $2",
limit,
offset
)
.fetch_all(pool)
.await
.unwrap()
}
/// Gets the post with id from the database
pub async fn db_get_post(id: i64, pool: &PgPool) -> Option<PublicPost> {
sqlx::query_as!(
PublicPost,
"SELECT id, content, upvotes, downvotes, created_at, updated_at FROM posts WHERE id = $1",
id
)
.fetch_one(pool)
.await
.ok()
}
/// Inserts a new post to the database
pub async fn db_new_post(userid: i64, content: &str, pool: &PgPool) -> Option<Post> {
info!("User with id {} submitted a post", userid);
let insert_query = sqlx::query!(
"INSERT INTO posts (user_id, content) VALUES ($1, $2)",
userid,
content
)
.execute(pool)
.await;
if insert_query.is_err() {
let s = insert_query.err().unwrap();
warn!("Error inserting post into database: {}", s);
return None;
}
// Dips into the database to get the post we just inserted
let post = sqlx::query_as!(
Post,
"SELECT * FROM posts WHERE id = (SELECT MAX(id) FROM posts)"
)
.fetch_one(pool)
.await
.ok()?;
Some(post)
}
/// Checks if the user exists in the database
pub async fn db_user_exists(username: String, pool: &PgPool) -> bool {
let exists = sqlx::query!("SELECT username FROM users WHERE username = $1", username)
.fetch_one(pool)
.await
.ok()
.map(|row| row.username);
exists.is_some()
}
/// Checks if the user exists and if the password is correct
pub async fn db_user_login(username: String, password: String, pool: &PgPool) -> Option<User> {
let username = username.clone();
let user = sqlx::query_as!(User, "SELECT * FROM users WHERE username = $1", username)
.fetch_one(pool)
.await
.ok()?;
let phc_password = user.password.clone();
let phc_password = match argon2::PasswordHash::new(&phc_password) {
Ok(phc_password) => phc_password,
Err(_) => {
warn!(
"Invalid hash for user {} fetched from database (not a valid PHC string)",
username
);
return None;
}
};
let argon2 = Argon2::default();
let password = password.as_bytes();
match argon2.verify_password(password, &phc_password) {
Ok(_) => Some(user),
Err(_) => None,
}
}
/// Creates a new user if the username is not already taken
pub async fn db_new_user(username: String, password: String, pool: &PgPool) -> Option<User> {
// First check if the user already exists
match db_user_exists(username.clone(), pool).await {
true => {
warn!("User \"{}\" already exists", username);
return None;
}
false => {}
}
// Unwrapping here because if this fails, we have a serious problem
let phc_hash = Argon2::default()
.hash_password(password.as_bytes(), &SaltString::generate(&mut OsRng))
.unwrap()
.to_string();
// Insert our new user into the database
let insert_query = sqlx::query!(
"INSERT INTO users (username, password) VALUES ($1, $2)",
username,
phc_hash
)
.execute(pool)
.await;
match insert_query {
Ok(_) => {
info!("User: {} registered", username);
let user = sqlx::query_as!(User, "SELECT * FROM users WHERE username = $1", username)
.fetch_one(pool)
.await
.ok()?;
Some(user)
}
Err(e) => {
warn!("Error inserting user into database: {}", e);
return None;
}
}
}

View file

@ -1,114 +1,61 @@
// use crate::{
// config::{DAYS_VALID, JWT_SECRET},
// Claims,
// };
use jsonwebtoken::{
decode, encode, errors::Result as JwtResult, DecodingKey, EncodingKey, Header, Validation,
};
use log::*;
use serde::{Deserialize, Serialize};
/// Claims holds the data that will be encoded into the JWT token.
const DAYS_VALID: i64 = 7;
const JWT_SECRET: &[u8] = "secret".as_bytes();
#[derive(Debug, Serialize, Deserialize)]
pub struct Claims {
#[serde(rename = "sub")]
pub sub: String,
#[serde(rename = "iss")]
pub iss: String,
#[serde(rename = "iat")]
pub aud: String,
pub iat: usize,
#[serde(rename = "exp")]
pub exp: usize,
}
impl Claims {
pub fn new(sub: &str, days: i64) -> Self {
Claims {
sub: sub.to_string(),
iss: "frostbyte".to_string(),
// JwtResult is just a predefined error from the jsonwebtoken crate
pub fn token_factory(user: &str) -> JwtResult<String> {
info!("Issuing JWT token for {}", user);
let token = encode(
&Header::default(),
&Claims {
sub: user.to_string(),
iss: "localhost".to_string(),
aud: "localhost".to_string(),
iat: chrono::Utc::now().timestamp() as usize,
exp: (chrono::Utc::now() + chrono::Duration::days(days)).timestamp() as usize,
exp: (chrono::Utc::now() + chrono::Duration::days(DAYS_VALID)).timestamp() as usize,
},
&EncodingKey::from_secret(JWT_SECRET),
)
.unwrap();
Ok(token)
}
#[allow(dead_code)]
pub fn validate_token(token: &str) -> JwtResult<Claims> {
let token_data = decode::<Claims>(
token,
&DecodingKey::from_secret(JWT_SECRET),
&Validation::default(),
);
match token_data {
Ok(token_data) => {
info!("Token validated for {}", token_data.claims.sub);
Ok(token_data.claims)
}
Err(e) => {
error!("Token validation failed: {}", e);
Err(e)
}
}
}
/// Authentication holds the data needed to encode and decode JWT tokens.
// This is then passed to the AuthenticationMiddleware
#[derive(Clone)]
pub struct Authentication {
encoding_key: EncodingKey,
decoding_key: DecodingKey,
validation: Validation,
days_valid: i64, // chrono::Duration::days() takes an i64, we don't want to cast it every time
}
impl Authentication {
/// Create a new Authentication struct
pub fn new(secret: &[u8]) -> Self {
Authentication {
encoding_key: EncodingKey::from_secret(secret),
decoding_key: DecodingKey::from_secret(secret),
validation: Validation::default(),
days_valid: 7,
}
}
/// Encode the Claims struct into a JWT token, this is the raw version
fn encode_raw(&self, claims: Claims) -> JwtResult<String> {
encode(&Header::default(), &claims, &self.encoding_key)
}
/// Wrapper for encode_raw that takes a username (sub) and creates a Claims struct
pub fn encode(&self, sub: &str) -> JwtResult<String> {
let claims = Claims::new(sub, self.days_valid);
self.encode_raw(claims)
}
/// Decode a JWT token into a Claims struct
// If this faie, it means the token is invalid
pub fn decode(&self, token: &str) -> JwtResult<Claims> {
decode::<Claims>(token, &self.decoding_key, &self.validation).map(|data| data.claims)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_auth() {
let username: &str = "testuser";
let auth = Authentication::new("secret".as_bytes());
assert!(auth.encode(username).is_ok());
let token = auth.encode(username);
assert!(!token.is_err());
let token = token.unwrap();
assert!(!token.is_empty());
}
#[test]
fn test_validate() {
let username: &str = "testuser";
let auth = Authentication::new("secret".as_bytes());
let token = auth.encode(username).unwrap();
let claims = auth.decode(&token).unwrap();
assert_eq!(claims.sub, username);
}
#[test]
fn test_invalid() {
let auth = Authentication::new("secret".as_bytes());
let token = auth.encode("testuser").unwrap();
// Remove the first character should invalidate the token
let token = token[1..].to_string();
assert!(auth.decode(&token).is_err());
}
#[test]
fn test_expired() {
let auth = Authentication::new("secret".as_bytes());
// Chrono::duration allows negative durations, -1 is yesterday in this case
let claims = Claims::new("testuser", -1);
let token = auth.encode_raw(claims).unwrap();
assert!(auth.decode(&token).is_err());
}
}

View file

@ -1,74 +1,39 @@
use actix_cors::Cors;
use actix_files::Files;
use actix_web::middleware;
use actix_web::web::Data;
use actix_web::{web::scope, App, HttpServer};
use log::info;
mod db;
mod jwt;
mod routes;
mod state;
mod types;
mod util;
use jwt::Authentication;
use routes::{get_comments, get_posts, login, new_comment, new_post, post_by_id, register};
use state::CaptchaState;
use routes::{get_posts, login, new_post, register, test};
use state::ServerState;
use util::hex_string;
#[actix_web::main]
async fn main() -> std::io::Result<()> {
env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("debug")).init();
let data = ServerState::new().await;
let capt_db = CaptchaState::new();
let auth = Authentication::new("secret".as_bytes());
#[cfg(debug_assertions)]
{
for _ in 0..10 {
let s = hex_string(10);
info!("Adding captcha key: {}", &s);
capt_db.capthca_db.lock().unwrap().insert(s);
}
}
info!("Spinning up server on http://localhost:8080");
HttpServer::new(move || {
let cors = Cors::default()
.allowed_origin("https://shitpost.se")
.allowed_methods(vec!["GET", "POST"])
.max_age(3600);
// In debug mode, allow any origin
#[cfg(debug_assertions)]
let cors = cors.allow_any_origin();
App::new()
.wrap(cors)
.wrap(middleware::Compress::default())
.wrap(middleware::Logger::default())
.wrap(middleware::NormalizePath::trim())
.service(
scope("/api")
.service(get_posts)
.service(new_post)
.service(new_comment)
.service(get_comments)
.service(post_by_id)
.service(routes::vote)
.service(test)
.service(login)
.service(register)
.app_data(Data::new(data.clone()))
.app_data(Data::new(capt_db.clone()))
.app_data(Data::new(auth.clone())),
)
.service(
Files::new("/", "./public")
.index_file("index.html")
.default_handler(actix_files::NamedFile::open("./public/index.html").unwrap()),
.app_data(Data::new(data.clone())),
)
.service(Files::new("/", "./public").index_file("index.html"))
})
.bind("0.0.0.0:8080")?
.run()

189
server/src/routes.rs Executable file
View file

@ -0,0 +1,189 @@
use crate::jwt::token_factory;
use crate::types::{NewPost, Post};
use crate::ServerState;
use actix_web::web::{Data, Path};
use actix_web::{get, post, web::Json, HttpResponse, Responder, Result};
use argon2::password_hash::rand_core::OsRng;
use argon2::password_hash::SaltString;
use argon2::password_hash::*;
use argon2::Argon2;
use argon2::PasswordHasher;
use argon2::PasswordVerifier;
use log::*;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
#[get("/")]
pub async fn get_posts(data: Data<ServerState>) -> impl Responder {
match data.posts.lock() {
Ok(posts) => {
let posts: Vec<Post> = posts.values().cloned().collect();
HttpResponse::Ok().json(posts)
}
Err(e) => {
warn!("Error: {:?}", e);
HttpResponse::InternalServerError().body("Error")
}
}
}
#[post("/")]
pub async fn new_post(new_post: Json<NewPost>, data: Data<ServerState>) -> impl Responder {
let post = Post::from(new_post.into_inner());
info!("Created post {:?}", post.uuid);
// let q = "INSERT INTO posts (uuid, content, upvotes, downvotes) VALUES (?, ?, ?, ?)";
// let query = sqlx::query(q)
// .bind(post.uuid)
// .bind(post.content)
// .bind(post.votes.up)
// .bind(post.votes.down);
match data.posts.lock() {
Ok(mut posts) => {
posts.insert(post.uuid, post);
}
Err(e) => {
warn!("Error: {:?}", e);
}
};
HttpResponse::Ok().json("Post added!")
}
// This is a test route, returns "Hello, world!"
#[get("/test")]
pub async fn test(data: Data<ServerState>) -> impl Responder {
match data.posts.lock() {
Ok(posts) => {
let posts: Vec<Post> = posts.values().cloned().collect();
HttpResponse::Ok().body(format!("Hello, world! {:?}", posts))
}
Err(e) => {
warn!("Error: {:?}", e);
HttpResponse::InternalServerError().body("Error")
}
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum VoteDirection {
Up,
Down,
Unupvote,
Undownvote,
}
#[post("vote/{uuid}/{direction}")]
pub async fn vote(params: Path<(Uuid, VoteDirection)>, data: Data<ServerState>) -> impl Responder {
let (uuid, direction) = params.into_inner();
println!("Voting {:?} on post {:?}", direction, uuid);
match data.posts.lock() {
Ok(mut posts) => {
let uuid = uuid;
if let Some(post) = posts.get_mut(&uuid) {
match direction {
VoteDirection::Up => post.votes.up += 1,
VoteDirection::Unupvote => post.votes.up -= 1,
VoteDirection::Down => post.votes.down += 1,
VoteDirection::Undownvote => post.votes.down -= 1,
}
HttpResponse::Ok().body("Downvoted!")
} else {
HttpResponse::NotFound().body("Post not found!")
}
}
Err(e) => {
warn!("Error: {:?}", e);
HttpResponse::InternalServerError().body("Error")
}
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct RegisterData {
username: String,
password: String,
captcha: String,
}
#[post("/register")]
pub async fn register(
data: Json<RegisterData>,
state: Data<ServerState>,
) -> Result<impl Responder> {
let q = "SELECT password FROM users WHERE username = ?";
let query = sqlx::query(q).bind(&data.username);
let result = query.fetch_one(&state.pool).await.ok();
if result.is_some() {
info!("User \"{}\" already exists", data.username);
return Ok(HttpResponse::BadRequest().json("Error"));
}
let password = data.password.clone();
let salt = SaltString::generate(&mut OsRng);
let phc_hash = Argon2::default().hash_password(password.as_bytes(), &salt);
if let Ok(phc_hash) = phc_hash {
info!("User: {} registered", data.username);
let phc_hash = phc_hash.to_string();
let q = "INSERT INTO users (username, password) VALUES (?, ?)";
let query = sqlx::query(q).bind(&data.username).bind(&phc_hash);
query.execute(&state.pool).await.unwrap();
} else {
return Ok(HttpResponse::BadRequest().json("Error"));
}
Ok(HttpResponse::Ok().json("User registered"))
}
#[derive(Debug, Serialize, Deserialize)]
pub struct LoginData {
username: String,
password: String,
}
use sqlx::Row;
#[derive(Debug, Serialize, Deserialize)]
struct LoginResponse {
username: String,
token: String,
}
#[post("/login")]
pub async fn login(data: Json<LoginData>, state: Data<ServerState>) -> Result<impl Responder> {
let q = "SELECT password FROM users WHERE username = ?";
let query = sqlx::query(q).bind(&data.username);
let result = query.fetch_one(&state.pool).await.ok();
if let Some(row) = result {
let phc_from_db = row.get::<String, _>("password");
let pwhash = PasswordHash::new(&phc_from_db).unwrap_or_else(|_| {
warn!(
"Invalid hash for user {} fetched from database (not a valid PHC string)",
data.username
);
panic!();
});
match Argon2::default().verify_password(data.password.as_bytes(), &pwhash) {
Ok(_) => {
info!("User {} logged in", data.username);
let token = token_factory(&data.username).unwrap();
println!("{:?}", token);
return Ok(HttpResponse::Ok().json(LoginResponse {
username: data.username.clone(),
token: token,
}));
}
Err(_) => {
info!("User \"{}\" failed to log in", data.username);
return Ok(HttpResponse::BadRequest().json("Error"));
}
}
}
Ok(HttpResponse::Ok().json("What happens here???"))
}

View file

@ -1,82 +0,0 @@
use crate::db::{db_get_comments, db_new_comment};
use crate::jwt::Authentication;
use crate::types::{CommentQueryParams, NewComment};
use crate::ServerState;
use actix_web::get;
use actix_web::web::{Data, Query};
use actix_web::{post, web::Json, HttpResponse, Responder, Result};
use log::info;
#[get("/comments")]
pub async fn get_comments(
comment_filter: Query<CommentQueryParams>,
state: Data<ServerState>,
) -> Result<impl Responder> {
let post_id = comment_filter.post_id;
let limit = comment_filter.limit.unwrap_or(10);
let offset = comment_filter.offset.unwrap_or(0);
info!(
"Getting comments for post {} with limit {} and offset {}",
post_id, limit, offset
);
let comments = db_get_comments(&state.pool, post_id, limit, offset).await;
Ok(HttpResponse::Ok().json(comments))
}
#[post("/comments")]
pub async fn new_comment(
data: Json<NewComment>,
state: Data<ServerState>,
auth: Data<Authentication>,
) -> Result<impl Responder> {
let user_claims = auth.decode(&data.user_token);
// Bail if the token is invalid
if let Err(e) = user_claims {
info!("Error validating token: {}", e);
return Ok(HttpResponse::BadRequest().json("Error"));
}
let claims = user_claims.unwrap();
let content = data.content.clone();
let username = claims.sub.clone();
// This one is avoidable if we just store the user id in the token
let userid = sqlx::query!("SELECT id FROM users WHERE username = $1", username)
.fetch_one(&state.pool)
.await
.unwrap()
.id;
info!(
"User {:?}, with id {:?} is creating a new comment",
&claims.sub, userid
);
info!("Creating a new comment {:?}", &data);
let success = db_new_comment(
&state.pool,
data.parent_post_id,
data.parent_comment_id,
userid,
&content,
)
.await;
match success {
true => {
info!("User {:?} created a new comment", &claims.sub);
Ok(HttpResponse::Ok().json("Successfully created comment"))
}
false => {
info!("User {:?} failed to create a new comment", &claims.sub);
Ok(HttpResponse::BadRequest().json("Failed to create comment"))
}
}
}

View file

@ -1,7 +0,0 @@
mod comment;
mod post;
mod users;
pub use comment::*;
pub use post::*;
pub use users::*;

View file

@ -1,69 +0,0 @@
use crate::db::{db_get_latest_posts, db_get_post, db_new_post};
use crate::jwt::Authentication;
use crate::types::{NewPost, PostQueryParams};
use crate::ServerState;
use actix_web::web::{Data, Path, Query};
use actix_web::{get, post, web::Json, HttpResponse, Responder, Result};
use log::info;
/// Gets all posts from the database, query parameters are optional
/// If limit is not specified, it defaults to a sane value
#[get("/posts")]
pub async fn get_posts(
query: Query<PostQueryParams>,
state: Data<ServerState>,
) -> Result<impl Responder> {
if let (Some(lim), Some(ofs)) = (query.limit, query.offset) {
return Ok(HttpResponse::Ok()
.json(db_get_latest_posts(&state.pool, std::cmp::min(lim, 30), ofs).await));
}
Ok(HttpResponse::Ok().json(db_get_latest_posts(&state.pool, 30, 0).await))
}
/// Creates a new post, requires a token in release mode
#[post("/posts")]
pub async fn new_post(
new_post: Json<NewPost>,
state: Data<ServerState>,
auth: Data<Authentication>,
) -> Result<impl Responder> {
let user_claims = auth.decode(&new_post.token);
if let Err(e) = user_claims {
info!("Error validating token: {}", e);
return Ok(HttpResponse::BadRequest().json("Error"));
}
// Bail if the token is invalid
let claims = user_claims.unwrap();
info!("User {:?} created a new post", &claims.sub);
let content = new_post.content.clone();
let username = claims.sub.clone();
// This one is avoidable if we just store the user id in the token
let userid = sqlx::query!("SELECT id FROM users WHERE username = $1", username)
.fetch_one(&state.pool)
.await
.unwrap()
.id;
// By now we know that the token is valid, so we can create the post
return match db_new_post(userid, &content, &state.pool).await {
Some(post) => {
info!("Created post {:?}", post.id);
Ok(HttpResponse::Ok().json(post))
}
None => Ok(HttpResponse::InternalServerError().json("Error")),
};
}
#[get("posts/{id}")]
pub async fn post_by_id(path: Path<i64>, state: Data<ServerState>) -> Result<impl Responder> {
let id = path.into_inner();
match db_get_post(id, &state.pool).await {
Some(post) => Ok(HttpResponse::Ok().json(post)),
None => Ok(HttpResponse::NotFound().json("Error")),
}
}

View file

@ -1,120 +0,0 @@
use crate::db::{db_new_user, db_user_login};
use crate::jwt::Authentication;
// use crate::jwt::token_factory;
use crate::state::CaptchaState;
use crate::types::{AuthResponse, LoginData, RegisterData};
use crate::ServerState;
use actix_web::web::Data;
use actix_web::{post, web::Json, HttpResponse, Responder, Result};
use biosvg::BiosvgBuilder;
use log::*;
#[post("/register")]
pub async fn register(
data: Json<RegisterData>,
state: Data<ServerState>,
captcha_state: Data<CaptchaState>,
auth: Data<Authentication>,
) -> Result<impl Responder> {
if !captcha_state
.capthca_db
.lock()
.unwrap()
.remove(&data.captcha)
{
info!("User failed to register, captcha was wrong");
return Ok(HttpResponse::BadRequest().json("Error"));
}
match db_new_user(data.username.clone(), data.password.clone(), &state.pool).await {
Some(user) => {
info!("User: {} registered", &user.username);
Ok(HttpResponse::Ok().json(AuthResponse {
username: user.username.clone(),
token: auth.encode(&user.username).unwrap(),
}))
}
None => {
info!("User \"{}\" already exists", data.username);
return Ok(HttpResponse::BadRequest().json("Error"));
}
}
}
#[post("/login")]
pub async fn login(
data: Json<LoginData>,
state: Data<ServerState>,
auth: Data<Authentication>,
) -> Result<impl Responder> {
let result = db_user_login(data.username.clone(), data.password.clone(), &state.pool).await;
match result {
Some(_) => {
return Ok(HttpResponse::Ok().json(AuthResponse {
username: data.username.clone(),
token: auth.encode(&data.username).unwrap(),
}));
}
None => {
info!("User \"{}\" failed to log in", data.username);
return Ok(HttpResponse::BadRequest().json("Error"));
}
}
}
/// Request a captcha from the captcha service
#[allow(unreachable_code, unused_variables)]
#[post("/captcha")]
pub async fn captcha_request(cstate: Data<CaptchaState>) -> Result<impl Responder> {
unimplemented!("Captcha is currently disabled");
return Ok(HttpResponse::InternalServerError().json("Error"));
// This might block the thread a bit too long
let (answer, svg) = get_captcha();
// let id = rand_core::OsRng.next_u32() as i32;
// let cresponse = CaptchaResponse {
// captcha_svg: svg.clone(),
// captcha_id: id,
// };
// This is bad in about every way i can think of
// It might just be better to hit the database every time, and let the database
// handle rng and maybe set a trigger to delete old captchas
// match cstate.capthca_db.lock() {
// Ok(mut db) => {
// if (db.len() as i32) > 100 {
// // To prevent the database from growing too large
// // Replace with a proper LRU cache or circular buffer
// db.remove(&(id % 100)); // This is terrible
// }
// db.insert(id, answer.clone()); // We do not care about collisions
// return Ok(HttpResponse::Ok().json(cresponse));
// }
// Err(_) => {
// // This shouldnt happen
// error!("Failed to lock captcha database");
// return Ok(HttpResponse::InternalServerError().json("Error"));
// }
// }
}
/// Returns a new captcha in the form of a tuple (answer, svg)
fn get_captcha() -> (String, String) {
BiosvgBuilder::new()
.length(4)
.difficulty(6)
.colors(vec![
// Feel free to change these
"#0078D6".to_string(),
"#aa3333".to_string(),
"#f08012".to_string(),
"#33aa00".to_string(),
"#aa33aa".to_string(),
])
.build()
.unwrap()
}

View file

@ -1,124 +1,31 @@
use std::collections::BTreeSet;
use crate::types::Post;
use sqlx::Pool;
use sqlx::Sqlite;
use sqlx::{self, sqlite};
use std::collections::BTreeMap;
use std::sync::Arc;
use std::sync::Mutex;
use log::error;
use log::info;
use sqlx::postgres::PgPoolOptions;
use sqlx::PgPool;
#[derive(Clone)]
pub struct CaptchaState {
// pub capthca_db: Arc<Mutex<BTreeMap<i32, String>>>,
pub capthca_db: Arc<Mutex<BTreeSet<String>>>,
}
impl CaptchaState {
pub fn new() -> Self {
Self {
capthca_db: Arc::new(Mutex::new(BTreeSet::new())),
}
}
}
use uuid::Uuid;
#[derive(Clone)]
pub struct ServerState {
pub pool: PgPool,
pub posts: Arc<Mutex<BTreeMap<Uuid, Post>>>,
pub pool: Pool<Sqlite>,
}
impl ServerState {
pub async fn new() -> Self {
// This is almost certainly bad practice for more reasons than I can count
dotenvy::dotenv().ok();
let db_url = dotenvy::var("DATABASE_URL").unwrap_or_else(|_| {
error!("DATABASE_URL not set in environment!");
std::process::exit(1);
});
info!("Using db_url: {}", &db_url);
let pool = PgPoolOptions::new()
let pool = sqlite::SqlitePoolOptions::new()
.max_connections(5)
.connect(&db_url)
.connect(":memory:")
.await
.unwrap();
sqlx::migrate!("./migrations").run(&pool).await.unwrap();
match crate::db::db_new_user("imbus".to_string(), "kartellen1234".to_string(), &pool).await
{
Some(u) => info!("Created default user {}", u.username),
None => error!("Failed to create default user..."),
}
match crate::db::db_new_user("hollgy".to_string(), "yomomonpizza".to_string(), &pool).await
{
Some(u) => info!("Created default user {}", u.username),
None => error!("Failed to create default user..."),
}
match crate::db::db_new_user("demouser".to_string(), "demopw".to_string(), &pool).await {
Some(u) => info!("Created default user {}", u.username),
None => error!("Failed to create default user..."),
}
// We want dummy posts
lipsum_setup(&pool).await.unwrap();
#[cfg(debug_assertions)]
debug_setup(&pool).await.unwrap();
Self { pool }
}
}
// Inserts a bunch of dummy data into the database
// Mostly useful for debugging new posts, as we need to satisfy foreign key constraints.
#[cfg(debug_assertions)]
async fn debug_setup(pool: &PgPool) -> Result<(), sqlx::Error> {
use crate::db::db_new_user;
db_new_user("user".to_string(), "pass".to_string(), pool).await;
Ok(())
}
/// Inserts a bunch of dummy posts into the database
async fn lipsum_setup(pool: &PgPool) -> Result<(), sqlx::Error> {
use lipsum::lipsum;
use rand::prelude::*;
use sqlx::query;
// Fetch any user
let user_exist = query!("SELECT * FROM users",)
.fetch_one(pool)
.await
.ok()
.is_some();
if user_exist {
let mut rng = rand::thread_rng();
// Insert a 100 dummy posts.
// This requires that the user with id 1 exists in the user table
for _ in 0..100 {
query!(
"INSERT INTO posts (user_id, content) VALUES (1, $1)",
lipsum(rng.gen_range(10..100))
)
.execute(pool)
.await?;
Self {
posts: Arc::new(Mutex::new(BTreeMap::new())),
pool: pool,
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_server_state() {
let state = CaptchaState::new();
assert!(state.capthca_db.lock().unwrap().is_empty());
state.capthca_db.lock().unwrap().insert("test".to_string());
assert!(!state.capthca_db.lock().unwrap().is_empty());
}
}

40
server/src/types.rs Executable file
View file

@ -0,0 +1,40 @@
use serde::{Deserialize, Serialize};
use uuid::Uuid;
// The post as it is received from the client
#[derive(Debug, Serialize, Deserialize)]
pub struct NewPost {
content: String,
token: String,
}
// The post as it is stored in the database
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Post {
pub uuid: Uuid,
pub content: String,
pub votes: VoteCount,
}
impl From<NewPost> for Post {
fn from(post: NewPost) -> Self {
Self {
uuid: Uuid::new_v4(),
content: post.content,
votes: VoteCount::new(),
}
}
}
// Part of the post struct
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct VoteCount {
pub up: u32,
pub down: u32,
}
impl VoteCount {
fn new() -> Self {
Self { up: 0, down: 0 }
}
}

View file

@ -1,45 +0,0 @@
use serde::{Deserialize, Serialize};
/// The comment as it is received from the client
#[derive(Debug, Serialize, Deserialize)]
pub struct NewComment {
pub parent_post_id: i64,
pub parent_comment_id: Option<i64>,
pub user_token: String,
pub content: String,
}
/// The comment as it is stored in the database, with all the related metadata
#[derive(Debug, Serialize, Deserialize, Clone, sqlx::FromRow)]
pub struct Comment {
pub id: i64,
pub parent_post_id: i64,
pub parent_comment_id: Option<i64>,
pub author_user_id: i64,
pub upvotes: i64,
pub downvotes: i64,
pub content: String,
pub created_at: chrono::NaiveDateTime,
pub updated_at: chrono::NaiveDateTime,
}
/// This is the comment as it is sent to the client, with only the public metadata
#[derive(Debug, Serialize, Deserialize, Clone, sqlx::FromRow)]
pub struct PublicComment {
pub id: i64,
pub parent_post_id: i64,
pub parent_comment_id: Option<i64>,
pub upvotes: i64,
pub downvotes: i64,
pub content: String,
pub created_at: chrono::NaiveDateTime,
pub updated_at: chrono::NaiveDateTime,
}
/// Query parameters for the /comments endpoint
#[derive(Debug, Serialize, Deserialize)]
pub struct CommentQueryParams {
pub post_id: i64,
pub limit: Option<i64>,
pub offset: Option<i64>,
}

View file

@ -1,7 +0,0 @@
mod comment;
mod post;
mod user;
pub use comment::*;
pub use post::*;
pub use user::*;

View file

@ -1,42 +0,0 @@
use serde::{Deserialize, Serialize};
use sqlx::FromRow;
// The post as it is received from the client
// The token is used to identify the user
#[derive(Debug, Serialize, Deserialize)]
pub struct NewPost {
pub content: String,
pub token: String,
}
// The post as it is stored in the database, with all the related metadata
#[derive(Debug, Serialize, Deserialize, Clone, FromRow)]
pub struct Post {
pub id: i64,
pub user_id: i64,
pub content: String,
pub upvotes: i64,
pub downvotes: i64,
pub created_at: chrono::NaiveDateTime,
pub updated_at: chrono::NaiveDateTime,
}
// The post as it is sent to the client, with only the public metadata
#[derive(Debug, Serialize, Deserialize, Clone, FromRow)]
pub struct PublicPost {
pub id: i64,
pub content: String,
pub upvotes: i64,
pub downvotes: i64,
pub created_at: chrono::NaiveDateTime,
pub updated_at: chrono::NaiveDateTime,
}
// These look like /posts?limit=10&offset=20 in the URL
// Note that these are optional
/// Query parameters for the /posts endpoint
#[derive(Debug, Serialize, Deserialize)]
pub struct PostQueryParams {
pub limit: Option<i64>,
pub offset: Option<i64>,
}

View file

@ -1,42 +0,0 @@
use serde::{Deserialize, Serialize};
use sqlx::FromRow;
/// The user as it is stored in the database, with all the related metadata
#[derive(Debug, Serialize, Deserialize, Clone, FromRow)]
pub struct User {
pub id: i64,
pub username: String,
pub password: String,
pub created_at: chrono::NaiveDateTime,
pub updated_at: chrono::NaiveDateTime,
}
/// The data recieved from the login form
#[derive(Debug, Serialize, Deserialize)]
pub struct LoginData {
pub username: String,
pub password: String,
}
/// The data recieved from the registration form
#[derive(Debug, Serialize, Deserialize)]
pub struct RegisterData {
pub username: String,
pub password: String,
pub captcha: String,
}
/// The response sent to the client after a successful login or registration
#[derive(Debug, Serialize, Deserialize)]
pub struct AuthResponse {
pub username: String,
pub token: String,
}
/// Data sent to the client to render the captcha
/// The captcha_id is used to identify the captcha in the database
#[derive(Debug, Serialize, Deserialize)]
pub struct CaptchaResponse {
pub captcha_svg: String,
pub captcha_id: i32,
}

View file

@ -1,3 +0,0 @@
mod util;
pub use util::*;

View file

@ -1,18 +0,0 @@
#[allow(dead_code)]
use rand::Rng;
// This will do for now
pub fn hex_string(length: usize) -> String {
let mut rng = rand::thread_rng();
let mut bytes = vec![0u8; length];
rng.fill(&mut bytes[..]);
bytes.iter().map(|b| format!("{:X}", b)).collect::<String>()[..length].to_string()
}
mod tests {
#[test]
fn test_random_hex_string() {
let s = super::hex_string(16);
assert_eq!(s.len(), 16);
}
}