43 Commits

Author SHA1 Message Date
d6e62b98aa Fix more clippy warnings
All checks were successful
Build Crate / build (push) Successful in 1m45s
2024-08-28 23:54:56 -04:00
aca0b83dd4 Implement login form error, more clippy fixes
All checks were successful
Build Crate / build (push) Successful in 1m47s
2024-08-28 23:45:10 -04:00
9a42ed5b80 Fix forget password
All checks were successful
Build Crate / build (push) Successful in 1m46s
2024-08-28 23:14:27 -04:00
ed780c9585 Fix more clippy issues, implement forgot password
All checks were successful
Build Crate / build (push) Successful in 1m48s
2024-08-28 23:03:52 -04:00
1faaf65aad Clean up imports
All checks were successful
Build Crate / build (push) Successful in 1m47s
2024-08-28 21:55:23 -04:00
df0d7d6c0d Add registration errors
All checks were successful
Build Crate / build (push) Successful in 1m48s
2024-08-28 17:29:51 -04:00
56ea1f12c7 Merge branch 'ft/add-db-and-auth'
All checks were successful
Build Crate / build (push) Successful in 1m45s
2024-08-28 16:54:39 -04:00
5af626b746 Add basic register and login
All checks were successful
Build Crate / build (push) Successful in 1m45s
2024-08-28 16:53:08 -04:00
f4f491085d Add database to server endpoints, move modals, add forget pw to db
All checks were successful
Build Crate / build (push) Successful in 1m45s
2024-08-27 02:12:57 -04:00
242f9b1218 Add initial forgot password form
Some checks failed
Build Crate / build (push) Failing after 1m43s
2024-08-26 20:15:48 -04:00
e376874afa Clean up login form, add files for others
Some checks failed
Build Crate / build (push) Failing after 1m46s
2024-08-26 19:44:52 -04:00
65d47615da Got log in and out working, moved global state
All checks were successful
Build Crate / build (push) Successful in 1m45s
close to done!
2024-08-26 17:43:08 -04:00
0f20ba3b86 Added basic logging in
Some checks failed
Build Crate / build (push) Failing after 54s
Needs a lot of work
2024-08-26 00:09:08 -04:00
99b4d9af1a Moved modal state into global state
All checks were successful
Build Crate / build (push) Successful in 1m39s
unfortunate but easiest way
2024-08-25 16:36:13 -04:00
462ca81a15 notwork - login form capsule with rcsignal 2024-08-25 14:07:27 -04:00
c2ecce0324 Add login form capsule
All checks were successful
Build Crate / build (push) Successful in 1m44s
2024-08-23 15:45:40 -04:00
8d2460c60e Add login modal
All checks were successful
Build Crate / build (push) Successful in 1m44s
2024-08-21 19:32:22 -04:00
528ce0335c Add auth global state and login button
All checks were successful
Build Crate / build (push) Successful in 1m42s
2024-08-19 02:38:29 -04:00
993a0834b4 Fix sea-orm version
All checks were successful
Build Crate / build (push) Successful in 1m33s
2024-08-18 20:11:32 -04:00
d29da66536 Fix clippy errors, update deps
Some checks failed
Build Crate / build (push) Failing after 52s
2024-08-18 19:56:00 -04:00
ffe6a771d2 Add engine and client cfg
All checks were successful
Build Crate / build (push) Successful in 1m33s
Should fix some linking errors
2024-08-18 16:30:37 -04:00
d3208303ba Add formatting check and fail on clippy warnings
All checks were successful
Build Crate / build (push) Successful in 1m35s
2024-08-18 16:06:46 -04:00
f71d2ae70a Add verbose building
All checks were successful
Build Crate / build (push) Successful in 1m32s
2024-08-18 15:57:11 -04:00
0fd6ef8817 Fix build, test out clippy
Some checks failed
Build Crate / build (push) Failing after 1m12s
2024-08-18 15:40:22 -04:00
8ad6967b7a Remove automatic deploy
Some checks failed
Build Crate / build (push) Failing after 1m26s
Too annoying to host now
2024-08-18 15:34:42 -04:00
528682d9b1 Update to more generic db models
Some checks failed
Build Crate / build (push) Has been cancelled
Also integrated entities into codebase
2024-08-18 03:26:12 -04:00
5d28013f30 Update readme with fixes
Some checks failed
Build Crate / build (push) Has been cancelled
also update tailwind
2024-08-14 21:31:48 -04:00
5cb67786bf Add initial database schema and references
Some checks are pending
Build Crate / build (push) Waiting to run
Also look into users a bit
2024-08-14 01:20:48 -04:00
Jacob Kassman
01eaf059dd Add the ability to add users
All checks were successful
Build Crate / build (push) Successful in 3m25s
2023-12-09 21:49:59 -05:00
cb5da9b966 Merge pull request 'Refactor PoolMatch' (#5) from refactor-pool-match into main
All checks were successful
Build Crate / build (push) Successful in 9m6s
Reviewed-on: https://questia.dev/git/vsquad/pool-elo/pulls/5
Reviewed-by: Matthew Kaminski <kaminskimateusz7@gmail.com>
2023-12-10 00:09:49 +00:00
cd8b52cd29 Co-authored-by: jkassman <jkassman@users.noreply.github.com>
All checks were successful
Build Crate / build (push) Successful in 8m23s
2023-10-29 23:30:38 -04:00
319c77cfa3 Merge branch 'add_api' into main
All checks were successful
Build Crate / build (push) Successful in 3m16s
2023-09-22 14:35:36 -04:00
976732ab59 Add missing file
All checks were successful
Build Crate / build (push) Successful in 3m11s
2023-09-22 14:35:19 -04:00
ae4cb23acb Merge pull request 'add_api' (#4) from add_api into main
Some checks failed
Build Crate / build (push) Failing after 3m31s
Reviewed-on: https://questia.dev/git/vsquad/pool-elo/pulls/4
2023-09-22 07:46:59 +00:00
30f3aa63d5 Add base data structures for pool matches
Some checks failed
Build Crate / build (push) Failing after 4m29s
2023-09-22 03:45:48 -04:00
0a68829d6c Add working API calls, fix warnings
All checks were successful
Build Crate / build (push) Successful in 7m16s
2023-09-21 20:03:16 -04:00
30b637dfef Add cargo file
Some checks failed
Build Crate / build (push) Failing after 6m20s
2023-09-20 21:33:12 -04:00
3d52cd0a24 Add API
Some checks failed
Build Crate / build (push) Failing after 6m25s
2023-09-20 21:32:19 -04:00
f31e87780f Merge pull request 'Add simple data store' (#3) from simple_data_store into main
All checks were successful
Build Crate / build (push) Successful in 5m7s
Reviewed-on: https://questia.dev/git/vsquad/pool-elo/pulls/3
2023-09-20 05:07:31 +00:00
ec06340def Add simple data store
All checks were successful
Build Crate / build (push) Successful in 8m5s
2023-09-20 00:28:16 -04:00
0a1c81c44e Merge pull request 'Add example pages and remove dead code' (#2) from clean_and_pages into main
All checks were successful
Build Crate / build (push) Successful in 9m26s
Reviewed-on: https://questia.dev/git/vsquad/pool-elo/pulls/2
2023-09-19 07:35:03 +00:00
1b3a6db223 Add example pages and remove dead code
All checks were successful
Build Crate / build (push) Successful in 4m41s
2023-09-19 03:27:31 -04:00
matkam7
aaaaf256f4 Merge pull request 'Fix actions info' (#1) from test into main
All checks were successful
Build Crate / build (push) Successful in 5m44s
Reviewed-on: https://questia.dev/git/vsquad/pool-elo/pulls/1
2023-09-18 04:32:17 +00:00
52 changed files with 2331 additions and 241 deletions

2
.cargo/config.toml Normal file
View File

@@ -0,0 +1,2 @@
[build]
rustflags = [ "--cfg", "engine" ]

4
.dev/.env Normal file
View File

@@ -0,0 +1,4 @@
POSTGRES_DB=elo_app
POSTGRES_USER=elo
POSTGRES_PASSWORD=elo
DATABASE_URL=postgres://elo:elo@db:5432/elo_app

18
.dev/docker-compose.yml Normal file
View File

@@ -0,0 +1,18 @@
services:
db:
image: postgres:15.3-alpine
restart: unless-stopped
ports:
- 5432:5432
networks:
- db
volumes:
- postgres-data:/var/lib/postgresql/data
env_file:
- .env
volumes:
postgres-data:
networks:
db:

View File

@@ -42,57 +42,14 @@ jobs:
run: npm install -D tailwindcss
- name: Compile css
run: npm run build
# TODO -> Remove wasm-opt-version once perseus is updated
- name: Build the project
run: perseus deploy
- name: Download private docker registry cert
uses: nicklasfrahm/scp-action@v1.0.1
with:
direction: download
host: ${{ secrets.REGISTRY_HOST }}
username: ${{ secrets.REGISTRY_HOST_USERNAME }}
insecure_password: ${{ secrets.REGISTRY_HOST_PASSWORD }}
source: ${{ secrets.REGISTRY_CRT_PATH }}
target: ca.crt
insecure_ignore_fingerprint: true
- name: Add directory for docker registry cert
run: 'mkdir -p /etc/docker/certs.d/${{ secrets.REGISTRY_HOST }}'
- name: Move private docker registry cert
run: 'mv ca.crt /etc/docker/certs.d/${{ secrets.REGISTRY_HOST }}'
- name: Install docker
uses: papodaca/install-docker-action@main
- name: Set up QEMU
uses: docker/setup-qemu-action@v2
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v2
with:
config-inline: |
[registry."${{ secrets.REGISTRY_HOST }}"]
insecure = true
ca=["/etc/docker/certs.d/${{ secrets.REGISTRY_HOST }}/ca.crt"]
- name: Login to private docker registry
uses: docker/login-action@v2
with:
registry: ${{ secrets.REGISTRY_HOST }}
username: ${{ secrets.REGISTRY_USERNAME }}
password: ${{ secrets.REGISTRY_PASSWORD }}
- name: Build and push
uses: docker/build-push-action@v4
with:
context: .
push: true
tags: ${{ secrets.REGISTRY_HOST }}/vsquad/pool-elo:${{ gitea.ref_name }}
- name: Trigger deployment
uses: fjogeleit/http-request-action@v1
with:
url: ${{ secrets.TRIGGER_DEPLOY_URL }}
method: POST
customHeaders: '{"Content-Type": "application/json"}'
data: '{"actionName": "deploy", "arguments": []}'
preventFailureOnNoResponse: 'true'
run: perseus --wasm-opt-version version_118 deploy --verbose
- name: Run clippy for server
run: RUSTFLAGS="--cfg=engine" cargo clippy --all --future-incompat-report -- -D warnings
continue-on-error: true
- name: Run clippy for frontend
run: RUSTFLAGS="--cfg=client" cargo clippy --all --future-incompat-report -- -D warnings
continue-on-error: true
- name: Check for formatting issues
run: cargo fmt --check

2
.gitignore vendored
View File

@@ -5,3 +5,5 @@ target
static
pkg
./Cargo.lock
package-lock.json
/data/

View File

@@ -6,17 +6,43 @@ edition = "2021"
[dependencies]
perseus = { version = "0.4.2", features = ["hydrate"] }
sycamore = "0.8.2"
sycamore = { version = "0.8.2", features = [
"suspense",
"web",
"wasm-bindgen-interning",
] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
env_logger = "0.10.0"
log = "0.4.20"
once_cell = "1.18.0"
web-sys = { version = "0.3.64", features = ["Window", "Storage"] }
cfg-if = "1.0.0"
chrono = { version = "0.4.38", features = ["serde", "wasm-bindgen"] }
lazy_static = "1.5"
[target.'cfg(engine)'.dev-dependencies]
fantoccini = "0.19"
[target.'cfg(engine)'.dependencies]
tokio = { version = "1", features = ["macros", "rt", "rt-multi-thread"] }
perseus-axum = { version = "0.4.2", features = [ "dflt-server" ] }
perseus-axum = { version = "0.4.2" }
axum = "0.6"
tower-http = { version = "0.3", features = ["fs"] }
futures = "0.3.28"
sea-orm = { version = "1.0", features = [
"sqlx-postgres",
"runtime-tokio-native-tls",
"macros",
"with-chrono",
] }
jsonwebtoken = "9.3.0"
argon2 = "0.5"
[target.'cfg(client)'.dependencies]
wasm-bindgen = "0.2.93"
reqwest = { version = "0.11", features = ["json"] }
sea-orm = { version = "1.0" }
[lints.rust]
unexpected_cfgs = { level = "warn", check-cfg = ['cfg(engine)', 'cfg(client)'] }

View File

@@ -14,6 +14,8 @@ Run `curl --proto '=https' --tlsv1.3 https://sh.rustup.rs -sSf | sh`
### Windows:
https://nodejs.org/en
(todo look into:)
https://pnpm.io/
### Unix based systems:
@@ -23,9 +25,18 @@ https://nodejs.org/en
## 3. Install Perseus, for real-time updates while developing
`cargo install perseus-cli`
`cargo build --target wasm32-unknown-unknown`
## 4. Install tailwindcss, for styling
(temporarily broken, if this doensn't work run `cargo install perseus-cli --locked` )
`rustup target add wasm32-unknown-unknown`
## 4. Install docker for Postgresql
## 5. Install SeaORM for database
`cargo install sea-orm-cli@1.0.0-rc.5`
## 5. Install tailwindcss, for styling
`npm install -D tailwindcss`
@@ -39,11 +50,19 @@ https://blog.logrocket.com/building-rust-app-perseus/
# Building the project
To set up the database, run:
`$env:DATABASE_URL = "postgres://elo:elo@localhost:5432/elo_app"; sea-orm-cli migrate up`
Updating entities after updating database:
`$env:DATABASE_URL = "postgres://elo:elo@localhost:5432/elo_app"; sea-orm-cli generate entity -o src/entity --with-serde both`
To build CSS run:
`npm run build`
To build the project for testing, run
`perseus serve`
`perseus serve --verbose`
(if broken: todo remove once fixed)
`perseus --wasm-opt-version version_118 serve --verbose`
# Deploying the project

16
migration/Cargo.toml Normal file
View File

@@ -0,0 +1,16 @@
[package]
name = "migration"
version = "0.1.0"
edition = "2021"
publish = false
[lib]
name = "migration"
path = "src/lib.rs"
[dependencies]
async-std = { version = "1", features = ["attributes", "tokio1"] }
[dependencies.sea-orm-migration]
version = "1.0.0"
features = ["sqlx-postgres", "runtime-tokio-native-tls"]

46
migration/README.md Normal file
View File

@@ -0,0 +1,46 @@
# References
https://www.sea-ql.org/sea-orm-tutorial/ch01-02-migration-cli.html
https://www.sea-ql.org/SeaORM/docs/migration/writing-migration/
# Running Migrator CLI
- Generate a new migration file
```sh
cargo run -- generate MIGRATION_NAME
```
- Apply all pending migrations
```sh
cargo run
```
```sh
cargo run -- up
```
- Apply first 10 pending migrations
```sh
cargo run -- up -n 10
```
- Rollback last applied migrations
```sh
cargo run -- down
```
- Rollback last 10 applied migrations
```sh
cargo run -- down -n 10
```
- Drop all tables from the database, then reapply all migrations
```sh
cargo run -- fresh
```
- Rollback all applied migrations, then reapply all migrations
```sh
cargo run -- refresh
```
- Rollback all applied migrations
```sh
cargo run -- reset
```
- Check the status of all migrations
```sh
cargo run -- status
```

16
migration/src/lib.rs Normal file
View File

@@ -0,0 +1,16 @@
pub use sea_orm_migration::prelude::*;
mod m20240813_000001_create_users;
mod m20240813_000002_create_game;
pub struct Migrator;
#[async_trait::async_trait]
impl MigratorTrait for Migrator {
fn migrations() -> Vec<Box<dyn MigrationTrait>> {
vec![
Box::new(m20240813_000001_create_users::Migration),
Box::new(m20240813_000002_create_game::Migration),
]
}
}

View File

@@ -0,0 +1,52 @@
use sea_orm_migration::{prelude::*, schema::*};
#[derive(DeriveMigrationName)]
pub struct Migration;
// https://github.com/SeaQL/sea-orm/blob/368b1126f73f47c7ec30fe523834f6a0962a193b/sea-orm-migration/src/schema.rs
#[async_trait::async_trait]
impl MigrationTrait for Migration {
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
// User table
// @todo verify all data saved is length-checked
manager
.create_table(
Table::create()
.table(User::Table)
.col(pk_auto(User::Id))
.col(string_uniq(User::Username))
.col(string(User::PasswordHashAndSalt))
.col(string_null(User::Nickname))
.col(timestamp(User::CreationTime))
.col(timestamp(User::LastActiveTime))
.col(boolean(User::IsAdmin))
.col(string_null(User::Email))
.col(string_null(User::Avatar))
.col(string_null(User::ForgotPasswordRequest))
.to_owned(),
)
.await
}
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.drop_table(Table::drop().table(User::Table).to_owned())
.await
}
}
#[derive(DeriveIden)]
pub enum User {
Table,
Id,
Username,
PasswordHashAndSalt,
Nickname,
CreationTime,
LastActiveTime,
IsAdmin,
Email,
Avatar,
ForgotPasswordRequest,
}

View File

@@ -0,0 +1,163 @@
use sea_orm::{DbBackend, DeriveActiveEnum, EnumIter, Schema};
use sea_orm_migration::sea_orm::ActiveEnum;
use sea_orm_migration::{prelude::*, schema::*, sea_query::extension::postgres::Type};
use super::m20240813_000001_create_users::User;
#[derive(DeriveMigrationName)]
pub struct Migration;
#[async_trait::async_trait]
impl MigrationTrait for Migration {
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
let schema = Schema::new(DbBackend::Postgres);
// Game type enum
manager
.create_type(schema.create_enum_from_active_enum::<GameType>())
.await?;
// Game table
manager
.create_table(
Table::create()
.table(Game::Table)
.col(pk_auto(Game::Id))
.col(timestamp_with_time_zone(Game::Time))
.col(ColumnDef::new(Game::GameType).custom(GameType::name()))
.to_owned(),
)
.await?;
// TeamResult table
manager
.create_table(
Table::create()
.table(TeamResult::Table)
.col(pk_auto(TeamResult::Id))
.col(integer(TeamResult::Place))
.col(integer_null(TeamResult::Score))
.to_owned(),
)
.await?;
// Game to TeamResult assoc
manager
.create_table(
Table::create()
.table(GameToTeamResult::Table)
.col(integer(GameToTeamResult::GameId))
.col(integer(GameToTeamResult::TeamResultId))
.primary_key(
Index::create()
.name("pk-game_to_team_result")
.col(GameToTeamResult::GameId)
.col(GameToTeamResult::TeamResultId),
)
.foreign_key(
ForeignKey::create()
.name("fk-game_to_team_result-game_id")
.from(GameToTeamResult::Table, GameToTeamResult::GameId)
.to(Game::Table, Game::Id),
)
.foreign_key(
ForeignKey::create()
.name("fk-game_to_team_result-team_result_id")
.from(GameToTeamResult::Table, GameToTeamResult::TeamResultId)
.to(TeamResult::Table, TeamResult::Id),
)
.to_owned(),
)
.await?;
// TeamResult to User assoc
manager
.create_table(
Table::create()
.table(TeamResultToUser::Table)
.col(integer(TeamResultToUser::TeamResultId))
.col(integer(TeamResultToUser::UserId))
.primary_key(
Index::create()
.name("pk-team_result_to_user")
.col(TeamResultToUser::TeamResultId)
.col(TeamResultToUser::UserId),
)
.foreign_key(
ForeignKey::create()
.name("fk-team_result_to_user-team_result_id")
.from(TeamResultToUser::Table, TeamResultToUser::TeamResultId)
.to(TeamResult::Table, TeamResult::Id),
)
.foreign_key(
ForeignKey::create()
.name("fk-team_result_to_user-user_id")
.from(TeamResultToUser::Table, TeamResultToUser::UserId)
.to(User::Table, User::Id),
)
.to_owned(),
)
.await
}
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
// Drop tables in reverse
manager
.drop_table(Table::drop().table(TeamResultToUser::Table).to_owned())
.await?;
manager
.drop_table(Table::drop().table(GameToTeamResult::Table).to_owned())
.await?;
manager
.drop_table(Table::drop().table(TeamResult::Table).to_owned())
.await?;
manager
.drop_table(Table::drop().table(Game::Table).to_owned())
.await?;
// Drop types
manager
.drop_type(Type::drop().name(GameType::name()).to_owned())
.await
}
}
// Enums
#[derive(EnumIter, DeriveActiveEnum)]
#[sea_orm(rs_type = "String", db_type = "Enum", enum_name = "game_type")]
enum GameType {
#[sea_orm(string_value = "TableTennis")]
TableTennis,
#[sea_orm(string_value = "Pool")]
Pool,
#[sea_orm(string_value = "PickleBall")]
PickleBall,
}
// Tables
#[derive(DeriveIden)]
enum Game {
Table,
Id,
Time,
GameType,
}
#[derive(DeriveIden)]
enum TeamResult {
Table,
Id,
Place,
Score,
}
// Assoc
#[derive(DeriveIden)]
enum GameToTeamResult {
Table,
GameId,
TeamResultId,
}
#[derive(DeriveIden)]
enum TeamResultToUser {
Table,
TeamResultId,
UserId,
}

6
migration/src/main.rs Normal file
View File

@@ -0,0 +1,6 @@
use sea_orm_migration::prelude::*;
#[async_std::main]
async fn main() {
cli::run_cli(migration::Migrator).await;
}

View File

@@ -11,6 +11,6 @@
"author": "",
"license": "ISC",
"devDependencies": {
"tailwindcss": "^3.3.3"
"tailwindcss": "^3.4.10"
}
}

19
src/auth.rs Normal file
View File

@@ -0,0 +1,19 @@
use crate::user;
use axum_login::{AuthUser, AuthnBackend, UserId};
use serde::{Deserialize, Serialize};
// References
// https://github.com/maxcountryman/axum-login/tree/main/examples/sqlite/src
// https://framesurge.sh/perseus/en-US/docs/0.4.x/state/intro
impl AuthUser for user::Model {
type Id = i32;
fn id(&self) -> Self::Id {
self.id
}
fn session_auth_hash(&self) -> &[u8] {
self.password.as_bytes()
}
}

View File

@@ -0,0 +1,162 @@
use lazy_static::lazy_static;
use perseus::prelude::*;
use serde::{Deserialize, Serialize};
use sycamore::prelude::*;
use web_sys::Event;
cfg_if::cfg_if! {
if #[cfg(client)] {
use crate::{
state_enums::{ OpenState},
templates::get_api_path,
global_state::{AppStateRx},
endpoints::FORGOT_PASSWORD,
models::{
auth::ForgotPasswordRequest,
generic::GenericResponse,
},
};
use reqwest::StatusCode;
}
}
lazy_static! {
pub static ref FORGOT_PASSWORD_FORM: Capsule<PerseusNodeType, ForgotPasswordFormProps> =
get_capsule();
}
#[derive(Serialize, Deserialize, Clone, ReactiveState)]
#[rx(alias = "ForgotPasswordFormStateRx")]
struct ForgotPasswordFormState {
username: String,
how_to_reach: String,
error: String,
}
impl ForgotPasswordFormStateRx {
#[cfg(client)]
fn reset(&self) {
self.username.set(String::new());
self.how_to_reach.set(String::new());
self.error.set(String::new());
}
}
#[derive(Clone)]
pub struct ForgotPasswordFormProps {}
#[auto_scope]
fn forgot_password_form_capsule<G: Html>(
cx: Scope,
state: &ForgotPasswordFormStateRx,
_props: ForgotPasswordFormProps,
) -> View<G> {
let close_modal = move |_event: Event| {
#[cfg(client)]
{
spawn_local_scoped(cx, async move {
let global_state = Reactor::<G>::from_cx(cx).get_global_state::<AppStateRx>(cx);
// Close modal
state.reset();
global_state
.modals_open
.forgot_password
.set(OpenState::Closed)
});
}
};
let handle_submit = move |_event: Event| {
#[cfg(client)]
{
spawn_local_scoped(cx, async move {
let request = ForgotPasswordRequest {
username: state.username.get().as_ref().clone(),
contact_info: state.how_to_reach.get().as_ref().clone(),
};
// // @todo clean up error handling
let client = reqwest::Client::new();
let response = client
.post(get_api_path(FORGOT_PASSWORD).as_str())
.json(&request)
.send()
.await
.unwrap();
let status = response.status();
let response_data = response.json::<GenericResponse>().await.unwrap();
if status != StatusCode::OK {
state.error.set(response_data.status);
return;
}
let global_state = Reactor::<G>::from_cx(cx).get_global_state::<AppStateRx>(cx);
// Close modal
state.reset();
global_state
.modals_open
.forgot_password
.set(OpenState::Closed);
});
}
};
view! { cx,
div (class="overflow-x-hidden overflow-y-auto fixed h-modal md:h-full top-4 left-0 right-0 md:inset-0 z-50 justify-center items-center"){
div (class="relative md:mx-auto w-full md:w-1/2 lg:w-1/3 z-0 my-10") {
div (class="bg-white rounded-lg shadow relative dark:bg-gray-700"){
div (class="flex justify-end p-2"){
button (on:click = close_modal, class="text-gray-400 bg-transparent hover:bg-gray-200 hover:text-gray-900 rounded-lg text-sm p-1.5 ml-auto inline-flex items-center dark:hover:bg-gray-800 dark:hover:text-white"){
"Close"
}
}
div (class="space-y-6 px-6 lg:px-8 pb-4 sm:pb-6 xl:pb-8") {
h3 (class="text-xl font-medium text-gray-900 dark:text-white"){"Forgot Password"}
(match state.error.get().as_ref() != "" {
true => { view!{cx,
div (role="alert") {
div (class="bg-red-500 text-white font-bold rounded-t px-4 py-2") {
"Error"
}
div (class="border border-t-0 border-red-400 rounded-b bg-red-100 px-4 py-3 text-red-700"){
p {(state.error.get())}
}
}
}},
false => {view!{cx,}},
})
div {
label (class="text-sm font-medium text-gray-900 block mb-2 dark:text-gray-300") {"Username"}
input (bind:value = state.username, class="bg-gray-50 border border-gray-300 text-gray-900 sm:text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-600 dark:border-gray-500 dark:placeholder-gray-400 dark:text-white") {}
}
div {
label (class="text-sm font-medium text-gray-900 block mb-2 dark:text-gray-300"){"Contact Info"}
input (bind:value = state.how_to_reach, class="bg-gray-50 border border-gray-300 text-gray-900 sm:text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-600 dark:border-gray-500 dark:placeholder-gray-400 dark:text-white"){}
}
button (on:click = handle_submit, class="w-full text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800"){"Submit"}
}
}
}
}
}
}
pub fn get_capsule<G: Html>() -> Capsule<G, ForgotPasswordFormProps> {
Capsule::build(Template::build("forgot_password_form").build_state_fn(get_build_state))
.empty_fallback()
.view_with_state(forgot_password_form_capsule)
.build()
}
#[engine_only_fn]
async fn get_build_state(_info: StateGeneratorInfo<()>) -> ForgotPasswordFormState {
ForgotPasswordFormState {
username: String::new(),
how_to_reach: String::new(),
error: String::new(),
}
}

217
src/capsules/login_form.rs Normal file
View File

@@ -0,0 +1,217 @@
use lazy_static::lazy_static;
use perseus::prelude::*;
use serde::{Deserialize, Serialize};
use sycamore::prelude::*;
use web_sys::Event;
cfg_if::cfg_if! {
if #[cfg(client)] {
use crate::{
endpoints::LOGIN,
global_state::{AppStateRx},
models::auth::{LoginInfo, LoginResponse, WebAuthInfo},
models::generic::GenericResponse,
state_enums::{OpenState},
templates::get_api_path,
};
use reqwest::StatusCode;
}
}
lazy_static! {
pub static ref LOGIN_FORM: Capsule<PerseusNodeType, LoginFormProps> = get_capsule();
}
#[derive(Serialize, Deserialize, Clone, ReactiveState)]
#[rx(alias = "LoginFormStateRx")]
struct LoginFormState {
username: String,
password: String,
remember_me: bool,
error: String,
}
impl LoginFormStateRx {
#[cfg(client)]
fn reset(&self) {
self.username.set(String::new());
self.password.set(String::new());
self.remember_me.set(false);
self.error.set(String::new());
}
}
#[derive(Clone)]
pub struct LoginFormProps {
pub remember_me: bool,
}
#[auto_scope]
fn login_form_capsule<G: Html>(
cx: Scope,
state: &LoginFormStateRx,
props: LoginFormProps,
) -> View<G> {
let close_modal = move |_event: Event| {
#[cfg(client)]
{
spawn_local_scoped(cx, async move {
let global_state = Reactor::<G>::from_cx(cx).get_global_state::<AppStateRx>(cx);
global_state.modals_open.login.set(OpenState::Closed)
});
}
};
let handle_forgot_password = move |_event: Event| {
#[cfg(client)]
{
spawn_local_scoped(cx, async move {
let global_state = Reactor::<G>::from_cx(cx).get_global_state::<AppStateRx>(cx);
global_state
.modals_open
.forgot_password
.set(OpenState::Open);
// Close modal
state.reset();
global_state.modals_open.login.set(OpenState::Closed);
});
}
};
let handle_register = move |_event: Event| {
#[cfg(client)]
{
spawn_local_scoped(cx, async move {
let global_state = Reactor::<G>::from_cx(cx).get_global_state::<AppStateRx>(cx);
global_state.modals_open.register.set(OpenState::Open);
// Close modal
state.reset();
global_state.modals_open.login.set(OpenState::Closed);
});
}
};
let handle_log_in = move |_event: Event| {
#[cfg(client)]
{
spawn_local_scoped(cx, async move {
let remember_me = *state.remember_me.get().as_ref();
let username = state.username.get().as_ref().clone();
let login_info = LoginInfo {
username: username.clone(),
password: state.password.get().as_ref().clone(),
remember_me,
};
// // @todo clean up error handling
let client = reqwest::Client::new();
let response = client
.post(get_api_path(LOGIN).as_str())
.json(&login_info)
.send()
.await
.unwrap();
let global_state = Reactor::<G>::from_cx(cx).get_global_state::<AppStateRx>(cx);
if response.status() != StatusCode::OK {
let response = response.json::<GenericResponse>().await.unwrap();
state.error.set(response.status.to_string());
state.reset();
return;
}
let response = response.json::<LoginResponse>().await.unwrap();
// Save token to session/local storage and update state
global_state.auth.handle_log_in(WebAuthInfo {
token: response.token,
expires: response.expires,
username,
remember_me,
});
// Close modal
state.reset();
global_state.modals_open.login.set(OpenState::Closed);
});
}
};
view! { cx,
div (class="overflow-x-hidden overflow-y-auto fixed h-modal md:h-full top-4 left-0 right-0 md:inset-0 z-50 justify-center items-center"){
div (class="relative md:mx-auto w-full md:w-1/2 lg:w-1/3 z-0 my-10") {
div (class="bg-white rounded-lg shadow relative dark:bg-gray-700"){
div (class="flex justify-end p-2"){
button (on:click = close_modal, class="text-gray-400 bg-transparent hover:bg-gray-200 hover:text-gray-900 rounded-lg text-sm p-1.5 ml-auto inline-flex items-center dark:hover:bg-gray-800 dark:hover:text-white"){
"Close"
}
}
div (class="space-y-6 px-6 lg:px-8 pb-4 sm:pb-6 xl:pb-8") {
h3 (class="text-xl font-medium text-gray-900 dark:text-white"){"Sign in"}
(match state.error.get().as_ref() != "" {
true => { view!{cx,
div (role="alert") {
div (class="bg-red-500 text-white font-bold rounded-t px-4 py-2") {
"Error"
}
div (class="border border-t-0 border-red-400 rounded-b bg-red-100 px-4 py-3 text-red-700"){
p {(state.error.get())}
}
}
}},
false => {view!{cx,}},
})
div {
label (class="text-sm font-medium text-gray-900 block mb-2 dark:text-gray-300") {"Username"}
input (bind:value = state.username, class="bg-gray-50 border border-gray-300 text-gray-900 sm:text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-600 dark:border-gray-500 dark:placeholder-gray-400 dark:text-white") {}
}
div {
label (class="text-sm font-medium text-gray-900 block mb-2 dark:text-gray-300"){"Password"}
input (bind:value = state.password, type = "password", class="bg-gray-50 border border-gray-300 text-gray-900 sm:text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-600 dark:border-gray-500 dark:placeholder-gray-400 dark:text-white"){}
}
div (class="flex justify-between"){
(match props.remember_me {
true => { view!{ cx,
div (class="flex items-start"){
div (class="flex items-center h-5"){
input (bind:checked = state.remember_me, type = "checkbox", class="w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600") {}
}
div (class="text-sm ml-3"){
label (class="font-medium text-gray-900 dark:text-gray-300"){"Remember me"}
}
}
}},
false => view!{cx, },
})
button (on:click = handle_forgot_password, class="text-sm text-blue-700 hover:underline dark:text-blue-500"){"Lost Password?"}
}
button (on:click = handle_log_in, class="w-full text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800"){"Log in"}
div (class="text-sm font-medium text-gray-500 dark:text-gray-300"){
button (on:click = handle_register, class="text-blue-700 hover:underline dark:text-blue-500"){"Create account"}
}
}
}
}
}
}
}
pub fn get_capsule<G: Html>() -> Capsule<G, LoginFormProps> {
Capsule::build(Template::build("login_form").build_state_fn(get_build_state))
.empty_fallback()
.view_with_state(login_form_capsule)
.build()
}
#[engine_only_fn]
async fn get_build_state(_info: StateGeneratorInfo<()>) -> LoginFormState {
LoginFormState {
username: String::new(),
password: String::new(),
remember_me: false,
error: String::new(),
}
}

