v1.0: First production version
This first version allows login of pre-existing users, creation and update of truths by admins, vote on the truths by users, their display as well as a simple graph for the vote results. Everything persisting in a SQLite database.
This commit is contained in:
commit
9911895b5b
22 changed files with 4790 additions and 0 deletions
4
.gitignore
vendored
Normal file
4
.gitignore
vendored
Normal file
|
@ -0,0 +1,4 @@
|
|||
/target
|
||||
**/.idea
|
||||
**.sqlite
|
||||
**.sqbpro
|
3268
Cargo.lock
generated
Normal file
3268
Cargo.lock
generated
Normal file
File diff suppressed because it is too large
Load diff
18
Cargo.toml
Normal file
18
Cargo.toml
Normal file
|
@ -0,0 +1,18 @@
|
|||
[package]
|
||||
name = "fabula_votes_server"
|
||||
license = "MPL-2.0"
|
||||
readme = "README.md"
|
||||
authors = ["trotFunky"]
|
||||
version = "1.0.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
rocket = { version = "0.5.1", features = ["secrets", "json"] }
|
||||
rocket_dyn_templates = { version = "0.2.0", features = ["tera"] }
|
||||
rocket_db_pools = {version = "0.2.0", features = ["sqlx_sqlite"]}
|
||||
sqlx = {version = "0.7.4", default-features = false, features = ["macros", "migrate"]}
|
||||
blake2 = "0.10.6"
|
||||
argon2 = "0.5.3"
|
||||
pulldown-cmark = "0.11.0"
|
373
LICENSE.md
Normal file
373
LICENSE.md
Normal file
|
@ -0,0 +1,373 @@
|
|||
Mozilla Public License Version 2.0
|
||||
==================================
|
||||
|
||||
1. Definitions
|
||||
--------------
|
||||
|
||||
1.1. "Contributor"
|
||||
means each individual or legal entity that creates, contributes to
|
||||
the creation of, or owns Covered Software.
|
||||
|
||||
1.2. "Contributor Version"
|
||||
means the combination of the Contributions of others (if any) used
|
||||
by a Contributor and that particular Contributor's Contribution.
|
||||
|
||||
1.3. "Contribution"
|
||||
means Covered Software of a particular Contributor.
|
||||
|
||||
1.4. "Covered Software"
|
||||
means Source Code Form to which the initial Contributor has attached
|
||||
the notice in Exhibit A, the Executable Form of such Source Code
|
||||
Form, and Modifications of such Source Code Form, in each case
|
||||
including portions thereof.
|
||||
|
||||
1.5. "Incompatible With Secondary Licenses"
|
||||
means
|
||||
|
||||
(a) that the initial Contributor has attached the notice described
|
||||
in Exhibit B to the Covered Software; or
|
||||
|
||||
(b) that the Covered Software was made available under the terms of
|
||||
version 1.1 or earlier of the License, but not also under the
|
||||
terms of a Secondary License.
|
||||
|
||||
1.6. "Executable Form"
|
||||
means any form of the work other than Source Code Form.
|
||||
|
||||
1.7. "Larger Work"
|
||||
means a work that combines Covered Software with other material, in
|
||||
a separate file or files, that is not Covered Software.
|
||||
|
||||
1.8. "License"
|
||||
means this document.
|
||||
|
||||
1.9. "Licensable"
|
||||
means having the right to grant, to the maximum extent possible,
|
||||
whether at the time of the initial grant or subsequently, any and
|
||||
all of the rights conveyed by this License.
|
||||
|
||||
1.10. "Modifications"
|
||||
means any of the following:
|
||||
|
||||
(a) any file in Source Code Form that results from an addition to,
|
||||
deletion from, or modification of the contents of Covered
|
||||
Software; or
|
||||
|
||||
(b) any new file in Source Code Form that contains any Covered
|
||||
Software.
|
||||
|
||||
1.11. "Patent Claims" of a Contributor
|
||||
means any patent claim(s), including without limitation, method,
|
||||
process, and apparatus claims, in any patent Licensable by such
|
||||
Contributor that would be infringed, but for the grant of the
|
||||
License, by the making, using, selling, offering for sale, having
|
||||
made, import, or transfer of either its Contributions or its
|
||||
Contributor Version.
|
||||
|
||||
1.12. "Secondary License"
|
||||
means either the GNU General Public License, Version 2.0, the GNU
|
||||
Lesser General Public License, Version 2.1, the GNU Affero General
|
||||
Public License, Version 3.0, or any later versions of those
|
||||
licenses.
|
||||
|
||||
1.13. "Source Code Form"
|
||||
means the form of the work preferred for making modifications.
|
||||
|
||||
1.14. "You" (or "Your")
|
||||
means an individual or a legal entity exercising rights under this
|
||||
License. For legal entities, "You" includes any entity that
|
||||
controls, is controlled by, or is under common control with You. For
|
||||
purposes of this definition, "control" means (a) the power, direct
|
||||
or indirect, to cause the direction or management of such entity,
|
||||
whether by contract or otherwise, or (b) ownership of more than
|
||||
fifty percent (50%) of the outstanding shares or beneficial
|
||||
ownership of such entity.
|
||||
|
||||
2. License Grants and Conditions
|
||||
--------------------------------
|
||||
|
||||
2.1. Grants
|
||||
|
||||
Each Contributor hereby grants You a world-wide, royalty-free,
|
||||
non-exclusive license:
|
||||
|
||||
(a) under intellectual property rights (other than patent or trademark)
|
||||
Licensable by such Contributor to use, reproduce, make available,
|
||||
modify, display, perform, distribute, and otherwise exploit its
|
||||
Contributions, either on an unmodified basis, with Modifications, or
|
||||
as part of a Larger Work; and
|
||||
|
||||
(b) under Patent Claims of such Contributor to make, use, sell, offer
|
||||
for sale, have made, import, and otherwise transfer either its
|
||||
Contributions or its Contributor Version.
|
||||
|
||||
2.2. Effective Date
|
||||
|
||||
The licenses granted in Section 2.1 with respect to any Contribution
|
||||
become effective for each Contribution on the date the Contributor first
|
||||
distributes such Contribution.
|
||||
|
||||
2.3. Limitations on Grant Scope
|
||||
|
||||
The licenses granted in this Section 2 are the only rights granted under
|
||||
this License. No additional rights or licenses will be implied from the
|
||||
distribution or licensing of Covered Software under this License.
|
||||
Notwithstanding Section 2.1(b) above, no patent license is granted by a
|
||||
Contributor:
|
||||
|
||||
(a) for any code that a Contributor has removed from Covered Software;
|
||||
or
|
||||
|
||||
(b) for infringements caused by: (i) Your and any other third party's
|
||||
modifications of Covered Software, or (ii) the combination of its
|
||||
Contributions with other software (except as part of its Contributor
|
||||
Version); or
|
||||
|
||||
(c) under Patent Claims infringed by Covered Software in the absence of
|
||||
its Contributions.
|
||||
|
||||
This License does not grant any rights in the trademarks, service marks,
|
||||
or logos of any Contributor (except as may be necessary to comply with
|
||||
the notice requirements in Section 3.4).
|
||||
|
||||
2.4. Subsequent Licenses
|
||||
|
||||
No Contributor makes additional grants as a result of Your choice to
|
||||
distribute the Covered Software under a subsequent version of this
|
||||
License (see Section 10.2) or under the terms of a Secondary License (if
|
||||
permitted under the terms of Section 3.3).
|
||||
|
||||
2.5. Representation
|
||||
|
||||
Each Contributor represents that the Contributor believes its
|
||||
Contributions are its original creation(s) or it has sufficient rights
|
||||
to grant the rights to its Contributions conveyed by this License.
|
||||
|
||||
2.6. Fair Use
|
||||
|
||||
This License is not intended to limit any rights You have under
|
||||
applicable copyright doctrines of fair use, fair dealing, or other
|
||||
equivalents.
|
||||
|
||||
2.7. Conditions
|
||||
|
||||
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
|
||||
in Section 2.1.
|
||||
|
||||
3. Responsibilities
|
||||
-------------------
|
||||
|
||||
3.1. Distribution of Source Form
|
||||
|
||||
All distribution of Covered Software in Source Code Form, including any
|
||||
Modifications that You create or to which You contribute, must be under
|
||||
the terms of this License. You must inform recipients that the Source
|
||||
Code Form of the Covered Software is governed by the terms of this
|
||||
License, and how they can obtain a copy of this License. You may not
|
||||
attempt to alter or restrict the recipients' rights in the Source Code
|
||||
Form.
|
||||
|
||||
3.2. Distribution of Executable Form
|
||||
|
||||
If You distribute Covered Software in Executable Form then:
|
||||
|
||||
(a) such Covered Software must also be made available in Source Code
|
||||
Form, as described in Section 3.1, and You must inform recipients of
|
||||
the Executable Form how they can obtain a copy of such Source Code
|
||||
Form by reasonable means in a timely manner, at a charge no more
|
||||
than the cost of distribution to the recipient; and
|
||||
|
||||
(b) You may distribute such Executable Form under the terms of this
|
||||
License, or sublicense it under different terms, provided that the
|
||||
license for the Executable Form does not attempt to limit or alter
|
||||
the recipients' rights in the Source Code Form under this License.
|
||||
|
||||
3.3. Distribution of a Larger Work
|
||||
|
||||
You may create and distribute a Larger Work under terms of Your choice,
|
||||
provided that You also comply with the requirements of this License for
|
||||
the Covered Software. If the Larger Work is a combination of Covered
|
||||
Software with a work governed by one or more Secondary Licenses, and the
|
||||
Covered Software is not Incompatible With Secondary Licenses, this
|
||||
License permits You to additionally distribute such Covered Software
|
||||
under the terms of such Secondary License(s), so that the recipient of
|
||||
the Larger Work may, at their option, further distribute the Covered
|
||||
Software under the terms of either this License or such Secondary
|
||||
License(s).
|
||||
|
||||
3.4. Notices
|
||||
|
||||
You may not remove or alter the substance of any license notices
|
||||
(including copyright notices, patent notices, disclaimers of warranty,
|
||||
or limitations of liability) contained within the Source Code Form of
|
||||
the Covered Software, except that You may alter any license notices to
|
||||
the extent required to remedy known factual inaccuracies.
|
||||
|
||||
3.5. Application of Additional Terms
|
||||
|
||||
You may choose to offer, and to charge a fee for, warranty, support,
|
||||
indemnity or liability obligations to one or more recipients of Covered
|
||||
Software. However, You may do so only on Your own behalf, and not on
|
||||
behalf of any Contributor. You must make it absolutely clear that any
|
||||
such warranty, support, indemnity, or liability obligation is offered by
|
||||
You alone, and You hereby agree to indemnify every Contributor for any
|
||||
liability incurred by such Contributor as a result of warranty, support,
|
||||
indemnity or liability terms You offer. You may include additional
|
||||
disclaimers of warranty and limitations of liability specific to any
|
||||
jurisdiction.
|
||||
|
||||
4. Inability to Comply Due to Statute or Regulation
|
||||
---------------------------------------------------
|
||||
|
||||
If it is impossible for You to comply with any of the terms of this
|
||||
License with respect to some or all of the Covered Software due to
|
||||
statute, judicial order, or regulation then You must: (a) comply with
|
||||
the terms of this License to the maximum extent possible; and (b)
|
||||
describe the limitations and the code they affect. Such description must
|
||||
be placed in a text file included with all distributions of the Covered
|
||||
Software under this License. Except to the extent prohibited by statute
|
||||
or regulation, such description must be sufficiently detailed for a
|
||||
recipient of ordinary skill to be able to understand it.
|
||||
|
||||
5. Termination
|
||||
--------------
|
||||
|
||||
5.1. The rights granted under this License will terminate automatically
|
||||
if You fail to comply with any of its terms. However, if You become
|
||||
compliant, then the rights granted under this License from a particular
|
||||
Contributor are reinstated (a) provisionally, unless and until such
|
||||
Contributor explicitly and finally terminates Your grants, and (b) on an
|
||||
ongoing basis, if such Contributor fails to notify You of the
|
||||
non-compliance by some reasonable means prior to 60 days after You have
|
||||
come back into compliance. Moreover, Your grants from a particular
|
||||
Contributor are reinstated on an ongoing basis if such Contributor
|
||||
notifies You of the non-compliance by some reasonable means, this is the
|
||||
first time You have received notice of non-compliance with this License
|
||||
from such Contributor, and You become compliant prior to 30 days after
|
||||
Your receipt of the notice.
|
||||
|
||||
5.2. If You initiate litigation against any entity by asserting a patent
|
||||
infringement claim (excluding declaratory judgment actions,
|
||||
counter-claims, and cross-claims) alleging that a Contributor Version
|
||||
directly or indirectly infringes any patent, then the rights granted to
|
||||
You by any and all Contributors for the Covered Software under Section
|
||||
2.1 of this License shall terminate.
|
||||
|
||||
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
|
||||
end user license agreements (excluding distributors and resellers) which
|
||||
have been validly granted by You or Your distributors under this License
|
||||
prior to termination shall survive termination.
|
||||
|
||||
************************************************************************
|
||||
* *
|
||||
* 6. Disclaimer of Warranty *
|
||||
* ------------------------- *
|
||||
* *
|
||||
* Covered Software is provided under this License on an "as is" *
|
||||
* basis, without warranty of any kind, either expressed, implied, or *
|
||||
* statutory, including, without limitation, warranties that the *
|
||||
* Covered Software is free of defects, merchantable, fit for a *
|
||||
* particular purpose or non-infringing. The entire risk as to the *
|
||||
* quality and performance of the Covered Software is with You. *
|
||||
* Should any Covered Software prove defective in any respect, You *
|
||||
* (not any Contributor) assume the cost of any necessary servicing, *
|
||||
* repair, or correction. This disclaimer of warranty constitutes an *
|
||||
* essential part of this License. No use of any Covered Software is *
|
||||
* authorized under this License except under this disclaimer. *
|
||||
* *
|
||||
************************************************************************
|
||||
|
||||
************************************************************************
|
||||
* *
|
||||
* 7. Limitation of Liability *
|
||||
* -------------------------- *
|
||||
* *
|
||||
* Under no circumstances and under no legal theory, whether tort *
|
||||
* (including negligence), contract, or otherwise, shall any *
|
||||
* Contributor, or anyone who distributes Covered Software as *
|
||||
* permitted above, be liable to You for any direct, indirect, *
|
||||
* special, incidental, or consequential damages of any character *
|
||||
* including, without limitation, damages for lost profits, loss of *
|
||||
* goodwill, work stoppage, computer failure or malfunction, or any *
|
||||
* and all other commercial damages or losses, even if such party *
|
||||
* shall have been informed of the possibility of such damages. This *
|
||||
* limitation of liability shall not apply to liability for death or *
|
||||
* personal injury resulting from such party's negligence to the *
|
||||
* extent applicable law prohibits such limitation. Some *
|
||||
* jurisdictions do not allow the exclusion or limitation of *
|
||||
* incidental or consequential damages, so this exclusion and *
|
||||
* limitation may not apply to You. *
|
||||
* *
|
||||
************************************************************************
|
||||
|
||||
8. Litigation
|
||||
-------------
|
||||
|
||||
Any litigation relating to this License may be brought only in the
|
||||
courts of a jurisdiction where the defendant maintains its principal
|
||||
place of business and such litigation shall be governed by laws of that
|
||||
jurisdiction, without reference to its conflict-of-law provisions.
|
||||
Nothing in this Section shall prevent a party's ability to bring
|
||||
cross-claims or counter-claims.
|
||||
|
||||
9. Miscellaneous
|
||||
----------------
|
||||
|
||||
This License represents the complete agreement concerning the subject
|
||||
matter hereof. If any provision of this License is held to be
|
||||
unenforceable, such provision shall be reformed only to the extent
|
||||
necessary to make it enforceable. Any law or regulation which provides
|
||||
that the language of a contract shall be construed against the drafter
|
||||
shall not be used to construe this License against a Contributor.
|
||||
|
||||
10. Versions of the License
|
||||
---------------------------
|
||||
|
||||
10.1. New Versions
|
||||
|
||||
Mozilla Foundation is the license steward. Except as provided in Section
|
||||
10.3, no one other than the license steward has the right to modify or
|
||||
publish new versions of this License. Each version will be given a
|
||||
distinguishing version number.
|
||||
|
||||
10.2. Effect of New Versions
|
||||
|
||||
You may distribute the Covered Software under the terms of the version
|
||||
of the License under which You originally received the Covered Software,
|
||||
or under the terms of any subsequent version published by the license
|
||||
steward.
|
||||
|
||||
10.3. Modified Versions
|
||||
|
||||
If you create software not governed by this License, and you want to
|
||||
create a new license for such software, you may create and use a
|
||||
modified version of this License if you rename the license and remove
|
||||
any references to the name of the license steward (except to note that
|
||||
such modified license differs from this License).
|
||||
|
||||
10.4. Distributing Source Code Form that is Incompatible With Secondary
|
||||
Licenses
|
||||
|
||||
If You choose to distribute Source Code Form that is Incompatible With
|
||||
Secondary Licenses under the terms of this version of the License, the
|
||||
notice described in Exhibit B of this License must be attached.
|
||||
|
||||
Exhibit A - Source Code Form License Notice
|
||||
-------------------------------------------
|
||||
|
||||
This Source Code Form is subject to the terms of the Mozilla Public
|
||||
License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
|
||||
If it is not possible or desirable to put the notice in a particular
|
||||
file, then You may include the notice in a location (such as a LICENSE
|
||||
file in a relevant directory) where a recipient would be likely to look
|
||||
for such a notice.
|
||||
|
||||
You may add additional accurate notices of copyright ownership.
|
||||
|
||||
Exhibit B - "Incompatible With Secondary Licenses" Notice
|
||||
---------------------------------------------------------
|
||||
|
||||
This Source Code Form is "Incompatible With Secondary Licenses", as
|
||||
defined by the Mozilla Public License, v. 2.0.
|
31
README.md
Normal file
31
README.md
Normal file
|
@ -0,0 +1,31 @@
|
|||
# Fabula Votes
|
||||
|
||||
This web application is intended as a simple way to share Truths for an upcoming campaign of [Fabula Ultima](https://need.games/fabula-ultima/),
|
||||
vote and who we think wrote them and see some stats !
|
||||
|
||||
# TODO
|
||||
|
||||
A list of things that could be implemented/added to the application, some of them are needed for "feature completeness" !
|
||||
|
||||
- [ ] Being able to change from one week to the next
|
||||
- [ ] Create new weeks for the admin
|
||||
- [ ] Proper week redirection
|
||||
- [ ] Add introduction to the weekly truths
|
||||
- [ ] Bundle static assets in the binary
|
||||
- [ ] Move the databse queries to their own functions
|
||||
- [ ] Cache those results
|
||||
- [ ] Centralize Markdown parsing ?
|
||||
- [ ] Use fairings for the different elements ?
|
||||
|
||||
# Dependencies
|
||||
|
||||
This project currently uses :
|
||||
- [Rocket](https://docs.rs/rocket/0.5.1/rocket/), for the web application backend
|
||||
- [SQLX](https://docs.rs/sqlx/0.7.4/sqlx/), for database access (this is only expeceted to be used with SQLite)
|
||||
- [Tera](https://docs.rs/tera/latest/tera/), for templating
|
||||
- [Argon2](https://docs.rs/argon2/latest/argon2/), for password hashing
|
||||
- [Pull_down CMark](https://docs.rs/pulldown-cmark/0.11.0/pulldown_cmark/), for markdown rendering
|
||||
|
||||
# License
|
||||
|
||||
The code present in this repository is licensed under the Mozilla Public License 2.0.
|
13
Rocket.toml
Normal file
13
Rocket.toml
Normal file
|
@ -0,0 +1,13 @@
|
|||
[default]
|
||||
template_dir = "templates"
|
||||
log_level = "normal"
|
||||
port = 24241
|
||||
|
||||
[debug]
|
||||
address = "0.0.0.0"
|
||||
|
||||
[release]
|
||||
address = "127.0.0.1"
|
||||
|
||||
[default.databases.data_sqlite]
|
||||
url = "./db/voting_data.sqlite"
|
35
db/00_create-tables.sql
Normal file
35
db/00_create-tables.sql
Normal file
|
@ -0,0 +1,35 @@
|
|||
CREATE TABLE IF NOT EXISTS Players (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
is_admin INTEGER NOT NULL DEFAULT 0,
|
||||
name VARCHAR NOT NULL,
|
||||
pwd_hash VARCHAR NOT NULL,
|
||||
picture VARCHAR
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS Truths (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
week INTEGER NOT NULL CHECK (week > 0),
|
||||
number INTEGER NOT NULL CHECK (number > 0),
|
||||
author_id INTEGER NOT NULL,
|
||||
rendered_text VARCHAR NOT NULL,
|
||||
raw_text VARCHAR NOT NULL,
|
||||
FOREIGN KEY (author_id) REFERENCES Players(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS Votes (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
truth_id INTEGER NOT NULL,
|
||||
voter_id INTEGER NOT NULL,
|
||||
voted_id INTEGER NOT NULL,
|
||||
FOREIGN KEY (truth_id) REFERENCES Truths(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (voter_id) REFERENCES Players(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (voted_id) REFERENCES Players(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS AuthTokens (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
player_id INTEGER NOT NULL,
|
||||
token VARCHAR NOT NULL,
|
||||
max_timestamp INTEGER NOT NULL,
|
||||
FOREIGN KEY (player_id) REFERENCES Players(id) ON DELETE CASCADE
|
||||
);
|
10
db/01_create-players.sql
Normal file
10
db/01_create-players.sql
Normal file
|
@ -0,0 +1,10 @@
|
|||
INSERT INTO Players (name, pwd_hash) VALUES ("Bystus", "$argon2id$v=19$m=4096,t=3,p=1$WXRDblJ3SGNQUUl1d0dyZFdwSzR2UT09$by9LM1LJ+geBhn6wvEzpiUsR7Tm7Ce9wIrqTTsbXyV0");
|
||||
INSERT INTO Players (name, pwd_hash) VALUES ("Corwyn", "$argon2id$v=19$m=4096,t=3,p=1$L2FNWW9BZUxPR0NTUEkwaGNib0xwZz09$x2pUo5IY0iq4xrzoXnHMEaX9oFGbkgaBFcnQ3EJ4Cts");
|
||||
INSERT INTO Players (name, pwd_hash) VALUES ("Dory", "$argon2id$v=19$m=4096,t=3,p=1$ekoxV1BrMDBIS1EzUC95SDRrVEZQZz09$Sv2xBUcNo8Ckm+tSiNjs1zBI7KGnCzNbd1ZEa3ABhmg");
|
||||
INSERT INTO Players (name, pwd_hash) VALUES ("Fen", "$argon2id$v=19$m=4096,t=3,p=1$d3pwaldqR2lNWThjZ0d5a29TNEh2Zz09$UsrRRUMdztOLoRJ/R7tP+YUl0EdCaeSYPImm7onlezM");
|
||||
INSERT INTO Players (name, pwd_hash) VALUES ("Lucky", "$argon2id$v=19$m=4096,t=3,p=1$dmZ2ZDNmUi9PaTBIOVFoQ0IvZ2JzUT09$agitRdj8VQS9oseMq7CHw3grugQ5u10L/k13KK1cZew");
|
||||
INSERT INTO Players (name, pwd_hash) VALUES ("Nico", "$argon2id$v=19$m=4096,t=3,p=1$K0Flb1BFb1czMEhtandLTjNGbDg5UT09$HNswLN3GsvOpBfQ6Ik/q9422XnguN4Pp9dMBWlwMmPU");
|
||||
INSERT INTO Players (name, pwd_hash) VALUES ("Peran", "$argon2id$v=19$m=4096,t=3,p=1$eUNTVlVvRjloekpXemZwUUMxb1p0QT09$DrtCsJ8Ok6Sid0YeWs82/XCjni7xqAslnVIo7npNB3k");
|
||||
INSERT INTO Players (name, pwd_hash) VALUES ("trot", "$argon2id$v=19$m=4096,t=3,p=1$dHdnVDdIMUpqdFJhYnAyc2NnYms1Zz09$H36JGR1/gvF0buJ+6+A5fyqncAqxixV1gGceF8sz/PE");
|
||||
|
||||
UPDATE Players SET is_admin = 1 WHERE name == "Corwyn";
|
21
db/02_create-dummy-truths.sql
Normal file
21
db/02_create-dummy-truths.sql
Normal file
|
@ -0,0 +1,21 @@
|
|||
--INSERT INTO Truths (week, number, rendered_text, raw_text, author_id) VALUES (1, 1,
|
||||
-- "This is a bit of bullshit that might be a looooot of bullshit, like, fucking hell, a lot.",
|
||||
-- "This is a bit of bullshit that might be a looooot of bullshit, like, fucking hell, a lot.", 1);
|
||||
--INSERT INTO Truths (week, number, rendered_text, raw_text, author_id) VALUES (1, 6,
|
||||
-- "This one, small one",
|
||||
-- "This one, small one", 4);
|
||||
--INSERT INTO Truths (week, number, rendered_text, raw_text, author_id) VALUES (1, 3,
|
||||
-- "At the time of writing, the share price is down more than 19 percent as the security shop to some of the biggest organizations in the world continues to work through issues with its customers.",
|
||||
-- "At the time of writing, the share price is down more than 19 percent as the security shop to some of the biggest organizations in the world continues to work through issues with its customers.", 5);
|
||||
--INSERT INTO Truths (week, number, rendered_text, raw_text, author_id) VALUES (1, 4,
|
||||
-- "Les récentes recherches démontrent qu’une civilisation perdue aurait développée une technologie fonctionnant à base de cristaux de mana élémentaires. Les outils actuels sont limités quand à l’utilisation de ces derniers mais nul doute que si l’on parvenait à les utiliser le monde entier subirait une révolution technologique. ",
|
||||
-- "Les récentes recherches démontrent qu’une civilisation perdue aurait développée une technologie fonctionnant à base de cristaux de mana élémentaires. Les outils actuels sont limités quand à l’utilisation de ces derniers mais nul doute que si l’on parvenait à les utiliser le monde entier subirait une révolution technologique. ", 3);
|
||||
--INSERT INTO Truths (week, number, rendered_text, raw_text, author_id) VALUES (1, 5,
|
||||
-- "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec aliquet egestas lacus at posuere. Donec quis laoreet lacus. Curabitur aliquam pharetra ligula vestibulum lacinia. Donec vitae elit venenatis, interdum lacus a, lobortis sem. Aliquam non dictum velit, at sagittis ex. Duis vestibulum nisi vitae mattis posuere. Integer rutrum accumsan diam. Cras cursus sapien tempus, bibendum metus et, scelerisque erat. Etiam eleifend vitae nunc vel pretium. Ut ipsum risus, consequat ac orci a, varius aliquam sapien. Integer ut elit bibendum, bibendum dui ac, maximus lacus. Aenean scelerisque sapien id tincidunt euismod. Morbi placerat, massa ac vehicula congue, mi sem eleifend diam, id consequat mauris nibh non neque. Integer et lacus leo. Aliquam hendrerit facilisis arcu at auctor. ",
|
||||
-- "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec aliquet egestas lacus at posuere. Donec quis laoreet lacus. Curabitur aliquam pharetra ligula vestibulum lacinia. Donec vitae elit venenatis, interdum lacus a, lobortis sem. Aliquam non dictum velit, at sagittis ex. Duis vestibulum nisi vitae mattis posuere. Integer rutrum accumsan diam. Cras cursus sapien tempus, bibendum metus et, scelerisque erat. Etiam eleifend vitae nunc vel pretium. Ut ipsum risus, consequat ac orci a, varius aliquam sapien. Integer ut elit bibendum, bibendum dui ac, maximus lacus. Aenean scelerisque sapien id tincidunt euismod. Morbi placerat, massa ac vehicula congue, mi sem eleifend diam, id consequat mauris nibh non neque. Integer et lacus leo. Aliquam hendrerit facilisis arcu at auctor. ", 6);
|
||||
--INSERT INTO Truths (week, number, rendered_text, raw_text, author_id) VALUES (1, 2,
|
||||
-- "And another one ! And another one ! And another one ! And another one ! And another one ! And another one ! And another one ! And another one !",
|
||||
-- "And another one ! And another one ! And another one ! And another one ! And another one ! And another one ! And another one ! And another one !", 8);
|
||||
--INSERT INTO Truths (week, number, rendered_text, raw_text, author_id) VALUES (1, 7,
|
||||
-- "Sure <b>why not</b> use emojis 🍌 and tags",
|
||||
-- "Sure *why not* use emojis 🍌 and tags", 7);
|
201
src/auth.rs
Normal file
201
src/auth.rs
Normal file
|
@ -0,0 +1,201 @@
|
|||
use rocket::http::CookieJar;
|
||||
use rocket::serde::{Deserialize, Serialize};
|
||||
use rocket::form::Form;
|
||||
use rocket::response::Redirect;
|
||||
use rocket_db_pools::{sqlx, sqlx::Row, Connection};
|
||||
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
use argon2::{Argon2, PasswordHash, PasswordVerifier};
|
||||
use blake2::{Blake2b512, Digest};
|
||||
use blake2::digest::FixedOutput;
|
||||
use sqlx::Error;
|
||||
use crate::database_records::{AuthTokens, PlayerLoginInfo, Vote};
|
||||
use crate::database;
|
||||
use database::Db;
|
||||
|
||||
// TODO: Make FromRequest guard https://api.rocket.rs/v0.5/rocket/request/trait.FromRequest and split admin
|
||||
#[derive(Deserialize, Serialize)]
|
||||
#[serde(crate = "rocket::serde")]
|
||||
pub struct User {
|
||||
pub logged_in: bool,
|
||||
pub is_admin: bool,
|
||||
pub id: u16,
|
||||
pub name: String,
|
||||
pub has_week_vote: bool,
|
||||
pub votes: Vec<Vote>
|
||||
}
|
||||
|
||||
pub async fn get_user(week: u8, db: &mut Connection<Db>, cookies: &CookieJar<'_>) -> User {
|
||||
let auth_token: Option<String> = match cookies.get_private("auth_token") {
|
||||
Some(cookie) => Some(cookie.value().to_string()),
|
||||
None => None
|
||||
};
|
||||
let auth_id: Option<String> = match cookies.get_private("auth_id") {
|
||||
Some(cookie) => Some(cookie.value().to_string()),
|
||||
None => None
|
||||
};
|
||||
|
||||
let current_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Non monotonous time event").as_secs();
|
||||
match sqlx::query("DELETE FROM AuthTokens WHERE max_timestamp < $1;")
|
||||
.bind(current_time as i64)
|
||||
.fetch_optional(&mut ***db).await {
|
||||
Ok(_) => debug!("Cleaned up old tokens"),
|
||||
Err(error) => error!("Error while cleaning up old tokens : {error}"),
|
||||
};
|
||||
|
||||
let id_str;
|
||||
|
||||
let mut logged_in: bool = if auth_token.is_some() && auth_id.is_some() {
|
||||
id_str = auth_id.unwrap().to_string();
|
||||
let token_str = auth_token.unwrap().to_string();
|
||||
let tokens: Vec::<AuthTokens> = match sqlx::query_as("SELECT token FROM AuthTokens WHERE player_id == $1")
|
||||
.bind(&id_str)
|
||||
.fetch_all(&mut ***db).await {
|
||||
Ok(auth_tokens) => {auth_tokens},
|
||||
Err(error) => {
|
||||
error!("Failed to fetch auth tokens for {:?} : {error}", &id_str);
|
||||
Vec::<AuthTokens>::new()
|
||||
}
|
||||
};
|
||||
tokens.iter().find(|auth_token| {println!("Token : {:?}\nCookie : {:?}", auth_token.token, token_str); auth_token.token.eq(&token_str)}).is_some()
|
||||
} else {
|
||||
id_str = String::new();
|
||||
false
|
||||
};
|
||||
// Consider the user authentified now, but revert in case of an error.
|
||||
|
||||
let (name, is_admin): (String, bool) = if logged_in {
|
||||
match sqlx::query("SELECT name, is_admin FROM Players WHERE id == $1")
|
||||
.bind(&id_str)
|
||||
.fetch_one(&mut ***db)
|
||||
.await {
|
||||
Ok(row) => match (row.try_get(0).ok().unwrap(), row.try_get(1).ok().unwrap()) {
|
||||
(Some(name), Some(admin)) => (name, admin),
|
||||
_ => {
|
||||
error!("Invalid return to retrieve user name and admin status");
|
||||
logged_in = false;
|
||||
(String::new(), false)
|
||||
}
|
||||
},
|
||||
Err(error) => {
|
||||
error!("Error while retrieving user name : {error}");
|
||||
logged_in = false;
|
||||
(String::new(), false)
|
||||
},
|
||||
}
|
||||
} else {
|
||||
(String::new(), false)
|
||||
};
|
||||
|
||||
let votes: Vec<Vote> = if logged_in {
|
||||
sqlx::query_as("SELECT Votes.* FROM Votes JOIN Truths ON Votes.truth_id == Truths.id AND Truths.week == $1 WHERE voter_id == $2 ORDER BY Truths.number;")
|
||||
.bind(week)
|
||||
.bind(&id_str)
|
||||
.fetch_all(&mut ***db).await.unwrap_or_else(|error| {
|
||||
error!("Error while getting votes : {error}");
|
||||
Vec::<Vote>::new()
|
||||
})
|
||||
} else {
|
||||
Vec::<Vote>::new()
|
||||
};
|
||||
|
||||
if logged_in {
|
||||
User {
|
||||
logged_in,
|
||||
is_admin,
|
||||
id: id_str.parse::<u16>().unwrap(),
|
||||
name,
|
||||
has_week_vote: if votes.is_empty() { false } else { true },
|
||||
votes
|
||||
}
|
||||
} else {
|
||||
User {
|
||||
logged_in,
|
||||
is_admin: false,
|
||||
id: 0,
|
||||
name,
|
||||
has_week_vote: false,
|
||||
votes
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(FromForm)]
|
||||
pub struct AuthForm {
|
||||
name: String,
|
||||
password: String
|
||||
}
|
||||
|
||||
#[post("/login", data="<form>")]
|
||||
pub async fn login(form: Form<AuthForm>, mut db: Connection<Db>, cookies: &CookieJar<'_>) -> Redirect {
|
||||
let user_search: Result<PlayerLoginInfo, _> = sqlx::query_as("SELECT id, is_admin, name, pwd_hash FROM Players WHERE name == $1")
|
||||
.bind(&form.name)
|
||||
.fetch_one(&mut **db)
|
||||
.await;
|
||||
|
||||
if user_search.is_err() {
|
||||
error!("Login failed : invalid user {:?}, err: {:?}", form.name, user_search.err());
|
||||
cookies.add(("toast_error", "Impossible de se connecter !"));
|
||||
return Redirect::to(uri!("/"));
|
||||
}
|
||||
let new_user = user_search.unwrap();
|
||||
|
||||
let password_hash_parse = PasswordHash::new(new_user.pwd_hash.as_str());
|
||||
if password_hash_parse.is_err() {
|
||||
error!("Login failed : could not parse password hash {:?}", password_hash_parse.err());
|
||||
cookies.add(("toast_error", "Impossible de se connecter !"));
|
||||
return Redirect::to(uri!("/"));
|
||||
}
|
||||
let password_hash = password_hash_parse.unwrap();
|
||||
|
||||
match Argon2::default().verify_password(form.password.as_bytes(), &password_hash) {
|
||||
Ok(_) => {
|
||||
let token_creation_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Non monotonous time event").as_secs();
|
||||
// Generate some kind of authentication token.
|
||||
let mut hasher = Blake2b512::new();
|
||||
hasher.update(new_user.id.to_le_bytes());
|
||||
hasher.update(token_creation_time.to_le_bytes());
|
||||
let hash = hasher.finalize_fixed().to_ascii_lowercase();
|
||||
let hash_str = String::from_utf8_lossy(hash.as_slice()).to_ascii_lowercase();
|
||||
|
||||
match sqlx::query("INSERT INTO AuthTokens (player_id, token, max_timestamp) VALUES ($1, $2, $3);")
|
||||
.bind(new_user.id)
|
||||
.bind(hash_str.clone())
|
||||
.bind((token_creation_time + 3628800) as i64) // Should be a while until we overflow to the 64th bit...
|
||||
.fetch_optional(&mut **db)
|
||||
.await {
|
||||
Ok(_) => {}
|
||||
Err(error) => {
|
||||
error!("Login failed : coult not store auth token in database : {error}");
|
||||
cookies.add(("toast_error", "Impossible de se connecter !"));
|
||||
return Redirect::to(uri!("/"));
|
||||
}
|
||||
}
|
||||
|
||||
cookies.add_private(("auth_token", hash_str.clone()));
|
||||
cookies.add_private(("auth_id", new_user.id.to_string()));
|
||||
}
|
||||
Err(err) => {
|
||||
error!("Login failed : invalid password for {:?}\nError : {err}", new_user.name);
|
||||
cookies.add(("toast_error", "Impossible de se connecter !"));
|
||||
return Redirect::to(uri!("/"));
|
||||
}
|
||||
}
|
||||
|
||||
Redirect::to(uri!("/"))
|
||||
}
|
||||
|
||||
pub fn bypass_auth_debug(cookies: &CookieJar<'_>) {
|
||||
if cookies.get_private("auth_token").is_some() {
|
||||
return
|
||||
}
|
||||
let mut hasher = Blake2b512::new();
|
||||
hasher.update(b"8");
|
||||
hasher.update(SystemTime::now().duration_since(UNIX_EPOCH).expect("Non monotonous time event").as_secs().to_le_bytes());
|
||||
let hash = hasher.finalize_fixed().to_ascii_lowercase();
|
||||
let hash_str = String::from_utf8_lossy(hash.as_slice()).to_ascii_lowercase();
|
||||
cookies.add_private(("auth_token", hash_str.clone()));
|
||||
cookies.add_private(("auth_id", 8.to_string()));
|
||||
|
||||
println!("Generated hash string : {hash_str}");
|
||||
}
|
26
src/database.rs
Normal file
26
src/database.rs
Normal file
|
@ -0,0 +1,26 @@
|
|||
use rocket::{Build, fairing, Rocket};
|
||||
use rocket::fairing::AdHoc;
|
||||
use rocket_db_pools::Database;
|
||||
|
||||
#[derive(Database)]
|
||||
#[database("data_sqlite")]
|
||||
pub struct Db(sqlx::SqlitePool);
|
||||
async fn run_migrations(rocket: Rocket<Build>) -> fairing::Result {
|
||||
match Db::fetch(&rocket) {
|
||||
Some(db) => match sqlx::migrate!("./db").run(&**db).await {
|
||||
Ok(_) => Ok(rocket),
|
||||
Err(e) => {
|
||||
error!("Failed to initialize SQLx database: {}", e);
|
||||
Err(rocket)
|
||||
}
|
||||
}
|
||||
None => Err(rocket),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn stage() -> AdHoc {
|
||||
AdHoc::on_ignite("SQLx Stage", |rocket| async {
|
||||
rocket.attach(Db::init())
|
||||
.attach(AdHoc::try_on_ignite("SQLx Migrations", run_migrations))
|
||||
})
|
||||
}
|
60
src/database_records.rs
Normal file
60
src/database_records.rs
Normal file
|
@ -0,0 +1,60 @@
|
|||
use rocket::serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(sqlx::FromRow, Deserialize, Serialize)]
|
||||
#[serde(crate = "rocket::serde")]
|
||||
pub struct Player {
|
||||
id: u16,
|
||||
name: String,
|
||||
}
|
||||
|
||||
#[derive(sqlx::FromRow, Deserialize, Serialize)]
|
||||
#[serde(crate = "rocket::serde")]
|
||||
pub struct PlayerLoginInfo {
|
||||
pub id: u16,
|
||||
pub is_admin: bool,
|
||||
pub name: String,
|
||||
pub pwd_hash: String,
|
||||
}
|
||||
|
||||
#[derive(sqlx::FromRow, Deserialize, Serialize)]
|
||||
#[serde(crate = "rocket::serde")]
|
||||
pub struct Truth {
|
||||
id: u32,
|
||||
week: u8,
|
||||
number: u8,
|
||||
author_id: u16,
|
||||
rendered_text: String,
|
||||
raw_text: String,
|
||||
}
|
||||
|
||||
#[derive(sqlx::FromRow, Deserialize, Serialize)]
|
||||
#[serde(crate = "rocket::serde")]
|
||||
pub struct DisplayTruth {
|
||||
id: u32,
|
||||
number: u8,
|
||||
author_id: u16,
|
||||
rendered_text: String,
|
||||
}
|
||||
|
||||
#[derive(sqlx::FromRow, Deserialize, Serialize)]
|
||||
#[serde(crate = "rocket::serde")]
|
||||
pub struct Vote {
|
||||
pub id: u32,
|
||||
pub truth_id: u32,
|
||||
pub voter_id: u16,
|
||||
pub voted_id: u16
|
||||
}
|
||||
|
||||
#[derive(sqlx::FromRow, Deserialize, Serialize)]
|
||||
#[serde(crate = "rocket::serde")]
|
||||
pub struct VotingData {
|
||||
pub votes_for: String,
|
||||
pub truth_number: u8,
|
||||
pub votes: u8
|
||||
}
|
||||
|
||||
#[derive(sqlx::FromRow, Deserialize, Serialize)]
|
||||
#[serde(crate = "rocket::serde")]
|
||||
pub struct AuthTokens {
|
||||
pub token: String,
|
||||
}
|
102
src/main.rs
Normal file
102
src/main.rs
Normal file
|
@ -0,0 +1,102 @@
|
|||
#[macro_use] extern crate rocket;
|
||||
|
||||
use rocket::{Rocket, Build, futures};
|
||||
use rocket::fs::{FileServer, relative};
|
||||
use rocket::http::CookieJar;
|
||||
use rocket::response::Redirect;
|
||||
use rocket::serde::{Serialize, Deserialize, json::Json};
|
||||
|
||||
use rocket_dyn_templates::{Template, context};
|
||||
|
||||
use rocket_db_pools::{sqlx, sqlx::Row, Database, Connection};
|
||||
|
||||
mod database_records;
|
||||
mod auth;
|
||||
mod vote;
|
||||
mod truth;
|
||||
|
||||
mod database;
|
||||
use database::Db;
|
||||
use database_records::*;
|
||||
use auth::User;
|
||||
|
||||
#[get("/<week_number>")]
|
||||
async fn week(week_number: u8, mut db: Connection<Db>, cookies: &CookieJar<'_>) -> Template {
|
||||
let user: User = auth::get_user(week_number, &mut db, cookies).await;
|
||||
|
||||
let other_players = if user.logged_in {
|
||||
match sqlx::query_as("SELECT id, name FROM Players WHERE id <> $1 AND is_admin == 0 ORDER BY name")
|
||||
.bind(user.id)
|
||||
.fetch_all(&mut **db).await {
|
||||
Ok(v) => v,
|
||||
Err(error) => {
|
||||
println!("Some error while getting players : {error}");
|
||||
Vec::<Player>::new()
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Vec::<Player>::new()
|
||||
};
|
||||
|
||||
// FIXME : This is fucking *trash* but fucking hell mate
|
||||
if user.is_admin {
|
||||
let truths: Vec<Truth> = match sqlx::query_as("SELECT * FROM Truths WHERE week == $1 ORDER BY number")
|
||||
.bind(week_number)
|
||||
.fetch_all(&mut **db).await {
|
||||
Ok(v) => v,
|
||||
Err(error) => {
|
||||
error!("Error while getting truths : {error}");
|
||||
Vec::<Truth>::new()
|
||||
}
|
||||
};
|
||||
|
||||
Template::render("index", context! {
|
||||
week_number: week_number,
|
||||
truths: truths,
|
||||
user: user,
|
||||
other_players: other_players,
|
||||
})
|
||||
} else {
|
||||
let truths: Vec<DisplayTruth> = match sqlx::query_as("SELECT id, number, author_id, rendered_text FROM Truths WHERE week == $1 ORDER BY number")
|
||||
.bind(week_number)
|
||||
.fetch_all(&mut **db).await {
|
||||
Ok(v) => v,
|
||||
Err(error) => {
|
||||
error!("Error while getting truths : {error}");
|
||||
Vec::<DisplayTruth>::new()
|
||||
}
|
||||
};
|
||||
|
||||
Template::render("index", context! {
|
||||
week_number: week_number,
|
||||
truths: truths,
|
||||
user: user,
|
||||
other_players: other_players,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[get("/")]
|
||||
async fn index(mut db: Connection<Db>) -> Redirect {
|
||||
let current_week: u8 = match sqlx::query("SELECT max(week) AS last_week FROM Truths;")
|
||||
.fetch_one(&mut **db).await {
|
||||
Ok(v) => v.try_get(0).ok().unwrap_or_else(|| 1), // If error, go back to 1
|
||||
Err(error) => {
|
||||
error!("Error while getting current week : {error:?}");
|
||||
1
|
||||
}
|
||||
};
|
||||
|
||||
Redirect::to(uri!("/", week(week_number = if current_week == 0 {1} else {current_week})))
|
||||
}
|
||||
|
||||
#[launch]
|
||||
fn rocket() -> _ {
|
||||
rocket::build()
|
||||
.mount("/", FileServer::from(relative!("static_files")))
|
||||
.mount("/", routes![index, vote::fetch_vote_data, vote::vote, truth::create_truth, truth::edit_truth, week, auth::login])
|
||||
.attach(database::stage())
|
||||
.attach(Template::fairing())
|
||||
}
|
||||
|
||||
// TODO: Random Row ID
|
112
src/truth.rs
Normal file
112
src/truth.rs
Normal file
|
@ -0,0 +1,112 @@
|
|||
use rocket::form::Form;
|
||||
use rocket::http::CookieJar;
|
||||
use rocket::response::Redirect;
|
||||
|
||||
use rocket_db_pools::{sqlx, Connection};
|
||||
|
||||
use pulldown_cmark::{Parser, Options};
|
||||
use sqlx::Row;
|
||||
use crate::{auth, database};
|
||||
|
||||
#[derive(FromForm)]
|
||||
pub struct TruthUpdateForm {
|
||||
truth_raw_text: String,
|
||||
truth_author: u8,
|
||||
}
|
||||
|
||||
#[post("/<week>/edit/<truth_number>", data="<form>")]
|
||||
pub async fn edit_truth(week: u8, truth_number: u8, form: Form<TruthUpdateForm>,
|
||||
mut db: Connection<database::Db>, cookies: &CookieJar<'_>) -> Redirect {
|
||||
let user = auth::get_user(week, &mut db, cookies).await;
|
||||
if !user.is_admin {
|
||||
cookies.add(("toast_error", "Vous n'avez pas la permission de changer la vérité."));
|
||||
return Redirect::to(uri!("/"));
|
||||
}
|
||||
|
||||
let mut options = Options::empty();
|
||||
options.insert(Options::ENABLE_STRIKETHROUGH);
|
||||
options.insert(Options::ENABLE_FOOTNOTES);
|
||||
options.insert(Options::ENABLE_MATH);
|
||||
options.insert(Options::ENABLE_TABLES);
|
||||
let markdown_parser = Parser::new_ext(form.truth_raw_text.as_str(), options);
|
||||
|
||||
let mut rendered_markdown = String::new();
|
||||
pulldown_cmark::html::push_html(&mut rendered_markdown, markdown_parser);
|
||||
|
||||
match sqlx::query("UPDATE Truths SET raw_text = $1, rendered_text = $2, author_id = $3 WHERE week == $4 AND number == $5;")
|
||||
.bind(&form.truth_raw_text)
|
||||
.bind(rendered_markdown)
|
||||
.bind(form.truth_author)
|
||||
.bind(week)
|
||||
.bind(truth_number)
|
||||
.fetch_optional(&mut **db)
|
||||
.await {
|
||||
Ok(_) => {
|
||||
debug!("Truth successfully updated")
|
||||
}
|
||||
Err(error) => {
|
||||
error!("Error while updating truth {truth_number} from week {week} : {error}");
|
||||
cookies.add(("toast_error", "Il y a eu un problème lors du changement de la vérité"));
|
||||
}
|
||||
};
|
||||
|
||||
Redirect::to(uri!("/"))
|
||||
}
|
||||
|
||||
#[post("/<week>/new", data="<form>")]
|
||||
pub async fn create_truth(week: u8, form: Form<TruthUpdateForm>,
|
||||
mut db: Connection<database::Db>, cookies: &CookieJar<'_>) -> Redirect {
|
||||
let user = auth::get_user(week, &mut db, cookies).await;
|
||||
if !user.is_admin {
|
||||
cookies.add(("toast_error", "Vous n'avez pas la permission d'ajouter de vérité."));
|
||||
return Redirect::to(uri!("/"));
|
||||
}
|
||||
|
||||
let truth_number: u8 = match sqlx::query("SELECT max(number) from Truths WHERE week == $1;")
|
||||
.bind(week)
|
||||
.fetch_one(&mut **db)
|
||||
.await {
|
||||
Ok(row) => match row.try_get::<u8, usize>(0).ok() {
|
||||
Some(max_truth_number) => max_truth_number+1,
|
||||
None => 0
|
||||
},
|
||||
Err(_) => 1 // If we can't fetch a row, this is the first one.
|
||||
};
|
||||
|
||||
if truth_number == 0 {
|
||||
error!("Error while getting max truth number.");
|
||||
cookies.add(("toast_error", "Erreur lors de l'ajout de la vérité..."));
|
||||
return Redirect::to(uri!("/"));
|
||||
}
|
||||
|
||||
let mut options = Options::empty();
|
||||
options.insert(Options::ENABLE_STRIKETHROUGH);
|
||||
options.insert(Options::ENABLE_FOOTNOTES);
|
||||
options.insert(Options::ENABLE_MATH);
|
||||
options.insert(Options::ENABLE_TABLES);
|
||||
let markdown_parser = Parser::new_ext(form.truth_raw_text.as_str(), options);
|
||||
|
||||
let mut rendered_markdown = String::new();
|
||||
pulldown_cmark::html::push_html(&mut rendered_markdown, markdown_parser);
|
||||
|
||||
match sqlx::query("INSERT INTO Truths (week, number, rendered_text, raw_text, author_id) VALUES ($1, $2, $3, $4, $5);")
|
||||
.bind(week)
|
||||
.bind(truth_number)
|
||||
.bind(rendered_markdown)
|
||||
.bind(&form.truth_raw_text)
|
||||
.bind(form.truth_author)
|
||||
.fetch_optional(&mut **db)
|
||||
.await {
|
||||
Ok(_) => {
|
||||
debug!("Truth successfully updated")
|
||||
}
|
||||
Err(error) => {
|
||||
error!("Error while creating truth {truth_number} from week {week} : {error}");
|
||||
cookies.add(("toast_error", "Il y a eu un problème lors du changement de la vérité"));
|
||||
}
|
||||
};
|
||||
|
||||
debug!("Truth was successfully added");
|
||||
|
||||
Redirect::to(uri!("/"))
|
||||
}
|
150
src/vote.rs
Normal file
150
src/vote.rs
Normal file
|
@ -0,0 +1,150 @@
|
|||
use std::collections::hash_map::Entry;
|
||||
use std::collections::HashMap;
|
||||
use rocket::fairing::AdHoc;
|
||||
use rocket::form::Form;
|
||||
use rocket::http::CookieJar;
|
||||
use rocket::response::Redirect;
|
||||
use rocket::serde::{Serialize, Deserialize};
|
||||
use rocket::serde::json::Json;
|
||||
|
||||
use rocket_db_pools::{sqlx, Connection};
|
||||
|
||||
use crate::{auth, database};
|
||||
use crate::database::Db;
|
||||
use crate::database_records::{Vote, VotingData};
|
||||
|
||||
#[derive(FromForm)]
|
||||
pub struct VoteForm {
|
||||
truth_votes: HashMap<u32, u16>
|
||||
}
|
||||
|
||||
#[post("/<week>/vote", data="<form>")]
|
||||
pub async fn vote(week: u8, form: Form<VoteForm>,
|
||||
mut db: Connection<database::Db>, cookies: &CookieJar<'_>) -> Redirect {
|
||||
let user = auth::get_user(week, &mut db, cookies).await;
|
||||
|
||||
if !user.logged_in {
|
||||
cookies.add(("toast_error", "Vous n'avez pas la permission de changer de vote."));
|
||||
return Redirect::to(uri!("/"));
|
||||
}
|
||||
|
||||
let filtered_votes = form.truth_votes.iter().filter_map(
|
||||
|vote| {
|
||||
if *vote.1 != 0 {
|
||||
Some(vote)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
let mut had_error = false;
|
||||
for (truth_id, voted_id) in filtered_votes {
|
||||
match user.votes.iter().find(|vote: &&Vote| {vote.truth_id == *truth_id}) {
|
||||
Some(vote) => {
|
||||
if *voted_id == vote.voted_id {
|
||||
continue;
|
||||
}
|
||||
debug!("Player {:?} updating vote {:?} for truth {truth_id} : \n\t\
|
||||
Previously voted {:?}, now voted {voted_id}", user.id, vote.id, vote.voted_id);
|
||||
match sqlx::query("UPDATE Votes SET voted_id = $3 WHERE truth_id == $1 AND voter_id == $2;")
|
||||
.bind(truth_id)
|
||||
.bind(user.id)
|
||||
.bind(voted_id)
|
||||
.fetch_optional(&mut **db)
|
||||
.await {
|
||||
Ok(_) => {}
|
||||
Err(error) => {
|
||||
error!("Error while submitting a vote : {error}");
|
||||
had_error = true;
|
||||
}
|
||||
};
|
||||
}
|
||||
None => {
|
||||
debug!("Player {:?} voting {voted_id} for truth {truth_id}", user.id);
|
||||
// TODO: Find a way to use only one statement ?
|
||||
// Cannot all launch and await because all connect to DB
|
||||
match sqlx::query("INSERT INTO Votes (truth_id, voter_id, voted_id) VALUES ($1, $2, $3);")
|
||||
.bind(truth_id)
|
||||
.bind(user.id)
|
||||
.bind(voted_id)
|
||||
.fetch_optional(&mut **db)
|
||||
.await {
|
||||
Ok(_) => {}
|
||||
Err(error) => {
|
||||
error!("Error while submitting a vote : {error}");
|
||||
had_error = true;
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
if had_error {
|
||||
cookies.add(("toast_error", "Il y a eu un problème lors de la soumission du vote !"));
|
||||
} else {
|
||||
debug!("Vote successful")
|
||||
}
|
||||
|
||||
Redirect::to(uri!("/"))
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(crate = "rocket::serde")]
|
||||
pub struct VoteData {
|
||||
votes: HashMap<String, Vec<u8>>,
|
||||
}
|
||||
|
||||
// TODO: Cache vote count ? Maintain in state ?
|
||||
#[get("/<week>/votes", format = "application/json")]
|
||||
pub async fn fetch_vote_data(week: u8, mut db: Connection<database::Db>) -> Option<Json<VoteData>> {
|
||||
let raw_votes: Vec<VotingData> = sqlx::query_as("
|
||||
SELECT Players.name as votes_for, Truths.number as truth_number, count(*) as votes FROM Votes
|
||||
JOIN Players ON Votes.voted_id == Players.id
|
||||
JOIN Truths on Votes.truth_id == Truths.id AND Truths.week == $1
|
||||
GROUP BY votes_for, truth_number
|
||||
ORDER BY votes_for, truth_number;")
|
||||
.bind(week)
|
||||
.fetch_all(&mut **db)
|
||||
.await.unwrap_or_else(|error| {
|
||||
error!("Error while fetching vote data {error}");
|
||||
Vec::<VotingData>::new()
|
||||
});
|
||||
|
||||
let vote_count = raw_votes.iter().fold(0, |count, votes| {count + votes.votes});
|
||||
if vote_count < 17 {
|
||||
return None;
|
||||
}
|
||||
|
||||
|
||||
let mut vote_data = HashMap::<String, Vec<u8>>::new();
|
||||
let mut next_truth_number = 1;
|
||||
for raw_vote in raw_votes {
|
||||
// The truth_number is monotonous (sorted by the SQL request).
|
||||
// If the next vote's truth is lower, we have changed player.
|
||||
if next_truth_number > raw_vote.truth_number {
|
||||
next_truth_number = 1;
|
||||
}
|
||||
|
||||
let votes_for_player: &mut Vec<u8> = match vote_data.entry(raw_vote.votes_for) {
|
||||
Entry::Occupied(existing) => {existing.into_mut()}
|
||||
Entry::Vacant(vacant) => {vacant.insert(Vec::<u8>::new())}
|
||||
};
|
||||
|
||||
// Fill up missing spaces if we are missing any.
|
||||
for _ in next_truth_number..raw_vote.truth_number {
|
||||
votes_for_player.push(0);
|
||||
}
|
||||
// Update with the vote result.
|
||||
votes_for_player.push(raw_vote.votes);
|
||||
next_truth_number = raw_vote.truth_number + 1;
|
||||
}
|
||||
|
||||
Some(Json(VoteData{votes: vote_data}))
|
||||
}
|
||||
|
||||
// FIXME:
|
||||
pub fn stage() -> AdHoc {
|
||||
AdHoc::on_ignite("SQLx Stage", |rocket| async {
|
||||
rocket.mount("/", routes![vote, fetch_vote_data])
|
||||
})
|
||||
}
|
86
static_files/style.css
Normal file
86
static_files/style.css
Normal file
|
@ -0,0 +1,86 @@
|
|||
.top_bar {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
justify-content: space-between;
|
||||
margin-right: 2em;
|
||||
}
|
||||
|
||||
.page_body {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
justify-content: space-between;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.truth_list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
width: 50vw;
|
||||
padding-left: 1eM;
|
||||
}
|
||||
|
||||
.individual_truth {
|
||||
padding-bottom: 2em;
|
||||
}
|
||||
|
||||
.truth_editor {
|
||||
width: 100%;
|
||||
height: 6eM;
|
||||
font-size: large;
|
||||
padding: 0.5em;
|
||||
margin-bottom: 1em;
|
||||
}
|
||||
|
||||
.graph {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-content: center;
|
||||
margin-right: 2vw;
|
||||
width: 45vw;
|
||||
height: auto;
|
||||
}
|
||||
|
||||
.graph > div {
|
||||
width: 100%;
|
||||
height: 80vh;
|
||||
position: sticky;
|
||||
top: 25%;
|
||||
}
|
||||
|
||||
hr {
|
||||
border: none;
|
||||
border-top: 2px solid #9ec5fe;
|
||||
color: #9ec5fe;
|
||||
overflow: visible;
|
||||
text-align: center;
|
||||
height: 5px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
blockquote {
|
||||
border-left: 2px solid #9ec5fe;
|
||||
padding-left: 1eM;
|
||||
margin-left: 1.5eM
|
||||
}
|
||||
|
||||
blockquote > blockquote {
|
||||
margin-left: 0.5em;
|
||||
}
|
||||
|
||||
body {
|
||||
margin-bottom: 10eM;
|
||||
}
|
||||
|
||||
body > h2 {
|
||||
padding-left: 0.25eM;
|
||||
}
|
||||
|
||||
@media (orientation: portrait) {
|
||||
.truth_list {
|
||||
width: 60vw;
|
||||
}
|
||||
|
||||
.graph {
|
||||
width: 35vw;
|
||||
}
|
||||
}
|
85
static_files/vote_chart.js
Normal file
85
static_files/vote_chart.js
Normal file
|
@ -0,0 +1,85 @@
|
|||
|
||||
// const names = ["Bystus", "Dory", "Fen", "Lucky", "Nico", "Peran", "trot"]
|
||||
//
|
||||
//
|
||||
// let data = [];
|
||||
// for (let i = 0; i < 7; i++) {
|
||||
// data.push({
|
||||
// parsing: true,
|
||||
// label: names[i],
|
||||
// data: Array.from(keys, () => Math.round(Math.random()*1.33))})
|
||||
// }
|
||||
async function main() {
|
||||
const vote_response = await fetch(document.URL+"/votes");
|
||||
if (!vote_response.ok) {
|
||||
return;
|
||||
}
|
||||
|
||||
const keys = ["Vérité 1", "Vérité 2", "Vérité 3", "Vérité 4", "Vérité 5", "Vérité 6", "Vérité 7"]
|
||||
let datasets = []
|
||||
|
||||
try {
|
||||
const vote_data = (await vote_response.json()).votes;
|
||||
for (let player in vote_data) {
|
||||
datasets.push({
|
||||
parsing: true,
|
||||
label: player,
|
||||
data: vote_data[player],
|
||||
})
|
||||
}
|
||||
console.log(datasets)
|
||||
} catch (error) {
|
||||
console.error("Failed to parse vote data : \n\t" + error.message);
|
||||
return;
|
||||
}
|
||||
|
||||
const chart_canvas = document.getElementById("vote_chart")
|
||||
let chart
|
||||
function create_chart(keys, data) {
|
||||
let main_axis;
|
||||
let aspect_ratio;
|
||||
if (window.innerWidth > window.innerHeight) {
|
||||
main_axis = 'x'
|
||||
aspect_ratio = 2
|
||||
} else {
|
||||
main_axis = 'y'
|
||||
aspect_ratio = 0.5
|
||||
}
|
||||
|
||||
if ( chart ) {
|
||||
chart.destroy()
|
||||
}
|
||||
|
||||
chart = new Chart(chart_canvas, {
|
||||
type: 'bar',
|
||||
data: {
|
||||
labels: keys,
|
||||
datasets: data,
|
||||
},
|
||||
options: {
|
||||
aspectRatio: aspect_ratio,
|
||||
indexAxis: main_axis,
|
||||
grouped: true,
|
||||
scales: {
|
||||
x: {
|
||||
stacked: true
|
||||
},
|
||||
y: {
|
||||
stacked: true
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function update_chart_ratio(_) {
|
||||
create_chart(keys, datasets)
|
||||
}
|
||||
|
||||
const orientation_query = matchMedia("screen and (orientation:portrait)");
|
||||
orientation_query.onchange = update_chart_ratio
|
||||
|
||||
create_chart(keys, datasets)
|
||||
}
|
||||
|
||||
main().then()
|
40
static_files/vote_handler.js
Normal file
40
static_files/vote_handler.js
Normal file
|
@ -0,0 +1,40 @@
|
|||
/**
|
||||
* This script handles disabling/enabling the different choices
|
||||
* accross the vote options.
|
||||
* This prevents sending weird votes that choose the same person for multiple truths.
|
||||
*/
|
||||
|
||||
const vote_select_tracking = new Map();
|
||||
|
||||
function log_select_change(event) {
|
||||
const changed_select = event.target;
|
||||
const original_index = vote_select_tracking.get(changed_select)
|
||||
for (const select of vote_select_tracking) {
|
||||
select.at(0)[original_index].disabled = false;
|
||||
// Don't disable the default entry, or the one we just moved to.
|
||||
if (changed_select.selectedIndex !== 0 && select.at(0) !== changed_select)
|
||||
select.at(0)[changed_select.selectedIndex].disabled = true
|
||||
}
|
||||
|
||||
// Make sure to change the selected *attribute*, because the .selected property doesn't impact
|
||||
// the form output, it seems.
|
||||
changed_select[original_index].removeAttribute("selected");
|
||||
changed_select[changed_select.selectedIndex].setAttribute("selected", true);
|
||||
// Update with the new tracked index.
|
||||
vote_select_tracking.set(changed_select, changed_select.selectedIndex);
|
||||
}
|
||||
|
||||
const selected_indices = [];
|
||||
for (const select of document.getElementsByTagName("select")) {
|
||||
select.addEventListener("change", log_select_change);
|
||||
vote_select_tracking.set(select, select.selectedIndex);
|
||||
if (select.selectedIndex !== 0) {
|
||||
selected_indices.push(select.selectedIndex);
|
||||
}
|
||||
}
|
||||
|
||||
for (const select of document.getElementsByTagName("select")) {
|
||||
for (const selected_index of selected_indices) {
|
||||
select[selected_index].disabled = true;
|
||||
}
|
||||
}
|
8
templates/editable_truth.tera
Normal file
8
templates/editable_truth.tera
Normal file
|
@ -0,0 +1,8 @@
|
|||
<div class="individual_truth">
|
||||
<h3>Vérité {{ truth.number }}</h3>
|
||||
<p>{{ truth.rendered_text | safe }}</p>
|
||||
<hr/>
|
||||
<form action="/{{ week_number }}/edit/{{ truth.number }}" method="POST">
|
||||
{% include "truth_editor" %}
|
||||
</form>
|
||||
</div>
|
95
templates/index.html.tera
Normal file
95
templates/index.html.tera
Normal file
|
@ -0,0 +1,95 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
{% set title = "Vérités Fabula Ultima" %}
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>{{ title }}</title>
|
||||
<link href="/style.css" rel="stylesheet"/>
|
||||
{% if user.logged_in == true and not user.is_admin %}
|
||||
<script defer="defer" type="text/javascript" src="/vote_handler.js"></script>
|
||||
{% endif %}
|
||||
<script defer="defer" type="application/javascript" src="https://cdn.jsdelivr.net/npm/chart.js@4.4.3/dist/chart.umd.min.js"></script>
|
||||
<script defer="defer" type="text/javascript" src="/vote_chart.js"></script>
|
||||
</head>
|
||||
|
||||
{# Check if the user has a vote in advance, for readability #}
|
||||
{% if user.logged_in == true and user.has_week_vote == true%}
|
||||
{% set has_vote = true %}
|
||||
{% else %}
|
||||
{% set has_vote = false %}
|
||||
{% endif -%}
|
||||
|
||||
<body>
|
||||
<div class="top_bar">
|
||||
<h1>{{ title }}</h1>
|
||||
{% if user.logged_in == true %}
|
||||
<p>Connecté en tant que <b>{{ user.name }}</b></p>
|
||||
{% else %}
|
||||
<form class="login" id="login" action="/login" method="POST">
|
||||
<label>Pseudo <input form="login" type="text" name="name"/></label>
|
||||
<label>Mot de passe <input form="login" type="password" name="password"/></label>
|
||||
<button form="login">Se connecter</button>
|
||||
</form>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
<h2>Semaine {{ week_number }}</h2>
|
||||
<div class="page_body">
|
||||
<div class="truth_list">
|
||||
{% if user.logged_in == true and user.is_admin == false %}
|
||||
<form id="truths" action="/{{ week_number }}/vote" method="POST">
|
||||
{% endif %}
|
||||
|
||||
{# Truths start at 1 but the array starts at 0 #}
|
||||
{% set index_delta = 1 %}
|
||||
{% for truth in truths %}
|
||||
{#
|
||||
The truths are in an ordered array, but one of them might be the user's.
|
||||
In this case, we need to stop the array index from incrementing if the current
|
||||
truth is the user's, as they cannot have voted for themselves, leading to one
|
||||
less votes than there are truths.
|
||||
#}
|
||||
{%- if truth.author_id == user.id -%}
|
||||
{%- set_global index_delta = 2 -%}
|
||||
{% endif %}
|
||||
{% set truth_index = truth.number - index_delta %}
|
||||
|
||||
{% if user.is_admin == true %}
|
||||
{% include "editable_truth" %}
|
||||
{% else %}
|
||||
{% include "truth" %}
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
|
||||
{% if user.logged_in == true and user.is_admin == false %}
|
||||
<br/>
|
||||
<button form="truths">
|
||||
{%- if has_vote == true -%}
|
||||
Changer de vote
|
||||
{% else %}
|
||||
À voter !
|
||||
{% endif %}
|
||||
</button>
|
||||
</form>
|
||||
{% endif %}
|
||||
|
||||
{# If admin, show an additional box for creating a new Truth. #}
|
||||
{% if user.is_admin == true %}
|
||||
<div class="individual_truth">
|
||||
<h3>Nouvelle vérité</h3>
|
||||
<form action="/{{ week_number }}/new" method="POST">
|
||||
{% include "truth_editor" %}
|
||||
</form>
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
<div class="graph">
|
||||
<div>
|
||||
<canvas id="vote_chart"></canvas>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</body>
|
||||
</html>
|
26
templates/truth.html.tera
Normal file
26
templates/truth.html.tera
Normal file
|
@ -0,0 +1,26 @@
|
|||
<div class="individual_truth">
|
||||
<h3>Vérité {{ truth.number }}</h3>
|
||||
<p>{{ truth.rendered_text | safe }}</p>
|
||||
{% if user.logged_in %}
|
||||
<hr/>
|
||||
<label>
|
||||
{%- if truth.author_id == user.id -%}
|
||||
Tu l'as fait :)
|
||||
{%- else -%}
|
||||
Qui l'a fait ?
|
||||
<select form="truths" name="truth_votes[{{ truth.id }}]">
|
||||
<option value="0">---</option>
|
||||
{% for player in other_players %}
|
||||
{# Check if we should pre-select an existing vote #}
|
||||
{% if has_vote == true and player.id == user.votes[truth_index].voted_id %}
|
||||
{% set is_selected = "selected" %}
|
||||
{% else %}
|
||||
{% set is_selected = "" %}
|
||||
{% endif %}
|
||||
<option value="{{ player.id }}" {{- is_selected -}}>{{ player.name }}</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
{%- endif -%}
|
||||
</label>
|
||||
{% endif %}
|
||||
</div>
|
26
templates/truth_editor.html.tera
Normal file
26
templates/truth_editor.html.tera
Normal file
|
@ -0,0 +1,26 @@
|
|||
<textarea class="truth_editor" name="truth_raw_text">
|
||||
{%- if truth.raw_text -%}
|
||||
{{- truth.raw_text -}}
|
||||
{%- endif -%}
|
||||
</textarea>
|
||||
<label>Qui l'a écrit ?
|
||||
<select name="truth_author">
|
||||
<option value="0">---</option>
|
||||
{% for player in other_players %}
|
||||
{# Check if we should pre-select if the truth already exists #}
|
||||
{% if truth.author_id and player.id == truth.author_id %}
|
||||
{% set is_selected = "selected" %}
|
||||
{% else %}
|
||||
{% set is_selected = "" %}
|
||||
{% endif %}
|
||||
<option value="{{ player.id }}" {{- is_selected -}}>{{ player.name }}</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</label>
|
||||
<button>
|
||||
{%- if not truth.author_id -%}
|
||||
Ajouter une vérité
|
||||
{%- else -%}
|
||||
Modifier la vérité
|
||||
{%- endif -%}
|
||||
</button>
|
Loading…
Add table
Reference in a new issue