Compare commits
33 Commits
c2ecce0324
...
ft/integra
| Author | SHA1 | Date | |
|---|---|---|---|
| 3e2163dbf3 | |||
| 659037ec00 | |||
| 8be43c95d4 | |||
| 72bac10714 | |||
| ec2edd1d2a | |||
| a288a35225 | |||
| d82a5e2c65 | |||
| 97420b84c8 | |||
| 82648cfbae | |||
| 4cb809f20f | |||
| abbece5f53 | |||
| 510158f381 | |||
| d523373b8e | |||
| d25fb283cc | |||
| 988d0f9807 | |||
| 2409cd1f52 | |||
| 8714f65a0f | |||
| 893a9b5a06 | |||
| d6e62b98aa | |||
| aca0b83dd4 | |||
| 9a42ed5b80 | |||
| ed780c9585 | |||
| 1faaf65aad | |||
| df0d7d6c0d | |||
| 56ea1f12c7 | |||
| 5af626b746 | |||
| f4f491085d | |||
| 242f9b1218 | |||
| e376874afa | |||
| 65d47615da | |||
| 0f20ba3b86 | |||
| 99b4d9af1a | |||
| 462ca81a15 |
2
.github/workflows/github-actions-demo.yml
vendored
2
.github/workflows/github-actions-demo.yml
vendored
@@ -40,6 +40,8 @@ jobs:
|
|||||||
run: npm install -g sass
|
run: npm install -g sass
|
||||||
- name: Install tailwindcss via npm
|
- name: Install tailwindcss via npm
|
||||||
run: npm install -D tailwindcss
|
run: npm install -D tailwindcss
|
||||||
|
- name: Install daisy ui via npm
|
||||||
|
run: npm i -D daisyui@latest
|
||||||
- name: Compile css
|
- name: Compile css
|
||||||
run: npm run build
|
run: npm run build
|
||||||
# TODO -> Remove wasm-opt-version once perseus is updated
|
# TODO -> Remove wasm-opt-version once perseus is updated
|
||||||
|
|||||||
@@ -16,11 +16,9 @@ serde_json = "1"
|
|||||||
env_logger = "0.10.0"
|
env_logger = "0.10.0"
|
||||||
log = "0.4.20"
|
log = "0.4.20"
|
||||||
once_cell = "1.18.0"
|
once_cell = "1.18.0"
|
||||||
web-sys = "0.3.64"
|
web-sys = { version = "0.3.64", features = ["Window", "Storage"] }
|
||||||
cfg-if = "1.0.0"
|
cfg-if = "1.0.0"
|
||||||
chrono = { version = "0.4.38", features = ["serde", "wasm-bindgen"] }
|
chrono = { version = "0.4.38", features = ["serde", "wasm-bindgen"] }
|
||||||
axum-login = "0.15.3"
|
|
||||||
password-auth = "1.0.0"
|
|
||||||
lazy_static = "1.5"
|
lazy_static = "1.5"
|
||||||
|
|
||||||
[target.'cfg(engine)'.dev-dependencies]
|
[target.'cfg(engine)'.dev-dependencies]
|
||||||
@@ -38,6 +36,8 @@ sea-orm = { version = "1.0", features = [
|
|||||||
"macros",
|
"macros",
|
||||||
"with-chrono",
|
"with-chrono",
|
||||||
] }
|
] }
|
||||||
|
jsonwebtoken = "9.3.0"
|
||||||
|
argon2 = "0.5"
|
||||||
|
|
||||||
[target.'cfg(client)'.dependencies]
|
[target.'cfg(client)'.dependencies]
|
||||||
wasm-bindgen = "0.2.93"
|
wasm-bindgen = "0.2.93"
|
||||||
|
|||||||
@@ -16,11 +16,17 @@ Run `curl --proto '=https' --tlsv1.3 https://sh.rustup.rs -sSf | sh`
|
|||||||
https://nodejs.org/en
|
https://nodejs.org/en
|
||||||
(todo look into:)
|
(todo look into:)
|
||||||
https://pnpm.io/
|
https://pnpm.io/
|
||||||
|
`npm i -D daisyui@latest`
|
||||||
|
|
||||||
### Unix based systems:
|
### Unix based systems:
|
||||||
|
|
||||||
`sudo apt install nodejs`
|
`sudo apt install nodejs`
|
||||||
`sudo apt install npm`
|
`sudo apt install npm`
|
||||||
|
`npm i -D daisyui@latest`
|
||||||
|
|
||||||
|
For easy UI see:
|
||||||
|
|
||||||
|
https://daisyui.com/components/button/
|
||||||
|
|
||||||
## 3. Install Perseus, for real-time updates while developing
|
## 3. Install Perseus, for real-time updates while developing
|
||||||
|
|
||||||
|
|||||||
@@ -9,19 +9,21 @@ pub struct Migration;
|
|||||||
impl MigrationTrait for Migration {
|
impl MigrationTrait for Migration {
|
||||||
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
||||||
// User table
|
// User table
|
||||||
|
// @todo verify all data saved is length-checked
|
||||||
manager
|
manager
|
||||||
.create_table(
|
.create_table(
|
||||||
Table::create()
|
Table::create()
|
||||||
.table(User::Table)
|
.table(User::Table)
|
||||||
.col(pk_auto(User::Id))
|
.col(pk_auto(User::Id))
|
||||||
.col(string(User::Username))
|
.col(string_uniq(User::Username))
|
||||||
.col(string(User::Password))
|
.col(string(User::PasswordHashAndSalt))
|
||||||
.col(string(User::Salt))
|
.col(string_null(User::Nickname))
|
||||||
.col(timestamp_with_time_zone(User::CreationTime))
|
.col(timestamp(User::CreationTime))
|
||||||
.col(timestamp_with_time_zone(User::LastActiveTime))
|
.col(timestamp(User::LastActiveTime))
|
||||||
.col(boolean(User::IsAdmin))
|
.col(boolean(User::IsAdmin))
|
||||||
.col(string_null(User::Email))
|
.col(string_null(User::Email))
|
||||||
.col(string_null(User::Avatar))
|
.col(string_null(User::Avatar))
|
||||||
|
.col(string_null(User::ForgotPasswordRequest))
|
||||||
.to_owned(),
|
.to_owned(),
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
@@ -39,11 +41,12 @@ pub enum User {
|
|||||||
Table,
|
Table,
|
||||||
Id,
|
Id,
|
||||||
Username,
|
Username,
|
||||||
Password,
|
PasswordHashAndSalt,
|
||||||
Salt,
|
Nickname,
|
||||||
CreationTime,
|
CreationTime,
|
||||||
LastActiveTime,
|
LastActiveTime,
|
||||||
IsAdmin,
|
IsAdmin,
|
||||||
Email,
|
Email,
|
||||||
Avatar,
|
Avatar,
|
||||||
|
ForgotPasswordRequest,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,6 +11,7 @@
|
|||||||
"author": "",
|
"author": "",
|
||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"daisyui": "^4.12.10",
|
||||||
"tailwindcss": "^3.4.10"
|
"tailwindcss": "^3.4.10"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
159
src/capsules/forgot_password_form.rs
Normal file
159
src/capsules/forgot_password_form.rs
Normal file
@@ -0,0 +1,159 @@
|
|||||||
|
use lazy_static::lazy_static;
|
||||||
|
use perseus::prelude::*;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use sycamore::prelude::*;
|
||||||
|
use web_sys::Event;
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
components::{
|
||||||
|
static_components::close_button::CloseButtonSvg, sub_components::error_block::ErrorBlock,
|
||||||
|
},
|
||||||
|
global_state::AppStateRx,
|
||||||
|
};
|
||||||
|
|
||||||
|
cfg_if::cfg_if! {
|
||||||
|
if #[cfg(client)] {
|
||||||
|
use crate::{
|
||||||
|
state_enums::{ OpenState},
|
||||||
|
templates::get_api_path,
|
||||||
|
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> {
|
||||||
|
// If there's a tentative username, set it
|
||||||
|
let global_state = Reactor::<G>::from_cx(cx).get_global_state::<AppStateRx>(cx);
|
||||||
|
state
|
||||||
|
.username
|
||||||
|
.set((*global_state.auth.pending_username.get()).clone());
|
||||||
|
global_state.auth.pending_username.set(String::new());
|
||||||
|
|
||||||
|
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,
|
||||||
|
dialog (class="modal-open modal modal-bottom sm:modal-middle animate-none") {
|
||||||
|
div (class="modal-box"){
|
||||||
|
// Header row - title and close button
|
||||||
|
h3 (class="text-lg font-bold mb-4 text-center"){"Forgot Password"}
|
||||||
|
button (on:click = close_modal, class = "btn btn-circle right-2 top-2 absolute") { CloseButtonSvg {} }
|
||||||
|
|
||||||
|
// Add component for handling error messages
|
||||||
|
ErrorBlock(error = state.error.clone())
|
||||||
|
|
||||||
|
// Username field
|
||||||
|
div (class = "label") { span (class = "label-text") { "Username" } }
|
||||||
|
input (bind:value = state.username, class = "input input-bordered w-full")
|
||||||
|
|
||||||
|
// Password field
|
||||||
|
div (class = "label") { span (class = "label-text") { "Contact Info" } }
|
||||||
|
input (bind:value = state.how_to_reach, class = "input input-bordered w-full")
|
||||||
|
|
||||||
|
// Submit button
|
||||||
|
div (class = "flex justify-center mt-6") {
|
||||||
|
button (on:click = handle_submit, class="btn"){"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(),
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,72 +2,194 @@ use lazy_static::lazy_static;
|
|||||||
use perseus::prelude::*;
|
use perseus::prelude::*;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use sycamore::prelude::*;
|
use sycamore::prelude::*;
|
||||||
|
use web_sys::Event;
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
components::{
|
||||||
|
static_components::close_button::CloseButtonSvg, sub_components::error_block::ErrorBlock,
|
||||||
|
},
|
||||||
|
global_state::AppStateRx,
|
||||||
|
};
|
||||||
|
|
||||||
|
cfg_if::cfg_if! {
|
||||||
|
if #[cfg(client)] {
|
||||||
|
use crate::{
|
||||||
|
endpoints::LOGIN,
|
||||||
|
models::auth::{LoginInfo, LoginResponse, WebAuthInfo},
|
||||||
|
models::generic::GenericResponse,
|
||||||
|
state_enums::{OpenState},
|
||||||
|
templates::get_api_path,
|
||||||
|
};
|
||||||
|
use reqwest::StatusCode;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
lazy_static! {
|
lazy_static! {
|
||||||
pub static ref LOGIN_FORM: Capsule<PerseusNodeType, LoginFormProps> = get_capsule();
|
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]
|
#[auto_scope]
|
||||||
fn login_form_capsule<G: Html>(
|
fn login_form_capsule<G: Html>(
|
||||||
cx: Scope,
|
cx: Scope,
|
||||||
state: &LoginFormStateRx,
|
state: &LoginFormStateRx,
|
||||||
props: LoginFormProps,
|
props: LoginFormProps,
|
||||||
) -> View<G> {
|
) -> View<G> {
|
||||||
view! {
|
// If there's a tentative username, set it
|
||||||
cx,
|
let global_state = Reactor::<G>::from_cx(cx).get_global_state::<AppStateRx>(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"){
|
state
|
||||||
div (class="relative w-full max-w-md px-4 h-full md:h-auto") {
|
.username
|
||||||
div (class="bg-white rounded-lg shadow relative dark:bg-gray-700"){
|
.set((*global_state.auth.pending_username.get()).clone());
|
||||||
div (class="flex justify-end p-2"){
|
global_state.auth.pending_username.set(String::new());
|
||||||
button (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"){
|
|
||||||
"Back"
|
let close_modal = move |_event: Event| {
|
||||||
}
|
#[cfg(client)]
|
||||||
}
|
{
|
||||||
form (class="space-y-6 px-6 lg:px-8 pb-4 sm:pb-6 xl:pb-8") {
|
spawn_local_scoped(cx, async move {
|
||||||
h3 (class="text-xl font-medium text-gray-900 dark:text-white"){"Sign in to our platform"}
|
let global_state = Reactor::<G>::from_cx(cx).get_global_state::<AppStateRx>(cx);
|
||||||
div {
|
state.reset();
|
||||||
label (class="text-sm font-medium text-gray-900 block mb-2 dark:text-gray-300") {"Your email"}
|
global_state.modals_open.login.set(OpenState::Closed)
|
||||||
input (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"){"Your password"}
|
|
||||||
input (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"){
|
|
||||||
div (class="flex items-start"){
|
|
||||||
div (class="flex items-center h-5"){
|
|
||||||
input (class="bg-gray-50 border border-gray-300 focus:ring-3 focus:ring-blue-300 h-4 w-4 rounded dark:bg-gray-600 dark:border-gray-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800") {}
|
|
||||||
}
|
|
||||||
div (class="text-sm ml-3"){
|
|
||||||
label (class="font-medium text-gray-900 dark:text-gray-300"){"Remember me"}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
a (class="text-sm text-blue-700 hover:underline dark:text-blue-500"){"Lost Password?"}
|
|
||||||
}
|
|
||||||
button (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"){"Login to your account"}
|
|
||||||
div (class="text-sm font-medium text-gray-500 dark:text-gray-300"){
|
|
||||||
a (class="text-blue-700 hover:underline dark:text-blue-500"){"Create account"}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
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);
|
||||||
|
|
||||||
|
// Update tentative username
|
||||||
|
global_state
|
||||||
|
.auth
|
||||||
|
.pending_username
|
||||||
|
.set((*state.username.get()).clone());
|
||||||
|
|
||||||
|
// Open new modal
|
||||||
|
global_state
|
||||||
|
.modals_open
|
||||||
|
.forgot_password
|
||||||
|
.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());
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Clone, ReactiveState)]
|
let response = response.json::<LoginResponse>().await.unwrap();
|
||||||
#[rx(alias = "LoginFormStateRx")]
|
|
||||||
struct LoginFormState {
|
// Save token to session/local storage and update state
|
||||||
username: String,
|
global_state.auth.handle_log_in(WebAuthInfo {
|
||||||
password: String,
|
token: response.token,
|
||||||
|
expires: response.expires,
|
||||||
|
username,
|
||||||
|
remember_me,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Close modal
|
||||||
|
state.reset();
|
||||||
|
global_state.modals_open.login.set(OpenState::Closed);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
view! { cx,
|
||||||
|
dialog (class="modal-open modal modal-bottom sm:modal-middle") {
|
||||||
|
div (class="modal-box"){
|
||||||
|
// Header row - title and close button
|
||||||
|
h3 (class="text-lg font-bold mb-4 text-center"){"Sign in"}
|
||||||
|
button (on:click = close_modal, class = "btn btn-circle right-2 top-2 absolute") { CloseButtonSvg {} }
|
||||||
|
|
||||||
|
// Add component for handling error messages
|
||||||
|
ErrorBlock(error = state.error.clone())
|
||||||
|
|
||||||
|
// Username field
|
||||||
|
div (class = "label") { span (class = "label-text") { "Username" } }
|
||||||
|
input (bind:value = state.username, class = "input input-bordered w-full")
|
||||||
|
|
||||||
|
// Password field
|
||||||
|
div (class = "label") { span (class = "label-text") { "Password" } }
|
||||||
|
input (bind:value = state.password, type = "password", class = "input input-bordered w-full")
|
||||||
|
|
||||||
|
// Remember me button and forget password button
|
||||||
|
div (class="flex justify-between items-center mt-1"){
|
||||||
|
// Remember me button
|
||||||
|
(match props.remember_me {
|
||||||
|
true => { view!{ cx,
|
||||||
|
div (class = "flex items-start form-control") {
|
||||||
|
label (class = "label cursor-pointer") {
|
||||||
|
span (class = "label-text mr-4") { "Remember me" }
|
||||||
|
input (bind:checked = state.remember_me, type = "checkbox", class = "checkbox")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}},
|
||||||
|
false => view!{cx, },
|
||||||
|
})
|
||||||
|
// Forget password button
|
||||||
|
button (on:click = handle_forgot_password, class="flex link link-primary"){"Lost Password?"}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone)]
|
// Log in button
|
||||||
pub struct LoginFormProps {
|
div (class = "flex justify-center") {
|
||||||
pub remember_me: bool,
|
button (on:click = handle_log_in, class="btn"){"Log in"}
|
||||||
pub endpoint: String,
|
}
|
||||||
pub lost_password_url: Option<String>,
|
}
|
||||||
pub forgot_password_url: Option<String>,
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_capsule<G: Html>() -> Capsule<G, LoginFormProps> {
|
pub fn get_capsule<G: Html>() -> Capsule<G, LoginFormProps> {
|
||||||
@@ -80,7 +202,9 @@ pub fn get_capsule<G: Html>() -> Capsule<G, LoginFormProps> {
|
|||||||
#[engine_only_fn]
|
#[engine_only_fn]
|
||||||
async fn get_build_state(_info: StateGeneratorInfo<()>) -> LoginFormState {
|
async fn get_build_state(_info: StateGeneratorInfo<()>) -> LoginFormState {
|
||||||
LoginFormState {
|
LoginFormState {
|
||||||
username: "".to_string(),
|
username: String::new(),
|
||||||
password: "".to_string(),
|
password: String::new(),
|
||||||
|
remember_me: false,
|
||||||
|
error: String::new(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1 +1,3 @@
|
|||||||
|
pub mod forgot_password_form;
|
||||||
pub mod login_form;
|
pub mod login_form;
|
||||||
|
pub mod register_form;
|
||||||
|
|||||||
191
src/capsules/register_form.rs
Normal file
191
src/capsules/register_form.rs
Normal file
@@ -0,0 +1,191 @@
|
|||||||
|
use lazy_static::lazy_static;
|
||||||
|
use perseus::prelude::*;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use sycamore::prelude::*;
|
||||||
|
use web_sys::Event;
|
||||||
|
|
||||||
|
use crate::components::{
|
||||||
|
static_components::close_button::CloseButtonSvg, sub_components::error_block::ErrorBlock,
|
||||||
|
};
|
||||||
|
|
||||||
|
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(®ister_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;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update tentative username
|
||||||
|
global_state
|
||||||
|
.auth
|
||||||
|
.pending_username
|
||||||
|
.set((*state.username.get()).clone());
|
||||||
|
|
||||||
|
// Open login modal
|
||||||
|
global_state.modals_open.login.set(OpenState::Open);
|
||||||
|
|
||||||
|
// Close modal
|
||||||
|
state.reset();
|
||||||
|
global_state.modals_open.register.set(OpenState::Closed);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
view! { cx,
|
||||||
|
dialog (class="modal-open modal modal-bottom sm:modal-middle"){
|
||||||
|
div (class="modal-box") {
|
||||||
|
// Header row - title and close button
|
||||||
|
h3 (class="text-lg font-bold mb-4 text-center"){"Register"}
|
||||||
|
button (on:click = close_modal, class = "btn btn-circle right-2 top-2 absolute") { CloseButtonSvg {} }
|
||||||
|
|
||||||
|
// Add component for handling error messages
|
||||||
|
ErrorBlock(error = state.error.clone())
|
||||||
|
|
||||||
|
// Username field
|
||||||
|
div (class = "label") { span (class = "label-text") { "Username" } }
|
||||||
|
input (bind:value = state.username, class = "input input-bordered w-full")
|
||||||
|
|
||||||
|
// Password field
|
||||||
|
div (class = "label") { span (class = "label-text") { "Password" } }
|
||||||
|
input (bind:value = state.password, type = "password", class = "input input-bordered w-full")
|
||||||
|
|
||||||
|
(match props.registration_code {
|
||||||
|
true => { view! {cx,
|
||||||
|
div (class = "label") { span (class = "label-text") { "Registration Code" } }
|
||||||
|
input (bind:value = state.registration_code, class = "input input-bordered w-full")
|
||||||
|
}},
|
||||||
|
false => {view!{cx,}},
|
||||||
|
})
|
||||||
|
(match props.nickname {
|
||||||
|
true => { view! {cx,
|
||||||
|
div (class = "label") { span (class = "label-text") { "Nickname (Optional)" } }
|
||||||
|
input (bind:value = state.nickname, class = "input input-bordered w-full")
|
||||||
|
}},
|
||||||
|
false => {view!{cx,}},
|
||||||
|
})
|
||||||
|
(match props.email {
|
||||||
|
true => { view! {cx,
|
||||||
|
div (class = "label") { span (class = "label-text") { "Email (Optional)" } }
|
||||||
|
input (bind:value = state.email, class = "input input-bordered w-full")
|
||||||
|
}},
|
||||||
|
false => {view!{cx,}},
|
||||||
|
})
|
||||||
|
|
||||||
|
// Register button
|
||||||
|
div (class = "flex justify-center mt-6") {
|
||||||
|
button (on:click = handle_register, class="btn"){"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(),
|
||||||
|
}
|
||||||
|
}
|
||||||
171
src/components/header.rs
Normal file
171
src/components/header.rs
Normal file
@@ -0,0 +1,171 @@
|
|||||||
|
use perseus::prelude::*;
|
||||||
|
use sycamore::prelude::*;
|
||||||
|
use web_sys::Event;
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
components::static_components::menu_button::MenuButtonSvg,
|
||||||
|
global_state::AppStateRx,
|
||||||
|
state_enums::{ContentState, LoginState},
|
||||||
|
};
|
||||||
|
|
||||||
|
cfg_if::cfg_if! {
|
||||||
|
if #[cfg(client)] {
|
||||||
|
use crate::{
|
||||||
|
state_enums::OpenState,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Prop)]
|
||||||
|
pub struct HeaderProps {
|
||||||
|
pub content_state: ContentState,
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO update to have user preferences
|
||||||
|
#[component]
|
||||||
|
fn LinkList<G: Html>(cx: Scope) -> View<G> {
|
||||||
|
// Get global state to get style info
|
||||||
|
let global_state = Reactor::<G>::from_cx(cx).get_global_state::<AppStateRx>(cx);
|
||||||
|
|
||||||
|
view! { cx,
|
||||||
|
li {
|
||||||
|
a (href = "pool") {
|
||||||
|
label (class = "swap") {
|
||||||
|
input (
|
||||||
|
type="radio",
|
||||||
|
name = "theme-dropdown",
|
||||||
|
class = "theme-controller",
|
||||||
|
value = (*global_state.style.theme.pool.get()),
|
||||||
|
) {}
|
||||||
|
p (class = (
|
||||||
|
if *global_state.style.theme.current.get() == *global_state.style.theme.pool.get(){
|
||||||
|
"font-bold"
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
""
|
||||||
|
}
|
||||||
|
)){ "Pool" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
li {
|
||||||
|
a (href = "table_tennis") {
|
||||||
|
label (class = "swap") {
|
||||||
|
input (
|
||||||
|
type="radio",
|
||||||
|
name = "theme-dropdown",
|
||||||
|
class = "theme-controller",
|
||||||
|
value = (*global_state.style.theme.table_tennis.get()),
|
||||||
|
) {}
|
||||||
|
p (class = (
|
||||||
|
if *global_state.style.theme.current.get() == *global_state.style.theme.table_tennis.get(){
|
||||||
|
"font-bold"
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
""
|
||||||
|
}
|
||||||
|
)){ "Table Tennis" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
li {
|
||||||
|
a (href = "pickleball") {
|
||||||
|
label (class = "swap") {
|
||||||
|
input (
|
||||||
|
type="radio",
|
||||||
|
name = "theme-dropdown",
|
||||||
|
class = "theme-controller",
|
||||||
|
value = (*global_state.style.theme.pickleball.get()),
|
||||||
|
) {}
|
||||||
|
p (class = (
|
||||||
|
if *global_state.style.theme.current.get() == *global_state.style.theme.pickleball.get(){
|
||||||
|
"font-bold"
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
""
|
||||||
|
}
|
||||||
|
)){ "Pickleball" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[component]
|
||||||
|
pub fn Header<G: Html>(cx: Scope, props: HeaderProps) -> View<G> {
|
||||||
|
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 (class="navbar bg-base-100") {
|
||||||
|
// Navigation
|
||||||
|
div (class="navbar-start") {
|
||||||
|
div (class="dropdown") {
|
||||||
|
div (tabindex="0", role="button", class="btn btn-ghost lg:hidden") { MenuButtonSvg {} }
|
||||||
|
ul (tabindex = "0", class = "menu menu-sm dropdown-content bg-base-100 rounded-box z-[1] mt-3 w-52 p-2 shadow" ) {
|
||||||
|
LinkList {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ul (class="menu menu-horizontal px-1 hidden lg:flex") {
|
||||||
|
LinkList {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Title
|
||||||
|
div (class="navbar-center lg:flex") {
|
||||||
|
(props.content_state.to_string())
|
||||||
|
}
|
||||||
|
// User buttons
|
||||||
|
div (class="navbar-end") {
|
||||||
|
(match *global_state.auth.state.get() {
|
||||||
|
LoginState::Authenticated => { view! { cx,
|
||||||
|
button(on:click = handle_log_out, class = "btn btn-primary mr-2") {
|
||||||
|
"Log out"
|
||||||
|
}
|
||||||
|
} },
|
||||||
|
LoginState::NotAuthenticated => { view! { cx,
|
||||||
|
button(on:click = handle_register, class = "btn btn-primary mr-2") {
|
||||||
|
"Register"
|
||||||
|
}
|
||||||
|
button(on:click = handle_log_in, class = "btn btn-secondary mr-2") {
|
||||||
|
"Log in"
|
||||||
|
}
|
||||||
|
} },
|
||||||
|
LoginState::Unknown => { view! { cx,
|
||||||
|
div (class = "px-5 py-2.5 me-2 mb-2") {
|
||||||
|
"Loading..."
|
||||||
|
}
|
||||||
|
} },
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,14 +1,19 @@
|
|||||||
use crate::{
|
use crate::{
|
||||||
capsules::login_form::{LoginFormProps, LOGIN_FORM},
|
capsules::{
|
||||||
templates::global_state::{AppStateRx, LoginState},
|
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::{ContentState, OpenState},
|
||||||
};
|
};
|
||||||
use perseus::prelude::*;
|
use perseus::prelude::*;
|
||||||
use sycamore::prelude::*;
|
use sycamore::prelude::*;
|
||||||
use web_sys::Event;
|
|
||||||
|
|
||||||
#[derive(Prop)]
|
#[derive(Prop)]
|
||||||
pub struct LayoutProps<'a, G: Html> {
|
pub struct LayoutProps<'a, G: Html> {
|
||||||
pub _title: &'a str,
|
pub content_state: ContentState,
|
||||||
pub children: Children<'a, G>,
|
pub children: Children<'a, G>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -18,105 +23,106 @@ pub struct LayoutProps<'a, G: Html> {
|
|||||||
pub fn Layout<'a, G: Html>(
|
pub fn Layout<'a, G: Html>(
|
||||||
cx: Scope<'a>,
|
cx: Scope<'a>,
|
||||||
LayoutProps {
|
LayoutProps {
|
||||||
_title: _,
|
content_state,
|
||||||
children,
|
children,
|
||||||
}: LayoutProps<'a, G>,
|
}: LayoutProps<'a, G>,
|
||||||
) -> View<G> {
|
) -> View<G> {
|
||||||
let children = children.call(cx);
|
|
||||||
// Get global state to get authentication info
|
|
||||||
let global_state = Reactor::<G>::from_cx(cx).get_global_state::<AppStateRx>(cx);
|
let global_state = Reactor::<G>::from_cx(cx).get_global_state::<AppStateRx>(cx);
|
||||||
|
// Set the theme
|
||||||
|
global_state.style.theme.current.set(match content_state {
|
||||||
|
ContentState::None => (*global_state.style.theme.default.get()).clone(),
|
||||||
|
ContentState::Pool => (*global_state.style.theme.pool.get()).clone(),
|
||||||
|
ContentState::Pickleball => (*global_state.style.theme.pickleball.get()).clone(),
|
||||||
|
ContentState::TableTennis => (*global_state.style.theme.table_tennis.get()).clone(),
|
||||||
|
});
|
||||||
|
#[cfg(client)]
|
||||||
|
let _ = web_sys::window()
|
||||||
|
.unwrap()
|
||||||
|
.document()
|
||||||
|
.unwrap()
|
||||||
|
.document_element()
|
||||||
|
.unwrap()
|
||||||
|
.set_attribute("data-theme", &global_state.style.theme.current.get());
|
||||||
|
|
||||||
|
let children = children.call(cx);
|
||||||
|
|
||||||
// Check if the client is authenticated or not
|
// Check if the client is authenticated or not
|
||||||
#[cfg(client)]
|
#[cfg(client)]
|
||||||
global_state.auth.detect_state();
|
global_state.auth.detect_state();
|
||||||
|
|
||||||
// TODO -> move into function
|
let content_state_header = content_state.clone();
|
||||||
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.auth.state.set(LoginState::Authenticated);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
view! { cx,
|
view! { cx,
|
||||||
// Main page header
|
// Main page header, including login functionality
|
||||||
header {
|
Header(content_state = content_state_header)
|
||||||
div (class = "flex items-center justify-between w-full md:text-center h-20") {
|
|
||||||
div(class = "flex-1") {}
|
|
||||||
div(class = "text-gray-700 text-2xl font-semibold py-2") {
|
|
||||||
"Pool Elo - Season 1"
|
|
||||||
}
|
|
||||||
|
|
||||||
div(class = "flex-1 py-2") {(
|
// Modals
|
||||||
match *global_state.auth.state.get() {
|
section(class = "flex-2") {
|
||||||
LoginState::NotAuthenticated => {
|
(match *global_state.modals_open.login.get() {
|
||||||
|
OpenState::Open => {
|
||||||
view! { cx,
|
view! { cx,
|
||||||
button(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") {
|
|
||||||
"Login"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
LoginState::Authenticated => {
|
|
||||||
view! { cx,
|
|
||||||
div {
|
|
||||||
"Hello {username}!"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Will only appear for a few seconds
|
|
||||||
LoginState::Unknown => {
|
|
||||||
view! { cx,
|
|
||||||
div (class = "px-5 py-2.5 me-2 mb-2"){
|
|
||||||
"Loading..."
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
main(style = "my-8") {
|
|
||||||
|
|
||||||
(
|
|
||||||
match *global_state.auth.state.get() {
|
|
||||||
LoginState::Authenticated => { view! { cx,
|
|
||||||
(LOGIN_FORM.widget(cx, "",
|
(LOGIN_FORM.widget(cx, "",
|
||||||
LoginFormProps{
|
LoginFormProps{
|
||||||
remember_me: true,
|
remember_me: true,
|
||||||
endpoint: "".to_string(),
|
}
|
||||||
lost_password_url: Some("".to_string()),
|
))
|
||||||
forgot_password_url: Some("".to_string())
|
}
|
||||||
|
}
|
||||||
|
OpenState::Closed => {
|
||||||
|
view!{ cx, }
|
||||||
|
}
|
||||||
})
|
})
|
||||||
)
|
(match *global_state.modals_open.register.get() {
|
||||||
}},
|
OpenState::Open => {
|
||||||
_ => { view! { cx, div {} } }})
|
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, }
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
main(style = "my-8") {
|
||||||
|
(match content_state {
|
||||||
|
ContentState::None => view!{ cx, },
|
||||||
|
ContentState::Pool => view!{ cx,
|
||||||
// Body header
|
// Body header
|
||||||
div {
|
|
||||||
div (class = "container mx-auto px-6 py-3") {
|
div (class = "container mx-auto px-6 py-3") {
|
||||||
nav (class = "sm:flex sm:justify-center sm:items-center mt-4 hidden") {
|
nav (class = "sm:flex sm:justify-center sm:items-center mt-4 hidden") {
|
||||||
div (class = "flex flex-col sm:flex-row"){
|
div (class = "flex flex-col sm:flex-row"){
|
||||||
a(href = "add-game-form",
|
a(href = "pool/add-game-form",
|
||||||
class = "mt-3 text-gray-600 hover:underline sm:mx-3 sm:mt-0"
|
class = "mt-3 text-gray-600 hover:underline sm:mx-3 sm:mt-0"
|
||||||
) { "Add game result" }
|
) { "Add game result" }
|
||||||
a(href = "one-v-one-board",
|
a(href = "pool/one-v-one-board",
|
||||||
class = "mt-3 text-gray-600 hover:underline sm:mx-3 sm:mt-0"
|
class = "mt-3 text-gray-600 hover:underline sm:mx-3 sm:mt-0"
|
||||||
) { "1v1 Leaderboard" }
|
) { "1v1 Leaderboard" }
|
||||||
a(href = "overall-board",
|
a(href = "pool/overall-board",
|
||||||
class = "mt-3 text-gray-600 hover:underline sm:mx-3 sm:mt-0"
|
class = "mt-3 text-gray-600 hover:underline sm:mx-3 sm:mt-0"
|
||||||
) { "Overall Leaderboard" }
|
) { "Overall Leaderboard" }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
// Content body
|
||||||
// Actual body
|
|
||||||
div(class = "container mx-auto px-6") {
|
div(class = "container mx-auto px-6") {
|
||||||
div(class = "md:flex mt-8 md:-mx-4") {
|
div(class = "md:flex mt-8 md:-mx-4") {
|
||||||
div(class = "rounded-md overflow-hidden bg-cover bg-center") {
|
div(class = "rounded-md overflow-hidden bg-cover bg-center") {
|
||||||
@@ -124,6 +130,10 @@ pub fn Layout<'a, G: Html>(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
ContentState::Pickleball => view!{ cx, },
|
||||||
|
ContentState::TableTennis => view!{ cx, },
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1 +1,4 @@
|
|||||||
|
mod header;
|
||||||
pub mod layout;
|
pub mod layout;
|
||||||
|
pub mod static_components;
|
||||||
|
pub mod sub_components;
|
||||||
|
|||||||
21
src/components/static_components/close_button.rs
Normal file
21
src/components/static_components/close_button.rs
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
use perseus::prelude::*;
|
||||||
|
use sycamore::prelude::*;
|
||||||
|
|
||||||
|
#[component]
|
||||||
|
pub fn CloseButtonSvg<G: Html>(cx: Scope) -> View<G> {
|
||||||
|
view! { cx,
|
||||||
|
svg (
|
||||||
|
xmlns = "http://www.w3.org/2000/svg",
|
||||||
|
class = "h-6 w-6 stroke-primary",
|
||||||
|
fill = "none",
|
||||||
|
viewBox = "0 0 24 24",
|
||||||
|
) {
|
||||||
|
path (
|
||||||
|
stroke-linecap = "round",
|
||||||
|
stroke-linejoin = "round",
|
||||||
|
stroke-width = "2",
|
||||||
|
d = "M6 18L18 6M6 6l12 12"
|
||||||
|
){}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
22
src/components/static_components/indicator.rs
Normal file
22
src/components/static_components/indicator.rs
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
use perseus::prelude::*;
|
||||||
|
use sycamore::prelude::*;
|
||||||
|
|
||||||
|
#[component]
|
||||||
|
pub fn ErrorSvg<G: Html>(cx: Scope) -> View<G> {
|
||||||
|
view! { cx,
|
||||||
|
svg (
|
||||||
|
xmlns="http://www.w3.org/2000/svg",
|
||||||
|
class="h-6 w-6 shrink-0 stroke-current",
|
||||||
|
fill="none",
|
||||||
|
viewBox="0 0 24 24",
|
||||||
|
)
|
||||||
|
{
|
||||||
|
path (
|
||||||
|
stroke-linecap="round",
|
||||||
|
stroke-linejoin="round",
|
||||||
|
stroke-width="2",
|
||||||
|
d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z",
|
||||||
|
){}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
20
src/components/static_components/menu_button.rs
Normal file
20
src/components/static_components/menu_button.rs
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
use perseus::prelude::*;
|
||||||
|
use sycamore::prelude::*;
|
||||||
|
|
||||||
|
#[component]
|
||||||
|
pub fn MenuButtonSvg<G: Html>(cx: Scope) -> View<G> {
|
||||||
|
view! { cx,
|
||||||
|
svg (
|
||||||
|
xmlns="http://www.w3.org/2000/svg",
|
||||||
|
class="h-5 w-5",
|
||||||
|
fill="none",
|
||||||
|
viewBox="0 0 24 24",
|
||||||
|
stroke="currentColor"){
|
||||||
|
path (
|
||||||
|
stroke-linecap="round",
|
||||||
|
stroke-linejoin="round",
|
||||||
|
stroke-width="2",
|
||||||
|
d="M4 6h16M4 12h8m-8 6h16") {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
3
src/components/static_components/mod.rs
Normal file
3
src/components/static_components/mod.rs
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
pub mod close_button;
|
||||||
|
pub mod indicator;
|
||||||
|
pub mod menu_button;
|
||||||
25
src/components/sub_components/error_block.rs
Normal file
25
src/components/sub_components/error_block.rs
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
use perseus::prelude::*;
|
||||||
|
use sycamore::prelude::*;
|
||||||
|
|
||||||
|
use crate::components::static_components::indicator::ErrorSvg;
|
||||||
|
|
||||||
|
#[component(inline_props)]
|
||||||
|
pub fn ErrorBlock<'a, G: Html>(cx: Scope<'a>, error: RcSignal<String>) -> View<G> {
|
||||||
|
let error = create_ref(cx, error);
|
||||||
|
let is_empty = create_selector(cx, || error.get().is_empty());
|
||||||
|
|
||||||
|
view! { cx,
|
||||||
|
(match !(*is_empty.get()) {
|
||||||
|
true => { view!{cx,
|
||||||
|
div (role="alert", class="alert alert-error") {
|
||||||
|
// Error icon
|
||||||
|
ErrorSvg {}
|
||||||
|
|
||||||
|
// Error text
|
||||||
|
span {(*error.get())}
|
||||||
|
}
|
||||||
|
}},
|
||||||
|
false => {view!{cx,}},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
1
src/components/sub_components/mod.rs
Normal file
1
src/components/sub_components/mod.rs
Normal file
@@ -0,0 +1 @@
|
|||||||
|
pub mod error_block;
|
||||||
@@ -1,2 +1,6 @@
|
|||||||
pub const MATCH: &str = "/api/post-match";
|
pub const REGISTER: &str = "/api/register";
|
||||||
pub const USER: &str = "/api/post-user";
|
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";
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.0-rc.5
|
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.0
|
||||||
|
|
||||||
use super::sea_orm_active_enums::GameType;
|
use super::sea_orm_active_enums::GameType;
|
||||||
use sea_orm::entity::prelude::*;
|
use sea_orm::entity::prelude::*;
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.0-rc.5
|
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.0
|
||||||
|
|
||||||
use sea_orm::entity::prelude::*;
|
use sea_orm::entity::prelude::*;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.0-rc.5
|
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.0
|
||||||
|
|
||||||
pub mod prelude;
|
pub mod prelude;
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.0-rc.5
|
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.0
|
||||||
|
|
||||||
pub use super::game::Entity as Game;
|
pub use super::game::Entity as Game;
|
||||||
pub use super::game_to_team_result::Entity as GameToTeamResult;
|
pub use super::game_to_team_result::Entity as GameToTeamResult;
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.0-rc.5
|
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.0
|
||||||
|
|
||||||
use sea_orm::entity::prelude::*;
|
use sea_orm::entity::prelude::*;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.0-rc.5
|
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.0
|
||||||
|
|
||||||
use sea_orm::entity::prelude::*;
|
use sea_orm::entity::prelude::*;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.0-rc.5
|
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.0
|
||||||
|
|
||||||
use sea_orm::entity::prelude::*;
|
use sea_orm::entity::prelude::*;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.0-rc.5
|
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.0
|
||||||
|
|
||||||
use sea_orm::entity::prelude::*;
|
use sea_orm::entity::prelude::*;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
@@ -8,14 +8,16 @@ use serde::{Deserialize, Serialize};
|
|||||||
pub struct Model {
|
pub struct Model {
|
||||||
#[sea_orm(primary_key)]
|
#[sea_orm(primary_key)]
|
||||||
pub id: i32,
|
pub id: i32,
|
||||||
|
#[sea_orm(unique)]
|
||||||
pub username: String,
|
pub username: String,
|
||||||
pub password: String,
|
pub password_hash_and_salt: String,
|
||||||
pub salt: String,
|
pub nickname: Option<String>,
|
||||||
pub creation_time: DateTimeWithTimeZone,
|
pub creation_time: DateTime,
|
||||||
pub last_active_time: DateTimeWithTimeZone,
|
pub last_active_time: DateTime,
|
||||||
pub is_admin: bool,
|
pub is_admin: bool,
|
||||||
pub email: Option<String>,
|
pub email: Option<String>,
|
||||||
pub avatar: Option<String>,
|
pub avatar: Option<String>,
|
||||||
|
pub forgot_password_request: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
|
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
|
||||||
|
|||||||
173
src/global_state.rs
Normal file
173
src/global_state.rs
Normal file
@@ -0,0 +1,173 @@
|
|||||||
|
// 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,
|
||||||
|
#[rx(nested)]
|
||||||
|
pub style: StyleData,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize, ReactiveState, Clone)]
|
||||||
|
#[rx(alias = "AuthDataRx")]
|
||||||
|
pub struct AuthData {
|
||||||
|
pub state: LoginState,
|
||||||
|
pub pending_username: String,
|
||||||
|
pub username: Option<String>,
|
||||||
|
pub remember_me: Option<bool>,
|
||||||
|
pub auth_info: Option<WebAuthInfo>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize, ReactiveState, Clone)]
|
||||||
|
#[rx(alias = "ModalOpenDataRx")]
|
||||||
|
pub struct ModalOpenData {
|
||||||
|
pub login: OpenState,
|
||||||
|
pub register: OpenState,
|
||||||
|
pub forgot_password: OpenState,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize, ReactiveState, Clone)]
|
||||||
|
#[rx(alias = "StyleDataRx")]
|
||||||
|
pub struct StyleData {
|
||||||
|
#[rx(nested)]
|
||||||
|
pub theme: ThemeData,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize, ReactiveState, Clone)]
|
||||||
|
#[rx(alias = "ThemeDataRx")]
|
||||||
|
pub struct ThemeData {
|
||||||
|
pub current: String,
|
||||||
|
pub pool: String,
|
||||||
|
pub pickleball: String,
|
||||||
|
pub table_tennis: String,
|
||||||
|
pub default: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
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,
|
||||||
|
pending_username: String::new(),
|
||||||
|
username: None,
|
||||||
|
remember_me: None,
|
||||||
|
auth_info: None,
|
||||||
|
},
|
||||||
|
modals_open: ModalOpenData {
|
||||||
|
login: OpenState::Closed,
|
||||||
|
register: OpenState::Closed,
|
||||||
|
forgot_password: OpenState::Closed,
|
||||||
|
},
|
||||||
|
style: StyleData {
|
||||||
|
theme: ThemeData {
|
||||||
|
current: "light".to_owned(),
|
||||||
|
pool: "autumn".to_owned(),
|
||||||
|
pickleball: "lemonade".to_owned(),
|
||||||
|
table_tennis: "nord".to_owned(),
|
||||||
|
default: "light".to_owned(),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
43
src/main.rs
43
src/main.rs
@@ -4,8 +4,11 @@ mod endpoints;
|
|||||||
#[allow(unused_imports)]
|
#[allow(unused_imports)]
|
||||||
mod entity;
|
mod entity;
|
||||||
mod error_views;
|
mod error_views;
|
||||||
|
mod global_state;
|
||||||
|
mod models;
|
||||||
#[cfg(engine)]
|
#[cfg(engine)]
|
||||||
mod server;
|
mod server;
|
||||||
|
mod state_enums;
|
||||||
mod templates;
|
mod templates;
|
||||||
|
|
||||||
use perseus::prelude::*;
|
use perseus::prelude::*;
|
||||||
@@ -20,9 +23,10 @@ cfg_if::cfg_if! {
|
|||||||
stores::MutableStore,
|
stores::MutableStore,
|
||||||
turbine::Turbine,
|
turbine::Turbine,
|
||||||
};
|
};
|
||||||
|
use crate::server::routes::get_api_router;
|
||||||
|
use crate::server::server_state::ServerState;
|
||||||
use futures::executor::block_on;
|
use futures::executor::block_on;
|
||||||
use sea_orm::{Database};
|
use sea_orm::Database;
|
||||||
use crate::server::routes::register_routes;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -35,16 +39,24 @@ pub async fn dflt_server<M: MutableStore + 'static, T: TranslationsManager + 'st
|
|||||||
let addr: SocketAddr = format!("{}:{}", host, port)
|
let addr: SocketAddr = format!("{}:{}", host, port)
|
||||||
.parse()
|
.parse()
|
||||||
.expect("Invalid address provided to bind to.");
|
.expect("Invalid address provided to bind to.");
|
||||||
let mut app = perseus_axum::get_router(turbine, opts).await;
|
let app = perseus_axum::get_router(turbine, opts).await;
|
||||||
|
|
||||||
app = register_routes(app);
|
|
||||||
|
|
||||||
// TODO -> Update to use environment variable
|
// TODO -> Update to use environment variable
|
||||||
if let Err(err) = block_on(Database::connect(
|
// TODO -> error handling
|
||||||
"postgres://elo:elo@localhost:5432/elo_app",
|
// 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);
|
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)
|
axum::Server::bind(&addr)
|
||||||
.serve(app.into_make_service())
|
.serve(app.into_make_service())
|
||||||
@@ -57,16 +69,21 @@ pub fn main<G: Html>() -> PerseusApp<G> {
|
|||||||
env_logger::init();
|
env_logger::init();
|
||||||
|
|
||||||
PerseusApp::new()
|
PerseusApp::new()
|
||||||
.global_state_creator(crate::templates::global_state::get_global_state_creator())
|
.global_state_creator(crate::global_state::get_global_state_creator())
|
||||||
.template(crate::templates::index::get_template())
|
.template(crate::templates::index::get_template())
|
||||||
.template(crate::templates::add_game_form::get_template())
|
.template(crate::templates::pickleball::index::get_template())
|
||||||
.template(crate::templates::one_v_one_board::get_template())
|
.template(crate::templates::pool::index::get_template())
|
||||||
.template(crate::templates::overall_board::get_template())
|
.template(crate::templates::pool::add_game_form::get_template())
|
||||||
|
.template(crate::templates::pool::one_v_one_board::get_template())
|
||||||
|
.template(crate::templates::pool::overall_board::get_template())
|
||||||
|
.template(crate::templates::table_tennis::index::get_template())
|
||||||
.capsule_ref(&*crate::capsules::login_form::LOGIN_FORM)
|
.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())
|
.error_views(crate::error_views::get_error_views())
|
||||||
.index_view(|cx| {
|
.index_view(|cx| {
|
||||||
view! { cx,
|
view! { cx,
|
||||||
html (class = "flex w-full h-full"){
|
html (class = "flex w-full h-full", data-theme = "light"){
|
||||||
head {
|
head {
|
||||||
meta(charset = "UTF-8")
|
meta(charset = "UTF-8")
|
||||||
meta(name = "viewport", content = "width=device-width, initial-scale=1.0")
|
meta(name = "viewport", content = "width=device-width, initial-scale=1.0")
|
||||||
|
|||||||
48
src/models/auth.rs
Normal file
48
src/models/auth.rs
Normal 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
21
src/models/generic.rs
Normal 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
2
src/models/mod.rs
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
pub mod auth;
|
||||||
|
pub mod generic;
|
||||||
40
src/server/auth/forgot_password.rs
Normal file
40
src/server/auth/forgot_password.rs
Normal 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
115
src/server/auth/login.rs
Normal 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
3
src/server/auth/mod.rs
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
pub mod forgot_password;
|
||||||
|
pub mod login;
|
||||||
|
pub mod register;
|
||||||
86
src/server/auth/register.rs
Normal file
86
src/server/auth/register.rs
Normal 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()))
|
||||||
|
}
|
||||||
@@ -1 +1,3 @@
|
|||||||
|
pub mod auth;
|
||||||
pub mod routes;
|
pub mod routes;
|
||||||
|
pub mod server_state;
|
||||||
|
|||||||
@@ -1,24 +1,21 @@
|
|||||||
// (Server only) Routes
|
// (Server only) Routes
|
||||||
use crate::{
|
use crate::endpoints::{FORGOT_PASSWORD, LOGIN, LOGIN_TEST, REGISTER};
|
||||||
endpoints::{MATCH, USER},
|
use axum::routing::{post, Router};
|
||||||
entity::{game, user},
|
|
||||||
};
|
use super::{
|
||||||
use axum::{
|
auth::{
|
||||||
extract::Json,
|
forgot_password::post_forgot_password,
|
||||||
routing::{post, Router},
|
login::{post_login_user, post_test_login},
|
||||||
|
register::post_register_user,
|
||||||
|
},
|
||||||
|
server_state::ServerState,
|
||||||
};
|
};
|
||||||
|
|
||||||
pub fn register_routes(app: Router) -> Router {
|
pub fn get_api_router(state: ServerState) -> Router {
|
||||||
let app = app.route(USER, post(post_user));
|
Router::new()
|
||||||
app.route(MATCH, post(post_match))
|
.route(REGISTER, post(post_register_user))
|
||||||
}
|
.route(LOGIN, post(post_login_user))
|
||||||
|
.route(LOGIN_TEST, post(post_test_login))
|
||||||
async fn post_user(_user: String) -> Json<user::Model> {
|
.route(FORGOT_PASSWORD, post(post_forgot_password))
|
||||||
// Update the store with the new match
|
.with_state(state)
|
||||||
todo!()
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn post_match(_user: String) -> Json<game::Model> {
|
|
||||||
// Update the store with the new match
|
|
||||||
todo!()
|
|
||||||
}
|
}
|
||||||
|
|||||||
6
src/server/server_state.rs
Normal file
6
src/server/server_state.rs
Normal 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
39
src/state_enums.rs
Normal 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 ContentState {
|
||||||
|
None,
|
||||||
|
Pool,
|
||||||
|
Pickleball,
|
||||||
|
TableTennis,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Display for ContentState {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
write!(
|
||||||
|
f,
|
||||||
|
"{}",
|
||||||
|
match self {
|
||||||
|
ContentState::None => "",
|
||||||
|
ContentState::Pool => "Pool",
|
||||||
|
ContentState::Pickleball => "Pickle Ball",
|
||||||
|
ContentState::TableTennis => "Table Tennis",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize, Clone)]
|
||||||
|
pub enum OpenState {
|
||||||
|
Open,
|
||||||
|
Closed,
|
||||||
|
}
|
||||||
@@ -1,64 +0,0 @@
|
|||||||
// Not a page, global state that is shared between all pages
|
|
||||||
|
|
||||||
use perseus::{prelude::*, state::GlobalStateCreator};
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
|
|
||||||
cfg_if::cfg_if! {
|
|
||||||
if #[cfg(engine)] {
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, ReactiveState, Clone)]
|
|
||||||
#[rx(alias = "AppStateRx")]
|
|
||||||
pub struct AppState {
|
|
||||||
#[rx(nested)]
|
|
||||||
pub auth: AuthData,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Clone)]
|
|
||||||
pub enum LoginState {
|
|
||||||
Authenticated,
|
|
||||||
NotAuthenticated,
|
|
||||||
Unknown,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[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 = "ClaimsRx")]
|
|
||||||
pub struct Claims {}
|
|
||||||
|
|
||||||
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 {},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,10 +1,10 @@
|
|||||||
use crate::components::layout::Layout;
|
use crate::{components::layout::Layout, state_enums::ContentState};
|
||||||
use perseus::prelude::*;
|
use perseus::prelude::*;
|
||||||
use sycamore::prelude::*;
|
use sycamore::prelude::*;
|
||||||
|
|
||||||
fn index_page<G: Html>(cx: Scope) -> View<G> {
|
fn index_page<G: Html>(cx: Scope) -> View<G> {
|
||||||
view! { cx,
|
view! { cx,
|
||||||
Layout(_title = "Index") {
|
Layout(content_state = ContentState::None) {
|
||||||
// Anything we put in here will be rendered inside the `<main>` block of the layout
|
// Anything we put in here will be rendered inside the `<main>` block of the layout
|
||||||
p { "Hello World!" }
|
p { "Hello World!" }
|
||||||
br {}
|
br {}
|
||||||
|
|||||||
@@ -1,13 +1,13 @@
|
|||||||
pub mod add_game_form;
|
|
||||||
pub mod global_state;
|
|
||||||
pub mod index;
|
pub mod index;
|
||||||
pub mod one_v_one_board;
|
pub mod pickleball;
|
||||||
pub mod overall_board;
|
pub mod pool;
|
||||||
|
pub mod table_tennis;
|
||||||
|
pub mod user;
|
||||||
|
|
||||||
#[cfg(client)]
|
#[cfg(client)]
|
||||||
use perseus::utils::get_path_prefix_client;
|
use perseus::utils::get_path_prefix_client;
|
||||||
|
|
||||||
#[allow(dead_code)]
|
#[cfg(client)]
|
||||||
pub fn get_api_path(path: &str) -> String {
|
pub fn get_api_path(path: &str) -> String {
|
||||||
#[cfg(engine)]
|
#[cfg(engine)]
|
||||||
{
|
{
|
||||||
|
|||||||
27
src/templates/pickleball/index.rs
Normal file
27
src/templates/pickleball/index.rs
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
use crate::{components::layout::Layout, state_enums::ContentState};
|
||||||
|
use perseus::prelude::*;
|
||||||
|
use sycamore::prelude::*;
|
||||||
|
|
||||||
|
fn index_page<G: Html>(cx: Scope) -> View<G> {
|
||||||
|
view! { cx,
|
||||||
|
Layout(content_state = ContentState::Pickleball) {
|
||||||
|
// Anything we put in here will be rendered inside the `<main>` block of the layout
|
||||||
|
p { "Hello World!" }
|
||||||
|
br {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[engine_only_fn]
|
||||||
|
fn head(cx: Scope) -> View<SsrNode> {
|
||||||
|
view! { cx,
|
||||||
|
title { "Index Page" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_template<G: Html>() -> Template<G> {
|
||||||
|
Template::build("pickleball")
|
||||||
|
.view(index_page)
|
||||||
|
.head(head)
|
||||||
|
.build()
|
||||||
|
}
|
||||||
1
src/templates/pickleball/mod.rs
Normal file
1
src/templates/pickleball/mod.rs
Normal file
@@ -0,0 +1 @@
|
|||||||
|
pub mod index;
|
||||||
@@ -1,18 +1,9 @@
|
|||||||
use crate::components::layout::Layout;
|
use crate::{components::layout::Layout, state_enums::ContentState};
|
||||||
use perseus::prelude::*;
|
use perseus::prelude::*;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use sycamore::prelude::*;
|
use sycamore::prelude::*;
|
||||||
use web_sys::Event;
|
use web_sys::Event;
|
||||||
|
|
||||||
cfg_if::cfg_if! {
|
|
||||||
if #[cfg(client)] {
|
|
||||||
use crate::templates::global_state::AppStateRx;
|
|
||||||
use crate::endpoints::{MATCH, USER};
|
|
||||||
use crate::templates::get_api_path;
|
|
||||||
use chrono::Utc;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Reactive page
|
// Reactive page
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Clone, ReactiveState)]
|
#[derive(Serialize, Deserialize, Clone, ReactiveState)]
|
||||||
@@ -40,7 +31,7 @@ fn add_game_form_page<'a, G: Html>(cx: BoundedScope<'_, 'a>, state: &'a PageStat
|
|||||||
};
|
};
|
||||||
|
|
||||||
view! { cx,
|
view! { cx,
|
||||||
Layout(_title = "Add Game Results") {
|
Layout(content_state = ContentState::Pool) {
|
||||||
div (class = "flex flex-wrap") {
|
div (class = "flex flex-wrap") {
|
||||||
select {
|
select {
|
||||||
option (value="red")
|
option (value="red")
|
||||||
@@ -85,8 +76,8 @@ async fn get_request_state(
|
|||||||
_req: Request,
|
_req: Request,
|
||||||
) -> Result<PageState, BlamedError<std::convert::Infallible>> {
|
) -> Result<PageState, BlamedError<std::convert::Infallible>> {
|
||||||
Ok(PageState {
|
Ok(PageState {
|
||||||
winner: "Ferris".to_string(),
|
winner: "Ferris".to_owned(),
|
||||||
new_user: "newguy".to_string(),
|
new_user: "newguy".to_owned(),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -100,7 +91,7 @@ fn head(cx: Scope) -> View<SsrNode> {
|
|||||||
// Template
|
// Template
|
||||||
|
|
||||||
pub fn get_template<G: Html>() -> Template<G> {
|
pub fn get_template<G: Html>() -> Template<G> {
|
||||||
Template::build("add-game-form")
|
Template::build("pool/add-game-form")
|
||||||
.request_state_fn(get_request_state)
|
.request_state_fn(get_request_state)
|
||||||
.view_with_state(add_game_form_page)
|
.view_with_state(add_game_form_page)
|
||||||
.head(head)
|
.head(head)
|
||||||
24
src/templates/pool/index.rs
Normal file
24
src/templates/pool/index.rs
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
use crate::{components::layout::Layout, state_enums::ContentState};
|
||||||
|
use perseus::prelude::*;
|
||||||
|
use sycamore::prelude::*;
|
||||||
|
|
||||||
|
fn index_page<G: Html>(cx: Scope) -> View<G> {
|
||||||
|
view! { cx,
|
||||||
|
Layout(content_state = ContentState::Pool) {
|
||||||
|
// Anything we put in here will be rendered inside the `<main>` block of the layout
|
||||||
|
p { "Hello World!" }
|
||||||
|
br {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[engine_only_fn]
|
||||||
|
fn head(cx: Scope) -> View<SsrNode> {
|
||||||
|
view! { cx,
|
||||||
|
title { "Index Page" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_template<G: Html>() -> Template<G> {
|
||||||
|
Template::build("pool").view(index_page).head(head).build()
|
||||||
|
}
|
||||||
4
src/templates/pool/mod.rs
Normal file
4
src/templates/pool/mod.rs
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
pub mod add_game_form;
|
||||||
|
pub mod index;
|
||||||
|
pub mod one_v_one_board;
|
||||||
|
pub mod overall_board;
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
use crate::components::layout::Layout;
|
use crate::{components::layout::Layout, state_enums::ContentState};
|
||||||
use perseus::prelude::*;
|
use perseus::prelude::*;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use sycamore::prelude::*;
|
use sycamore::prelude::*;
|
||||||
@@ -9,7 +9,7 @@ struct PageState {}
|
|||||||
|
|
||||||
fn one_v_one_board_page<'a, G: Html>(cx: BoundedScope<'_, 'a>, _state: &'a PageStateRx) -> View<G> {
|
fn one_v_one_board_page<'a, G: Html>(cx: BoundedScope<'_, 'a>, _state: &'a PageStateRx) -> View<G> {
|
||||||
view! { cx,
|
view! { cx,
|
||||||
Layout(_title = "1v1 Leaderboard") {
|
Layout(content_state = ContentState::Pool) {
|
||||||
p { "leaderboard" }
|
p { "leaderboard" }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -31,7 +31,7 @@ fn head(cx: Scope) -> View<SsrNode> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_template<G: Html>() -> Template<G> {
|
pub fn get_template<G: Html>() -> Template<G> {
|
||||||
Template::build("one-v-one-board")
|
Template::build("pool/one-v-one-board")
|
||||||
.request_state_fn(get_request_state)
|
.request_state_fn(get_request_state)
|
||||||
.view_with_state(one_v_one_board_page)
|
.view_with_state(one_v_one_board_page)
|
||||||
.head(head)
|
.head(head)
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
use crate::{components::layout::Layout, templates::global_state::AppStateRx};
|
use crate::{components::layout::Layout, global_state::AppStateRx, state_enums::ContentState};
|
||||||
|
|
||||||
use perseus::prelude::*;
|
use perseus::prelude::*;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
@@ -12,7 +12,7 @@ fn overall_board_page<'a, G: Html>(cx: BoundedScope<'_, 'a>, _state: &'a PageSta
|
|||||||
let _global_state = Reactor::<G>::from_cx(cx).get_global_state::<AppStateRx>(cx);
|
let _global_state = Reactor::<G>::from_cx(cx).get_global_state::<AppStateRx>(cx);
|
||||||
|
|
||||||
view! { cx,
|
view! { cx,
|
||||||
Layout(_title = "Overall Leaderboard") {
|
Layout(content_state = ContentState::Pool) {
|
||||||
ul {
|
ul {
|
||||||
(View::new_fragment(
|
(View::new_fragment(
|
||||||
vec![],
|
vec![],
|
||||||
@@ -38,7 +38,7 @@ fn head(cx: Scope) -> View<SsrNode> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_template<G: Html>() -> Template<G> {
|
pub fn get_template<G: Html>() -> Template<G> {
|
||||||
Template::build("overall-board")
|
Template::build("pool/overall-board")
|
||||||
.request_state_fn(get_request_state)
|
.request_state_fn(get_request_state)
|
||||||
.view_with_state(overall_board_page)
|
.view_with_state(overall_board_page)
|
||||||
.head(head)
|
.head(head)
|
||||||
27
src/templates/table_tennis/index.rs
Normal file
27
src/templates/table_tennis/index.rs
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
use crate::{components::layout::Layout, state_enums::ContentState};
|
||||||
|
use perseus::prelude::*;
|
||||||
|
use sycamore::prelude::*;
|
||||||
|
|
||||||
|
fn index_page<G: Html>(cx: Scope) -> View<G> {
|
||||||
|
view! { cx,
|
||||||
|
Layout(content_state = ContentState::TableTennis) {
|
||||||
|
// Anything we put in here will be rendered inside the `<main>` block of the layout
|
||||||
|
p { "Hello World!" }
|
||||||
|
br {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[engine_only_fn]
|
||||||
|
fn head(cx: Scope) -> View<SsrNode> {
|
||||||
|
view! { cx,
|
||||||
|
title { "Index Page" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_template<G: Html>() -> Template<G> {
|
||||||
|
Template::build("table_tennis")
|
||||||
|
.view(index_page)
|
||||||
|
.head(head)
|
||||||
|
.build()
|
||||||
|
}
|
||||||
1
src/templates/table_tennis/mod.rs
Normal file
1
src/templates/table_tennis/mod.rs
Normal file
@@ -0,0 +1 @@
|
|||||||
|
pub mod index;
|
||||||
0
src/templates/user/mod.rs
Normal file
0
src/templates/user/mod.rs
Normal file
@@ -1,3 +1,5 @@
|
|||||||
|
const { default: daisyui } = require("daisyui");
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
purge: {
|
purge: {
|
||||||
mode: "all",
|
mode: "all",
|
||||||
@@ -10,5 +12,8 @@ module.exports = {
|
|||||||
},
|
},
|
||||||
theme: {},
|
theme: {},
|
||||||
variants: {},
|
variants: {},
|
||||||
plugins: [],
|
plugins: [require("daisyui")],
|
||||||
|
daisyui: {
|
||||||
|
themes: ["light", "dark", "lemonade", "autumn", "nord"],
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
Reference in New Issue
Block a user