3
src/capsules/mod.rs Normal file
View File

@@ -0,0 +1,3 @@
pub mod forgot_password_form;
pub mod login_form;
pub mod register_form;

View File

@@ -0,0 +1,203 @@
use lazy_static::lazy_static;
use perseus::prelude::*;
use serde::{Deserialize, Serialize};
use sycamore::prelude::*;
use web_sys::Event;
cfg_if::cfg_if! {
if #[cfg(client)] {
use crate::{
models::auth::{RegisterRequest},
endpoints::REGISTER,
state_enums::OpenState,
templates::get_api_path,
global_state::AppStateRx,
models::{
generic::GenericResponse
},
};
use reqwest::StatusCode;
}
}
lazy_static! {
pub static ref REGISTER_FORM: Capsule<PerseusNodeType, RegisterFormProps> = get_capsule();
}
#[derive(Serialize, Deserialize, Clone, ReactiveState)]
#[rx(alias = "RegisterFormStateRx")]
struct RegisterFormState {
username: String,
password: String,
nickname: String,
registration_code: String,
email: String,
error: String,
}
impl RegisterFormStateRx {
#[cfg(client)]
fn reset(&self) {
self.username.set(String::new());
self.password.set(String::new());
self.nickname.set(String::new());
self.registration_code.set(String::new());
self.email.set(String::new());
self.error.set(String::new());
}
}
#[derive(Clone)]
pub struct RegisterFormProps {
pub nickname: bool,
pub registration_code: bool,
pub email: bool,
}
#[auto_scope]
fn register_form_capsule<G: Html>(
cx: Scope,
state: &RegisterFormStateRx,
props: RegisterFormProps,
) -> View<G> {
let close_modal = move |_event: Event| {
#[cfg(client)]
{
spawn_local_scoped(cx, async move {
state.reset();
let global_state = Reactor::<G>::from_cx(cx).get_global_state::<AppStateRx>(cx);
global_state.modals_open.register.set(OpenState::Closed)
});
}
};
let handle_register = move |_event: Event| {
#[cfg(client)]
{
let registration_code = state.registration_code.get().as_ref().clone();
spawn_local_scoped(cx, async move {
let register_info = RegisterRequest {
username: state.username.get().as_ref().clone(),
password: state.password.get().as_ref().clone(),
nickname: state.nickname.get().as_ref().clone(),
email: state.email.get().as_ref().clone(),
registration_code,
};
// // @todo clean up error handling
let client = reqwest::Client::new();
let response = client
.post(get_api_path(REGISTER).as_str())
.json(&register_info)
.send()
.await
.unwrap();
let global_state = Reactor::<G>::from_cx(cx).get_global_state::<AppStateRx>(cx);
let status = response.status();
let response_data = response.json::<GenericResponse>().await.unwrap();
if status != StatusCode::OK {
// todo update to some type of alert
state.error.set(response_data.status);
return;
}
// Open login modal
global_state.modals_open.login.set(OpenState::Open);
state.reset();
// Close modal
state.reset();
global_state.modals_open.register.set(OpenState::Closed);
});
}
};
view! { cx,
div (class="overflow-x-hidden overflow-y-auto fixed h-modal md:h-full top-4 left-0 right-0 md:inset-0 z-50 justify-center items-center"){
div (class="relative md:mx-auto w-full md:w-1/2 lg:w-1/3 z-0 my-10") {
div (class="bg-white rounded-lg shadow relative dark:bg-gray-700"){
div (class="flex justify-end p-2"){
button (on:click = close_modal, class="text-gray-400 bg-transparent hover:bg-gray-200 hover:text-gray-900 rounded-lg text-sm p-1.5 ml-auto inline-flex items-center dark:hover:bg-gray-800 dark:hover:text-white"){
"Close"
}
}
div (class="space-y-6 px-6 lg:px-8 pb-4 sm:pb-6 xl:pb-8") {
h3 (class="text-xl font-medium text-gray-900 dark:text-white"){"Register"}
(match state.error.get().as_ref() != "" {
true => { view!{cx,
div (role="alert") {
div (class="bg-red-500 text-white font-bold rounded-t px-4 py-2") {
"Error"
}
div (class="border border-t-0 border-red-400 rounded-b bg-red-100 px-4 py-3 text-red-700"){
p {(state.error.get())}
}
}
}},
false => {view!{cx,}},
})
div {
label (class="text-sm font-medium text-gray-900 block mb-2 dark:text-gray-300") {"Username"}
input (bind:value = state.username, class="bg-gray-50 border border-gray-300 text-gray-900 sm:text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-600 dark:border-gray-500 dark:placeholder-gray-400 dark:text-white") {}
}
div {
label (class="text-sm font-medium text-gray-900 block mb-2 dark:text-gray-300"){"Password"}
input (bind:value = state.password, type = "password", class="bg-gray-50 border border-gray-300 text-gray-900 sm:text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-600 dark:border-gray-500 dark:placeholder-gray-400 dark:text-white"){}
}
(match props.registration_code {
true => { view!{cx,
div {
label (class="text-sm font-medium text-gray-900 block mb-2 dark:text-gray-300"){"Registration code"}
input (bind:value = state.registration_code, class="bg-gray-50 border border-gray-300 text-gray-900 sm:text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-600 dark:border-gray-500 dark:placeholder-gray-400 dark:text-white"){}
}
}},
false => {view!{cx,}},
})
(match props.nickname {
true => { view!{cx,
div {
label (class="text-sm font-medium text-gray-900 block mb-2 dark:text-gray-300"){"Nickname (optional)"}
input (bind:value = state.nickname, class="bg-gray-50 border border-gray-300 text-gray-900 sm:text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-600 dark:border-gray-500 dark:placeholder-gray-400 dark:text-white"){}
}
}},
false => {view!{cx,}},
})
(match props.email {
true => { view!{cx,
div {
label (class="text-sm font-medium text-gray-900 block mb-2 dark:text-gray-300"){"Email (optional)"}
input (bind:value = state.email, class="bg-gray-50 border border-gray-300 text-gray-900 sm:text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-600 dark:border-gray-500 dark:placeholder-gray-400 dark:text-white"){}
}
}},
false => {view!{cx,}},
})
button (on:click = handle_register, class="w-full text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800"){"Register"}
}
}
}
}
}
}
pub fn get_capsule<G: Html>() -> Capsule<G, RegisterFormProps> {
Capsule::build(Template::build("register_form").build_state_fn(get_build_state))
.empty_fallback()
.view_with_state(register_form_capsule)
.build()
}
#[engine_only_fn]
async fn get_build_state(_info: StateGeneratorInfo<()>) -> RegisterFormState {
RegisterFormState {
username: String::new(),
password: String::new(),
error: String::new(),
nickname: String::new(),
registration_code: String::new(),
email: String::new(),
}
}

105
src/components/header.rs Normal file
View File

@@ -0,0 +1,105 @@
use perseus::prelude::*;
use sycamore::prelude::*;
use web_sys::Event;
use crate::{
global_state::AppStateRx,
state_enums::{GameState, LoginState},
};
cfg_if::cfg_if! {
if #[cfg(client)] {
use crate::{
state_enums::OpenState,
};
}
}
#[derive(Prop)]
pub struct HeaderProps {
pub game: GameState,
}
#[component]
pub fn Header<G: Html>(cx: Scope, props: HeaderProps) -> View<G> {
// Get global state to get authentication info
let global_state = Reactor::<G>::from_cx(cx).get_global_state::<AppStateRx>(cx);
let handle_log_in = move |_event: Event| {
#[cfg(client)]
{
spawn_local_scoped(cx, async move {
let global_state = Reactor::<G>::from_cx(cx).get_global_state::<AppStateRx>(cx);
global_state.modals_open.login.set(OpenState::Open);
});
}
};
let handle_register = move |_event: Event| {
#[cfg(client)]
{
spawn_local_scoped(cx, async move {
let global_state = Reactor::<G>::from_cx(cx).get_global_state::<AppStateRx>(cx);
global_state.modals_open.register.set(OpenState::Open);
});
}
};
let handle_log_out = move |_event: Event| {
#[cfg(client)]
{
spawn_local_scoped(cx, async move {
let global_state = Reactor::<G>::from_cx(cx).get_global_state::<AppStateRx>(cx);
global_state.auth.handle_log_out();
});
}
};
view! { cx,
header {
div (class = "flex items-center justify-between w-full md:text-center h-20") {
div(class = "flex-1") {}
// Title
div(class = "text-gray-700 text-2xl font-semibold py-2") {
(props.game.to_string()) " - Season 1"
}
// Login / register or user buttons
div(class = "flex-1 py-2") {(
match *global_state.auth.state.get() {
LoginState::NotAuthenticated => {
view! { cx,
button(on:click = handle_register, class = "text-gray-900 bg-white border border-gray-300 focus:outline-none hover:bg-gray-100 focus:ring-4 focus:ring-gray-100 font-medium rounded-lg text-sm px-5 py-2.5 me-2 mb-2 dark:bg-gray-800 dark:text-white dark:border-gray-600 dark:hover:bg-gray-700 dark:hover:border-gray-600 dark:focus:ring-gray-700") {
"Register"
}
button(on:click = handle_log_in, class = "text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 me-2 mb-2 dark:bg-blue-600 dark:hover:bg-blue-700 focus:outline-none dark:focus:ring-blue-800") {
"Log in"
}
}
}
LoginState::Authenticated => {
view! { cx,
div {
"Hello "
(global_state.auth.username.get().as_ref().clone().unwrap_or("".to_owned()))
}
button(on:click = handle_log_out, class = "text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 me-2 mb-2 dark:bg-blue-600 dark:hover:bg-blue-700 focus:outline-none dark:focus:ring-blue-800") {
"Log out"
}
}
}
// Will only appear for a few seconds
LoginState::Unknown => {
view! { cx,
div (class = "px-5 py-2.5 me-2 mb-2"){
"Loading..."
}
}
},
})
}
}
}
}
}

View File

@@ -1,30 +1,114 @@
use crate::{
capsules::{
forgot_password_form::{ForgotPasswordFormProps, FORGOT_PASSWORD_FORM},
login_form::{LoginFormProps, LOGIN_FORM},
register_form::{RegisterFormProps, REGISTER_FORM},
},
components::header::Header,
global_state::AppStateRx,
state_enums::{GameState, OpenState},
};
use perseus::prelude::*;
use sycamore::prelude::*;
#[derive(Prop)]
pub struct LayoutProps<'a, G: Html> {
pub game: GameState,
pub children: Children<'a, G>,
}
// Using elements from here: https://flowbite.com/docs/components/buttons/
#[component]
pub fn Layout<'a, G: Html>(
cx: Scope<'a>,
LayoutProps { title, children }: LayoutProps<'a, G>,
LayoutProps { game, children }: LayoutProps<'a, G>,
) -> View<G> {
let children = children.call(cx);
let global_state = Reactor::<G>::from_cx(cx).get_global_state::<AppStateRx>(cx);
// Check if the client is authenticated or not
#[cfg(client)]
global_state.auth.detect_state();
view! { cx,
// These elements are styled with bright colors for demonstration purposes
header(style = "background-color: red; color: white; padding: 1rem") {
p { (title.to_string()) }
// Main page header, including login functionality
Header(game = game)
// Modals
section(class = "flex-2") {
(match *global_state.modals_open.login.get() {
OpenState::Open => {
view! { cx,
(LOGIN_FORM.widget(cx, "",
LoginFormProps{
remember_me: true,
}
main(style = "padding: 1rem") {
(children)
}
footer(style = "background-color: black; color: white; padding: 1rem") {
p { "Hey there, I'm a footer!" }
))
}
}
OpenState::Closed => {
view!{ cx, }
}
})
(match *global_state.modals_open.register.get() {
OpenState::Open => {
view! { cx,
(REGISTER_FORM.widget(cx, "",
RegisterFormProps{
registration_code: true,
nickname: true,
email: true,
}
))
}
}
OpenState::Closed => {
view!{ cx, }
}
})
(match *global_state.modals_open.forgot_password.get() {
OpenState::Open => {
view! { cx,
(FORGOT_PASSWORD_FORM.widget(cx, "",
ForgotPasswordFormProps{}
))
}
}
OpenState::Closed => {
view!{ cx, }
}
})
}
#[derive(Prop)]
pub struct LayoutProps<'a, G: Html> {
/// The title of the page, which will be displayed in the header.
pub title: &'a str,
/// The content to put inside the layout.
pub children: Children<'a, G>,
main(style = "my-8") {
// Body header
div {
div (class = "container mx-auto px-6 py-3") {
nav (class = "sm:flex sm:justify-center sm:items-center mt-4 hidden") {
div (class = "flex flex-col sm:flex-row"){
a(href = "add-game-form",
class = "mt-3 text-gray-600 hover:underline sm:mx-3 sm:mt-0"
) { "Add game result" }
a(href = "one-v-one-board",
class = "mt-3 text-gray-600 hover:underline sm:mx-3 sm:mt-0"
) { "1v1 Leaderboard" }
a(href = "overall-board",
class = "mt-3 text-gray-600 hover:underline sm:mx-3 sm:mt-0"
) { "Overall Leaderboard" }
}
}
}
}
// Content body
div(class = "container mx-auto px-6") {
div(class = "md:flex mt-8 md:-mx-4") {
div(class = "rounded-md overflow-hidden bg-cover bg-center") {
(children)
}
}
}
}
}
}

View File

@@ -1 +1,2 @@
mod header;
pub mod layout;

6
src/endpoints.rs Normal file
View File

@@ -0,0 +1,6 @@
pub const REGISTER: &str = "/api/register";
pub const LOGIN: &str = "/api/login";
// TODO -> remove once it's used
#[cfg(engine)]
pub const LOGIN_TEST: &str = "/api/login-test";
pub const FORGOT_PASSWORD: &str = "/api/forgot-password";

37
src/entity/game.rs Normal file
View File

@@ -0,0 +1,37 @@
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.0
use super::sea_orm_active_enums::GameType;
use sea_orm::entity::prelude::*;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq, Serialize, Deserialize)]
#[sea_orm(table_name = "game")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i32,
pub time: DateTimeWithTimeZone,
pub game_type: Option<GameType>,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
#[sea_orm(has_many = "super::game_to_team_result::Entity")]
GameToTeamResult,
}
impl Related<super::game_to_team_result::Entity> for Entity {
fn to() -> RelationDef {
Relation::GameToTeamResult.def()
}
}
impl Related<super::team_result::Entity> for Entity {
fn to() -> RelationDef {
super::game_to_team_result::Relation::TeamResult.def()
}
fn via() -> Option<RelationDef> {
Some(super::game_to_team_result::Relation::Game.def().rev())
}
}
impl ActiveModelBehavior for ActiveModel {}

View File

@@ -0,0 +1,47 @@
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.0
use sea_orm::entity::prelude::*;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq, Serialize, Deserialize)]
#[sea_orm(table_name = "game_to_team_result")]
pub struct Model {
#[sea_orm(primary_key, auto_increment = false)]
pub game_id: i32,
#[sea_orm(primary_key, auto_increment = false)]
pub team_result_id: i32,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
#[sea_orm(
belongs_to = "super::game::Entity",
from = "Column::GameId",
to = "super::game::Column::Id",
on_update = "NoAction",
on_delete = "NoAction"
)]
Game,
#[sea_orm(
belongs_to = "super::team_result::Entity",
from = "Column::TeamResultId",
to = "super::team_result::Column::Id",
on_update = "NoAction",
on_delete = "NoAction"
)]
TeamResult,
}
impl Related<super::game::Entity> for Entity {
fn to() -> RelationDef {
Relation::Game.def()
}
}
impl Related<super::team_result::Entity> for Entity {
fn to() -> RelationDef {
Relation::TeamResult.def()
}
}
impl ActiveModelBehavior for ActiveModel {}

10
src/entity/mod.rs Normal file
View File

@@ -0,0 +1,10 @@
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.0
pub mod prelude;
pub mod game;
pub mod game_to_team_result;
pub mod sea_orm_active_enums;
pub mod team_result;
pub mod team_result_to_user;
pub mod user;

7
src/entity/prelude.rs Normal file
View File

@@ -0,0 +1,7 @@
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.0
pub use super::game::Entity as Game;
pub use super::game_to_team_result::Entity as GameToTeamResult;
pub use super::team_result::Entity as TeamResult;
pub use super::team_result_to_user::Entity as TeamResultToUser;
pub use super::user::Entity as User;

View File

@@ -0,0 +1,15 @@
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.0
use sea_orm::entity::prelude::*;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, Eq, EnumIter, DeriveActiveEnum, Serialize, Deserialize)]
#[sea_orm(rs_type = "String", db_type = "Enum", enum_name = "game_type")]
pub enum GameType {
#[sea_orm(string_value = "PickleBall")]
PickleBall,
#[sea_orm(string_value = "Pool")]
Pool,
#[sea_orm(string_value = "TableTennis")]
TableTennis,
}

53
src/entity/team_result.rs Normal file
View File

@@ -0,0 +1,53 @@
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.0
use sea_orm::entity::prelude::*;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq, Serialize, Deserialize)]
#[sea_orm(table_name = "team_result")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i32,
pub place: i32,
pub score: Option<i32>,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
#[sea_orm(has_many = "super::game_to_team_result::Entity")]
GameToTeamResult,
#[sea_orm(has_many = "super::team_result_to_user::Entity")]
TeamResultToUser,
}
impl Related<super::game_to_team_result::Entity> for Entity {
fn to() -> RelationDef {
Relation::GameToTeamResult.def()
}
}
impl Related<super::team_result_to_user::Entity> for Entity {
fn to() -> RelationDef {
Relation::TeamResultToUser.def()
}
}
impl Related<super::game::Entity> for Entity {
fn to() -> RelationDef {
super::game_to_team_result::Relation::Game.def()
}
fn via() -> Option<RelationDef> {
Some(super::game_to_team_result::Relation::TeamResult.def().rev())
}
}
impl Related<super::user::Entity> for Entity {
fn to() -> RelationDef {
super::team_result_to_user::Relation::User.def()
}
fn via() -> Option<RelationDef> {
Some(super::team_result_to_user::Relation::TeamResult.def().rev())
}
}
impl ActiveModelBehavior for ActiveModel {}

View File

@@ -0,0 +1,47 @@
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.0
use sea_orm::entity::prelude::*;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq, Serialize, Deserialize)]
#[sea_orm(table_name = "team_result_to_user")]
pub struct Model {
#[sea_orm(primary_key, auto_increment = false)]
pub team_result_id: i32,
#[sea_orm(primary_key, auto_increment = false)]
pub user_id: i32,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
#[sea_orm(
belongs_to = "super::team_result::Entity",
from = "Column::TeamResultId",
to = "super::team_result::Column::Id",
on_update = "NoAction",
on_delete = "NoAction"
)]
TeamResult,
#[sea_orm(
belongs_to = "super::user::Entity",
from = "Column::UserId",
to = "super::user::Column::Id",
on_update = "NoAction",
on_delete = "NoAction"
)]
User,
}
impl Related<super::team_result::Entity> for Entity {
fn to() -> RelationDef {
Relation::TeamResult.def()
}
}
impl Related<super::user::Entity> for Entity {
fn to() -> RelationDef {
Relation::User.def()
}
}
impl ActiveModelBehavior for ActiveModel {}

44
src/entity/user.rs Normal file
View File

@@ -0,0 +1,44 @@
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.0
use sea_orm::entity::prelude::*;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq, Serialize, Deserialize)]
#[sea_orm(table_name = "user")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i32,
#[sea_orm(unique)]
pub username: String,
pub password_hash_and_salt: String,
pub nickname: Option<String>,
pub creation_time: DateTime,
pub last_active_time: DateTime,
pub is_admin: bool,
pub email: Option<String>,
pub avatar: Option<String>,
pub forgot_password_request: Option<String>,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
#[sea_orm(has_many = "super::team_result_to_user::Entity")]
TeamResultToUser,
}
impl Related<super::team_result_to_user::Entity> for Entity {
fn to() -> RelationDef {
Relation::TeamResultToUser.def()
}
}
impl Related<super::team_result::Entity> for Entity {
fn to() -> RelationDef {
super::team_result_to_user::Relation::TeamResult.def()
}
fn via() -> Option<RelationDef> {
Some(super::team_result_to_user::Relation::User.def().rev())
}
}
impl ActiveModelBehavior for ActiveModel {}

143
src/global_state.rs Normal file
View File

@@ -0,0 +1,143 @@
// Not a page, global state that is shared between all pages
use perseus::{prelude::*, state::GlobalStateCreator};
use serde::{Deserialize, Serialize};
use crate::{
models::auth::WebAuthInfo,
state_enums::{LoginState, OpenState},
};
#[derive(Serialize, Deserialize, ReactiveState, Clone)]
#[rx(alias = "AppStateRx")]
pub struct AppState {
#[rx(nested)]
pub auth: AuthData,
#[rx(nested)]
pub modals_open: ModalOpenData,
}
#[derive(Serialize, Deserialize, ReactiveState, Clone)]
#[rx(alias = "AuthDataRx")]
pub struct AuthData {
pub state: LoginState,
pub username: Option<String>,
pub remember_me: Option<bool>,
pub auth_info: Option<WebAuthInfo>,
}
impl AuthDataRx {
#[cfg(client)]
pub fn handle_log_in(&self, auth_info: WebAuthInfo) {
// Save new token to persistent storage
if auth_info.remember_me {
let storage: web_sys::Storage =
web_sys::window().unwrap().local_storage().unwrap().unwrap();
let value = serde_json::to_string(&auth_info).unwrap();
storage.set_item("auth", &value).unwrap();
}
// Save into session storage always
let storage: web_sys::Storage = web_sys::window()
.unwrap()
.session_storage()
.unwrap()
.unwrap();
let value = serde_json::to_string(&auth_info).unwrap();
storage.set_item("auth", &value).unwrap();
// Save token to session storage
self.username.set(Some(auth_info.username.clone()));
self.remember_me.set(Some(auth_info.remember_me));
self.auth_info.set(Some(auth_info));
self.state.set(LoginState::Authenticated);
}
#[cfg(client)]
pub fn handle_log_out(&self) {
// Delete persistent storage
// TODO -> handle error if local storage is not readable in browser
let storage: web_sys::Storage =
web_sys::window().unwrap().local_storage().unwrap().unwrap();
storage.remove_item("auth").unwrap();
let storage: web_sys::Storage = web_sys::window()
.unwrap()
.session_storage()
.unwrap()
.unwrap();
storage.remove_item("auth").unwrap();
// Update state
self.auth_info.set(None);
self.username.set(None);
self.remember_me.set(None);
self.state.set(LoginState::NotAuthenticated);
}
}
#[derive(Serialize, Deserialize, ReactiveState, Clone)]
#[rx(alias = "ModalOpenDataRx")]
pub struct ModalOpenData {
pub login: OpenState,
pub register: OpenState,
pub forgot_password: OpenState,
}
pub fn get_global_state_creator() -> GlobalStateCreator {
GlobalStateCreator::new().build_state_fn(get_build_state)
}
#[engine_only_fn]
pub async fn get_build_state() -> AppState {
AppState {
auth: AuthData {
state: LoginState::Unknown,
username: None,
remember_me: None,
auth_info: None,
},
modals_open: ModalOpenData {
login: OpenState::Closed,
register: OpenState::Closed,
forgot_password: OpenState::Closed,
},
}
}
// Client only code to check if they're authenticated
#[cfg(client)]
impl AuthDataRx {
pub fn detect_state(&self) {
// If the user is in a known state, return
if let LoginState::Authenticated | LoginState::NotAuthenticated = *self.state.get() {
return;
}
// TODO handle error case better
// Save new token to persistent storage
let storage: web_sys::Storage =
web_sys::window().unwrap().local_storage().unwrap().unwrap();
let saved_auth = storage.get("auth").unwrap();
match saved_auth {
Some(auth_info) => {
// TODO check if session is expiring
let auth_info = serde_json::from_str(&auth_info).unwrap();
self.handle_log_in(auth_info);
}
None => {
// Try session storage
let storage: web_sys::Storage = web_sys::window()
.unwrap()
.session_storage()
.unwrap()
.unwrap();
let saved_auth = storage.get("auth").unwrap();
match saved_auth {
Some(auth_info) => {
let auth_info = serde_json::from_str(&auth_info).unwrap();
self.handle_log_in(auth_info);
}
None => {
self.state.set(LoginState::NotAuthenticated);
}
}
}
}
}
}

View File

@@ -1,29 +1,93 @@
mod capsules;
mod components;
mod templates;
mod endpoints;
#[allow(unused_imports)]
mod entity;
mod error_views;
mod global_state;
mod models;
#[cfg(engine)]
mod server;
mod state_enums;
mod templates;
use perseus::prelude::*;
use sycamore::prelude::view;
#[perseus::main(perseus_axum::dflt_server)]
cfg_if::cfg_if! {
if #[cfg(engine)] {
use std::net::SocketAddr;
use perseus::{
i18n::TranslationsManager,
server::ServerOptions,
stores::MutableStore,
turbine::Turbine,
};
use crate::server::routes::get_api_router;
use crate::server::server_state::ServerState;
use futures::executor::block_on;
use sea_orm::Database;
}
}
#[cfg(engine)]
pub async fn dflt_server<M: MutableStore + 'static, T: TranslationsManager + 'static>(
turbine: &'static Turbine<M, T>,
opts: ServerOptions,
(host, port): (String, u16),
) {
let addr: SocketAddr = format!("{}:{}", host, port)
.parse()
.expect("Invalid address provided to bind to.");
let app = perseus_axum::get_router(turbine, opts).await;
// TODO -> Update to use environment variable
// TODO -> error handling
// Includes making database connection
let db_conn = Database::connect("postgres://elo:elo@localhost:5432/elo_app");
let db_conn = block_on(db_conn);
let db_conn = match db_conn {
Ok(db_conn) => db_conn,
Err(err) => {
panic!("{}", err);
}
};
let state = ServerState { db_conn };
// Get server routes
let api_router = get_api_router(state);
let app = app.merge(api_router);
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await
.unwrap();
}
#[perseus::main(dflt_server)]
pub fn main<G: Html>() -> PerseusApp<G> {
use log::{info, warn};
env_logger::init();
PerseusApp::new()
.global_state_creator(crate::global_state::get_global_state_creator())
.template(crate::templates::index::get_template())
.template(crate::templates::long::get_template())
.template(crate::templates::add_game_form::get_template())
.template(crate::templates::one_v_one_board::get_template())
.template(crate::templates::overall_board::get_template())
.capsule_ref(&*crate::capsules::login_form::LOGIN_FORM)
.capsule_ref(&*crate::capsules::forgot_password_form::FORGOT_PASSWORD_FORM)
.capsule_ref(&*crate::capsules::register_form::REGISTER_FORM)
.error_views(crate::error_views::get_error_views())
.index_view(|cx| {
view! { cx,
html {
html (class = "flex w-full h-full"){
head {
meta(charset = "UTF-8")
meta(name = "viewport", content = "width=device-width, initial-scale=1.0")
// Perseus automatically resolves `/.perseus/static/` URLs to the contents of the `static/` directory at the project root
link(rel = "stylesheet", href = ".perseus/static/style.css")
}
body {
body (class = "w-full"){
// Quirk: this creates a wrapper `<div>` around the root `<div>` by necessity
PerseusRoot()
}

48
src/models/auth.rs Normal file
View File

@@ -0,0 +1,48 @@
use chrono::serde::ts_seconds;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Clone)]
pub struct LoginInfo {
pub username: String,
pub password: String,
pub remember_me: bool,
}
#[derive(Serialize, Deserialize, Clone)]
pub struct LoginResponse {
pub token: String,
#[serde(with = "ts_seconds")]
pub expires: DateTime<Utc>,
}
#[derive(Serialize, Deserialize, Clone)]
pub struct Claims {
pub sub: String,
pub exp: usize,
}
// For client local storage and session storage
#[derive(Serialize, Deserialize, Clone)]
pub struct WebAuthInfo {
pub token: String,
#[serde(with = "ts_seconds")]
pub expires: DateTime<Utc>,
pub username: String,
pub remember_me: bool,
}
#[derive(Serialize, Deserialize, Clone)]
pub struct RegisterRequest {
pub username: String,
pub password: String,
pub email: String,
pub nickname: String,
pub registration_code: String,
}
#[derive(Serialize, Deserialize, Clone)]
pub struct ForgotPasswordRequest {
pub username: String,
pub contact_info: String,
}

21
src/models/generic.rs Normal file
View File

@@ -0,0 +1,21 @@
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Clone)]
pub struct GenericResponse {
pub status: String,
}
impl GenericResponse {
#[cfg(engine)]
pub fn ok() -> Self {
GenericResponse {
status: String::new(),
}
}
#[cfg(engine)]
pub fn err(msg: &str) -> Self {
GenericResponse {
status: msg.to_string(),
}
}
}

2
src/models/mod.rs Normal file
View File

@@ -0,0 +1,2 @@
pub mod auth;
pub mod generic;

View File

@@ -0,0 +1,40 @@
use crate::{
entity::{prelude::*, user},
models::{auth::ForgotPasswordRequest, generic::GenericResponse},
server::server_state::ServerState,
};
use axum::{
extract::{Json, State},
http::StatusCode,
};
use sea_orm::{ActiveModelTrait, ColumnTrait, EntityTrait, IntoActiveModel, QueryFilter, Set};
pub async fn post_forgot_password(
State(state): State<ServerState>,
Json(password_request): Json<ForgotPasswordRequest>,
) -> (StatusCode, Json<GenericResponse>) {
// Get user
let existing_user: Option<user::Model> = User::find()
.filter(user::Column::Username.eq(password_request.username))
.one(&state.db_conn)
.await
.unwrap();
match existing_user {
Some(user) => {
let mut user = user.into_active_model();
user.forgot_password_request = Set(Some(password_request.contact_info));
let user = user.update(&state.db_conn).await;
match user {
Ok(_) => (StatusCode::OK, Json(GenericResponse::ok())),
Err(_) => (
StatusCode::BAD_REQUEST,
Json(GenericResponse::err("Database error")),
),
}
}
None => (
StatusCode::BAD_REQUEST,
Json(GenericResponse::err("Username doesn't exist")),
),
}
}

115
src/server/auth/login.rs Normal file
View File

@@ -0,0 +1,115 @@
use crate::{
entity::{
prelude::*,
user::{self},
},
models::{
auth::{Claims, LoginInfo, LoginResponse},
generic::GenericResponse,
},
server::server_state::ServerState,
};
use argon2::{Argon2, PasswordHash, PasswordVerifier};
use axum::{
extract::{Json, State},
http::{HeaderMap, StatusCode},
};
use jsonwebtoken::{decode, encode, DecodingKey, EncodingKey, Header, Validation};
use sea_orm::{ColumnTrait, EntityTrait, QueryFilter};
pub async fn credentials_are_correct(
username: &str,
password: &str,
state: &ServerState,
) -> Result<(), String> {
// Get user
let existing_user: Option<user::Model> = User::find()
.filter(user::Column::Username.eq(username))
.one(&state.db_conn)
.await
.unwrap();
let hash_to_check: String = match existing_user {
Some(user) => user.password_hash_and_salt,
None => {
// @todo make dummy password hash
return Err("Username doesn't exist".to_owned());
}
};
match Argon2::default().verify_password(
password.as_bytes(),
&PasswordHash::new(hash_to_check.as_str()).unwrap(),
) {
Ok(_) => Ok(()),
Err(_) => Err("Invalid credentials".to_owned()),
}
}
pub async fn post_login_user(
State(state): State<ServerState>,
Json(login_info): Json<LoginInfo>,
) -> (
StatusCode,
Result<Json<LoginResponse>, Json<GenericResponse>>,
) {
let user_authenticated =
credentials_are_correct(&login_info.username, &login_info.password, &state);
match user_authenticated.await {
Err(why) => (
StatusCode::UNAUTHORIZED,
Err(Json(GenericResponse::err(why.as_str()))),
),
Ok(_) => {
let expires = match login_info.remember_me {
true => chrono::Utc::now() + chrono::Duration::days(365),
false => chrono::Utc::now() + chrono::Duration::days(1),
};
let claims = Claims {
sub: login_info.username.clone(),
exp: expires.timestamp() as usize,
};
// @todo change secret
let token = match encode(
&Header::default(),
&claims,
&EncodingKey::from_secret("secret".as_ref()),
) {
Ok(token) => token,
Err(_) => {
return (
StatusCode::INTERNAL_SERVER_ERROR,
Err(Json(GenericResponse::err("Failed to get token"))),
)
}
};
(StatusCode::OK, Ok(Json(LoginResponse { token, expires })))
}
}
}
pub async fn post_test_login(
State(_): State<ServerState>,
header_map: HeaderMap,
) -> Result<Json<String>, StatusCode> {
if let Some(auth_header) = header_map.get("Authorization") {
if let Ok(auth_header_str) = auth_header.to_str() {
if auth_header_str.starts_with("Bearer ") {
let token = auth_header_str.trim_start_matches("Bearer ").to_string();
// @todo change secret
if decode::<Claims>(
&token,
&DecodingKey::from_secret("secret".as_ref()),
&Validation::default(),
)
.is_ok()
{
return Ok(Json("Logged in".to_owned()));
}
}
}
}
Err(StatusCode::UNAUTHORIZED)
}

3
src/server/auth/mod.rs Normal file
View File

@@ -0,0 +1,3 @@
pub mod forgot_password;
pub mod login;
pub mod register;

View File

@@ -0,0 +1,86 @@
use crate::{
entity::{prelude::*, user},
models::{auth::RegisterRequest, generic::GenericResponse},
server::server_state::ServerState,
};
use argon2::{
password_hash::{rand_core::OsRng, SaltString},
Argon2, PasswordHash, PasswordHasher,
};
use axum::{extract::State, http::StatusCode, Json};
use chrono::Utc;
use sea_orm::{ColumnTrait, EntityTrait, QueryFilter, Set};
pub async fn post_register_user(
State(state): State<ServerState>,
Json(register_info): Json<RegisterRequest>,
) -> (StatusCode, Json<GenericResponse>) {
// TODO -> update to use env, maybe prevent brute force too
if register_info.registration_code != "ferris" {
return (
StatusCode::UNAUTHORIZED,
Json(GenericResponse::err("Incorrect registration code")),
);
}
// See if username already exists
let username = register_info.username;
let existing_user: Option<user::Model> = User::find()
.filter(user::Column::Username.eq(username.clone()))
.one(&state.db_conn)
.await
.unwrap();
if existing_user.is_some() {
return (
StatusCode::BAD_REQUEST,
Json(GenericResponse::err("Username already exists")),
);
}
// Generate password
let salt = SaltString::generate(&mut OsRng);
let argon2 = Argon2::default();
let password_hash = argon2
.hash_password(register_info.password.as_bytes(), &salt)
.unwrap()
.to_string();
let phc_string = PasswordHash::new(&password_hash).unwrap().to_string();
// If the username doen't exist, create the user
let new_user = user::ActiveModel {
username: Set(username),
password_hash_and_salt: Set(phc_string),
nickname: Set({
if register_info.nickname.is_empty() {
None
} else {
Some(register_info.nickname)
}
}),
creation_time: Set(Utc::now().naive_utc()),
last_active_time: Set(Utc::now().naive_utc()),
is_admin: Set(false),
email: Set({
if register_info.email.is_empty() {
None
} else {
Some(register_info.email)
}
}),
avatar: Set(None),
forgot_password_request: Set(None),
..Default::default()
};
let db_resp = user::Entity::insert(new_user).exec(&state.db_conn).await;
match db_resp {
Ok(_) => {}
Err(_) => {
return (
StatusCode::INTERNAL_SERVER_ERROR,
Json(GenericResponse::err("Database error")),
);
}
};
(StatusCode::OK, Json(GenericResponse::ok()))
}

3
src/server/mod.rs Normal file
View File

@@ -0,0 +1,3 @@
pub mod auth;
pub mod routes;
pub mod server_state;

21
src/server/routes.rs Normal file
View File

@@ -0,0 +1,21 @@
// (Server only) Routes
use crate::endpoints::{FORGOT_PASSWORD, LOGIN, LOGIN_TEST, REGISTER};
use axum::routing::{post, Router};
use super::{
auth::{
forgot_password::post_forgot_password,
login::{post_login_user, post_test_login},
register::post_register_user,
},
server_state::ServerState,
};
pub fn get_api_router(state: ServerState) -> Router {
Router::new()
.route(REGISTER, post(post_register_user))
.route(LOGIN, post(post_login_user))
.route(LOGIN_TEST, post(post_test_login))
.route(FORGOT_PASSWORD, post(post_forgot_password))
.with_state(state)
}

View File

@@ -0,0 +1,6 @@
use sea_orm::DatabaseConnection;
#[derive(Clone)]
pub struct ServerState {
pub db_conn: DatabaseConnection,
}

39
src/state_enums.rs Normal file
View File

@@ -0,0 +1,39 @@
use std::fmt::Display;
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Clone)]
pub enum LoginState {
Authenticated,
NotAuthenticated,
Unknown,
}
#[derive(Serialize, Deserialize, Clone)]
pub enum GameState {
None,
Pool,
Pickleball,
TableTennis,
}
impl Display for GameState {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}",
match self {
GameState::None => "",
GameState::Pool => "Pool",
GameState::Pickleball => "Pickle Ball",
GameState::TableTennis => "Table Tennis",
}
)
}
}
#[derive(Serialize, Deserialize, Clone)]
pub enum OpenState {
Open,
Closed,
}

View File

@@ -0,0 +1,99 @@
use crate::{components::layout::Layout, state_enums::GameState};
use perseus::prelude::*;
use serde::{Deserialize, Serialize};
use sycamore::prelude::*;
use web_sys::Event;
// Reactive page
#[derive(Serialize, Deserialize, Clone, ReactiveState)]
#[rx(alias = "PageStateRx")]
struct PageState {
winner: String,
new_user: String,
}
fn add_game_form_page<'a, G: Html>(cx: BoundedScope<'_, 'a>, state: &'a PageStateRx) -> View<G> {
let handle_add_match = move |_event: Event| {
#[cfg(client)]
{
// state.winner.get().as_ref().clone()
spawn_local_scoped(cx, async move {})
}
};
let handle_add_user = move |_event: Event| {
#[cfg(client)]
{
// state.winner.get().as_ref().clone()
spawn_local_scoped(cx, async move {})
}
};
view! { cx,
Layout(game = GameState::Pool) {
div (class = "flex flex-wrap") {
select {
option (value="red")
option (value="blue")
}
}
div (class = "flex flex-wrap") {
input (bind:value = state.winner,
class = "appearance-none block w-full bg-gray-200 text-gray-700 border \
border-red-500 rounded py-3 px-4 mb-3 leading-tight focus:outline-none \
focus:bg-white",)
}
div (class = "flex flex-wrap") {
button(on:click = handle_add_match,
class = "flex-shrink-0 bg-teal-500 hover:bg-teal-700 border-teal-500 \
hover:border-teal-700 text-sm border-4 text-white py-1 px-2 rounded",
) {
"Add result"
}
}
div (class = "flex flex-wrap") {
input (bind:value = state.new_user,
class = "appearance-none block w-full bg-gray-200 text-gray-700 border \
border-red-500 rounded py-3 px-4 mb-3 leading-tight focus:outline-none \
focus:bg-white",)
}
div (class = "flex flex-wrap") {
button(on:click = handle_add_user,
class = "flex-shrink-0 bg-teal-500 hover:bg-teal-700 border-teal-500 \
hover:border-teal-700 text-sm border-4 text-white py-1 px-2 rounded",
) {
"Add new user"
}
}
}
}
}
#[engine_only_fn]
async fn get_request_state(
_info: StateGeneratorInfo<()>,
_req: Request,
) -> Result<PageState, BlamedError<std::convert::Infallible>> {
Ok(PageState {
winner: "Ferris".to_owned(),
new_user: "newguy".to_owned(),
})
}
#[engine_only_fn]
fn head(cx: Scope) -> View<SsrNode> {
view! { cx,
title { "Add Game Form" }
}
}
// Template
pub fn get_template<G: Html>() -> Template<G> {
Template::build("add-game-form")
.request_state_fn(get_request_state)
.view_with_state(add_game_form_page)
.head(head)
.build()
}

View File

@@ -0,0 +1,66 @@
// Not a page, global state that is shared between all pages
use perseus::{prelude::*, state::GlobalStateCreator};
use serde::{Deserialize, Serialize};
use crate::{
models::auth::Claims,
state_enums::{LoginState, OpenState},
};
#[derive(Serialize, Deserialize, ReactiveState, Clone)]
#[rx(alias = "AppStateRx")]
pub struct AppState {
#[rx(nested)]
pub auth: AuthData,
#[rx(nested)]
pub modals_open: ModalOpenData,
}
#[derive(Serialize, Deserialize, ReactiveState, Clone)]
#[rx(alias = "AuthDataRx")]
pub struct AuthData {
pub state: LoginState,
pub username: Option<String>,
pub claims: Claims,
}
#[derive(Serialize, Deserialize, ReactiveState, Clone)]
#[rx(alias = "ModalOpenDataRx")]
pub struct ModalOpenData {
pub login: OpenState,
}
pub fn get_global_state_creator() -> GlobalStateCreator {
GlobalStateCreator::new().build_state_fn(get_build_state)
}
#[engine_only_fn]
pub async fn get_build_state() -> AppState {
AppState {
auth: AuthData {
state: LoginState::Unknown,
username: None,
claims: Claims {
sub: "".to_owned(),
exp: 0,
},
},
modals_open: ModalOpenData {
login: OpenState::Closed,
},
}
}
// Client only code to check if they're authenticated
#[cfg(client)]
impl AuthDataRx {
pub fn detect_state(&self) {
// If the user is in a known state, return
if let LoginState::Authenticated | LoginState::NotAuthenticated = *self.state.get() {
return;
}
// TODO -> Get state from storage
self.state.set(LoginState::NotAuthenticated);
}
}

View File

@@ -1,15 +1,13 @@
use crate::components::layout::Layout;
use crate::{components::layout::Layout, state_enums::GameState};
use perseus::prelude::*;
use sycamore::prelude::*;
use crate::templates::get_path;
fn index_page<G: Html>(cx: Scope) -> View<G> {
view! { cx,
Layout(title = "Index") {
Layout(game = GameState::Pool) {
// Anything we put in here will be rendered inside the `<main>` block of the layout
p { "Hello World!" }
br {}
a(href = "long") { "Long page" }
}
}
}
@@ -22,8 +20,5 @@ fn head(cx: Scope) -> View<SsrNode> {
}
pub fn get_template<G: Html>() -> Template<G> {
Template::build(get_path("").as_str())
.view(index_page)
.head(head)
.build()
Template::build("").view(index_page).head(head).build()
}

View File

@@ -1,86 +0,0 @@
use crate::components::layout::Layout;
use perseus::prelude::*;
use serde::{Deserialize, Serialize};
use std::fs;
use sycamore::prelude::*;
use crate::templates::get_path;
// Reactive page
#[derive(Serialize, Deserialize, Clone, ReactiveState)]
#[rx(alias = "PageStateRx")]
struct PageState {
ip: String,
text: String,
}
fn request_state_page<'a, G: Html>(cx: BoundedScope<'_, 'a>, state: &'a PageStateRx) -> View<G> {
view! { cx,
p {
(
format!("Your IP address is {}.", state.ip.get())
)
}
p {
(
state.text.get().repeat(5000)
)
}
}
}
#[engine_only_fn]
async fn get_request_state(
_info: StateGeneratorInfo<()>,
req: Request,
) -> Result<PageState, BlamedError<std::convert::Infallible>> {
let text = fs::read_to_string("static/test.txt")
.unwrap_or("~".to_string())
.parse()
.unwrap();
Ok(PageState {
ip: format!(
"{:?}",
req.headers()
// NOTE: This header can be trivially spoofed, and may well not be the user's actual
// IP address
.get("X-Forwarded-For")
.unwrap_or(&perseus::http::HeaderValue::from_str("hidden from view!").unwrap())
),
text,
})
}
// Regular page
fn long_page<G: Html>(cx: Scope) -> View<G> {
view! { cx,
Layout(title = "Long") {
// Anything we put in here will be rendered inside the `<main>` block of the layout
a(href = "") { "Index" }
br {}
p {
("This is a test. ".repeat(5000))
}
}
}
}
#[engine_only_fn]
fn head(cx: Scope) -> View<SsrNode> {
view! { cx,
title { "Long Page" }
}
}
// Template
pub fn get_template<G: Html>() -> Template<G> {
// Template::build(get_full_path("long")).view(long_page).head(head).build()
Template::build(get_path("long").as_str())
.request_state_fn(get_request_state)
.view_with_state(request_state_page)
.head(head)
.build()
}

View File

@@ -1,17 +1,14 @@
use std::env;
pub mod add_game_form;
pub mod index;
pub mod long;
pub mod one_v_one_board;
pub mod overall_board;
pub fn get_path(path: &str) -> String {
// Get base path
match env::var("PERSEUS_BASE_PATH") {
Ok(env_path) => {
// Strip the slash on both sides for directory consistency
// let stripped_env = env_path.trim_start_matches("/").trim_end_matches("/");
// format!("{stripped_env}/{path}").to_string().trim_end_matches("/").to_owned()
path.to_owned()
}
Err(_) => path.to_owned(),
}
#[cfg(client)]
use perseus::utils::get_path_prefix_client;
#[cfg(client)]
pub fn get_api_path(path: &str) -> String {
let origin = web_sys::window().unwrap().origin();
let base_path = get_path_prefix_client();
format!("{}{}{}", origin, base_path, path)
}

View File

@@ -0,0 +1,39 @@
use crate::{components::layout::Layout, state_enums::GameState};
use perseus::prelude::*;
use serde::{Deserialize, Serialize};
use sycamore::prelude::*;
#[derive(Serialize, Deserialize, Clone, ReactiveState)]
#[rx(alias = "PageStateRx")]
struct PageState {}
fn one_v_one_board_page<'a, G: Html>(cx: BoundedScope<'_, 'a>, _state: &'a PageStateRx) -> View<G> {
view! { cx,
Layout(game = GameState::Pool) {
p { "leaderboard" }
}
}
}
#[engine_only_fn]
async fn get_request_state(
_info: StateGeneratorInfo<()>,
_req: Request,
) -> Result<PageState, BlamedError<std::convert::Infallible>> {
Ok(PageState {})
}
#[engine_only_fn]
fn head(cx: Scope) -> View<SsrNode> {
view! { cx,
title { "1v1 Leaderboard" }
}
}
pub fn get_template<G: Html>() -> Template<G> {
Template::build("one-v-one-board")
.request_state_fn(get_request_state)
.view_with_state(one_v_one_board_page)
.head(head)
.build()
}

View File

@@ -0,0 +1,46 @@
use crate::{components::layout::Layout, global_state::AppStateRx, state_enums::GameState};
use perseus::prelude::*;
use serde::{Deserialize, Serialize};
use sycamore::prelude::*;
#[derive(Serialize, Deserialize, Clone, ReactiveState)]
#[rx(alias = "PageStateRx")]
struct PageState {}
fn overall_board_page<'a, G: Html>(cx: BoundedScope<'_, 'a>, _state: &'a PageStateRx) -> View<G> {
let _global_state = Reactor::<G>::from_cx(cx).get_global_state::<AppStateRx>(cx);
view! { cx,
Layout(game = GameState::Pool) {
ul {
(View::new_fragment(
vec![],
))
}
}
}
}
#[engine_only_fn]
async fn get_request_state(
_info: StateGeneratorInfo<()>,
_req: Request,
) -> Result<PageState, BlamedError<std::convert::Infallible>> {
Ok(PageState {})
}
#[engine_only_fn]
fn head(cx: Scope) -> View<SsrNode> {
view! { cx,
title { "Overall leaderboard" }
}
}
pub fn get_template<G: Html>() -> Template<G> {
Template::build("overall-board")
.request_state_fn(get_request_state)
.view_with_state(overall_board_page)
.head(head)
.build()
}

View File

@@ -2,47 +2,3 @@
@tailwind components;
@tailwind utilities;
/* This removes the margins inserted by default around pages */
* {
margin: 0;
}
/* This makes all the elements that wrap our code take up the whole page, so that we can put things at the bottom.
* Without this, the footer would be just beneath the content if the content doesn't fill the whole page (try disabling this).
*/
html, body, #root {
height: 100%;
}
/* This makes the `<div>` that wraps our whole app use CSS Grid to display three sections: the header, content, and footer. */
#root {
display: grid;
grid-template-columns: 1fr;
/* The header will be automatically sized, the footer will be as small as possible, and the content will take up the rest of the space in the middle */
grid-template-rows: auto 1fr min-content;
grid-template-areas:
'header'
'main'
'footer';
}
header {
/* Put this in the right place in the grid */
grid-area: header;
/* Make this float over the content so it persists as we scroll */
position: fixed;
top: 0;
z-index: 99;
/* Make this span the whole page */
width: 100%;
}
main {
/* Put this in the right place in the grid */
grid-area: main;
/* The header is positioned 'floating' over the content, so we have to make sure this doesn't go behind the header, or it would be invisible.
* You may need to adjust this based on screen size, depending on how the header expands.
*/
margin-top: 5rem;
}
footer {
/* Put this in the right place in the grid */
grid-area: footer;
}