6 Commits

Author SHA1 Message Date
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
33 changed files with 1028 additions and 188 deletions

View File

@@ -16,10 +16,9 @@ serde_json = "1"
env_logger = "0.10.0"
log = "0.4.20"
once_cell = "1.18.0"
web-sys = "0.3.64"
web-sys = { version = "0.3.64", features = ["Window", "Storage"] }
cfg-if = "1.0.0"
chrono = { version = "0.4.38", features = ["serde", "wasm-bindgen"] }
password-auth = "1.0.0"
lazy_static = "1.5"
[target.'cfg(engine)'.dev-dependencies]
@@ -37,6 +36,8 @@ sea-orm = { version = "1.0", features = [
"macros",
"with-chrono",
] }
jsonwebtoken = "9.3.0"
argon2 = "0.5"
[target.'cfg(client)'.dependencies]
wasm-bindgen = "0.2.93"

View File

@@ -9,19 +9,21 @@ pub struct Migration;
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(User::Username))
.col(string(User::Password))
.col(string(User::Salt))
.col(timestamp_with_time_zone(User::CreationTime))
.col(timestamp_with_time_zone(User::LastActiveTime))
.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
@@ -39,11 +41,12 @@ pub enum User {
Table,
Id,
Username,
Password,
Salt,
PasswordHashAndSalt,
Nickname,
CreationTime,
LastActiveTime,
IsAdmin,
Email,
Avatar,
ForgotPasswordRequest,
}

View File

@@ -0,0 +1,119 @@
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::{self, AppStateRx},
};
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,
}
impl ForgotPasswordFormStateRx {
#[cfg(client)]
fn reset(&self) {
self.username.set(String::new());
self.how_to_reach.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 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"){
"Back"
}
}
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"}
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: "".to_owned(),
how_to_reach: "".to_owned(),
}
}

View File

@@ -4,7 +4,19 @@ use serde::{Deserialize, Serialize};
use sycamore::prelude::*;
use web_sys::Event;
use crate::{state_enums::OpenState, templates::global_state::AppStateRx};
cfg_if::cfg_if! {
if #[cfg(client)] {
use crate::{
models::auth::{LoginInfo, LoginResponse},
endpoints::LOGIN,
state_enums::{LoginState, OpenState},
templates::{get_api_path},
global_state::{self, AppStateRx},
models::auth::WebAuthInfo,
};
use reqwest::StatusCode;
}
}
lazy_static! {
pub static ref LOGIN_FORM: Capsule<PerseusNodeType, LoginFormProps> = get_capsule();
@@ -15,14 +27,21 @@ lazy_static! {
struct LoginFormState {
username: String,
password: String,
remember_me: bool,
}
impl LoginFormStateRx {
#[cfg(client)]
fn reset(&self) {
self.username.set(String::new());
self.password.set(String::new());
self.remember_me.set(false);
}
}
#[derive(Clone)]
pub struct LoginFormProps {
pub remember_me: bool,
pub endpoint: String,
pub lost_password_url: Option<String>,
pub forgot_password_url: Option<String>,
}
#[auto_scope]
@@ -41,6 +60,81 @@ fn login_form_capsule<G: Html>(
}
};
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().clone();
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 {
// todo update to some type of alert
state.username.set(response.status().to_string());
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") {
@@ -50,30 +144,35 @@ fn login_form_capsule<G: Html>(
"Back"
}
}
form (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 to our platform"}
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"}
div {
label (class="text-sm font-medium text-gray-900 block mb-2 dark:text-gray-300") {"Your email"}
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") {}
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"){"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"){}
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"){
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?"}
(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 (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"}
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"){
a (class="text-blue-700 hover:underline dark:text-blue-500"){"Create account"}
button (on:click = handle_register, class="text-blue-700 hover:underline dark:text-blue-500"){"Create account"}
}
}
}
@@ -92,7 +191,8 @@ pub fn get_capsule<G: Html>() -> Capsule<G, LoginFormProps> {
#[engine_only_fn]
async fn get_build_state(_info: StateGeneratorInfo<()>) -> LoginFormState {
LoginFormState {
username: "".to_string(),
password: "".to_string(),
username: "".to_owned(),
password: "".to_owned(),
remember_me: false,
}
}

View File

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

View File

@@ -0,0 +1,181 @@
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::{LoginState, OpenState},
templates::{get_api_path},
global_state::{self, AppStateRx},
models::auth::WebAuthInfo,
};
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,
}
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());
}
}
#[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);
if response.status() != StatusCode::OK {
// todo update to some type of alert
state.username.set(response.status().to_string());
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"){
"Back"
}
}
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"}
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(),
nickname: String::new(),
registration_code: String::new(),
email: String::new(),
}
}

View File

@@ -5,9 +5,14 @@ use sycamore::prelude::*;
use web_sys::Event;
use crate::{
capsules::login_form::{LoginFormProps, LOGIN_FORM},
capsules::{
forgot_password_form::{ForgotPasswordFormProps, FORGOT_PASSWORD_FORM},
login_form::{LoginFormProps, LOGIN_FORM},
},
endpoints::LOGIN,
global_state::AppStateRx,
models::auth::LoginInfo,
state_enums::{GameState, LoginState, OpenState},
templates::global_state::AppStateRx,
};
#[derive(Prop)]
@@ -31,6 +36,26 @@ pub fn Header<'a, G: Html>(cx: Scope<'a>, HeaderProps { game, title }: HeaderPro
}
};
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") {
@@ -46,18 +71,22 @@ pub fn Header<'a, G: Html>(cx: Scope<'a>, HeaderProps { game, title }: HeaderPro
match *global_state.auth.state.get() {
LoginState::NotAuthenticated => {
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") {
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") {
"Login"
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 {username}!"
"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"
}
}
}
@@ -73,25 +102,5 @@ pub fn Header<'a, G: Html>(cx: Scope<'a>, HeaderProps { game, title }: HeaderPro
}
}
}
section(class = "flex-2") {
(match *global_state.modals_open.login.get() {
OpenState::Open => {
view! { cx,
(LOGIN_FORM.widget(cx, "",
LoginFormProps{
remember_me: true,
endpoint: "".to_string(),
lost_password_url: Some("".to_string()),
forgot_password_url: Some("".to_string()),
}
))
}
}
OpenState::Closed => {
view!{ cx, }
}
})
}
}
}

View File

@@ -1,8 +1,12 @@
use crate::{
capsules::login_form::{LoginFormProps, LOGIN_FORM},
capsules::{
forgot_password_form::{ForgotPasswordFormProps, FORGOT_PASSWORD_FORM},
login_form::{LoginFormProps, LOGIN_FORM},
register_form::{RegisterFormProps, REGISTER_FORM},
},
components::header::{Header, HeaderProps},
state_enums::{GameState, LoginState},
templates::global_state::AppStateRx,
global_state::AppStateRx,
state_enums::{GameState, LoginState, OpenState},
};
use perseus::prelude::*;
use sycamore::prelude::*;
@@ -28,8 +32,6 @@ pub fn Layout<'a, G: Html>(
) -> View<G> {
let children = children.call(cx);
// Get global state to get authentication info
#[cfg(client)]
let global_state = Reactor::<G>::from_cx(cx).get_global_state::<AppStateRx>(cx);
// Check if the client is authenticated or not
@@ -40,6 +42,52 @@ pub fn Layout<'a, G: Html>(
// Main page header, including login functionality
Header(game = game, title = title)
// Modals
section(class = "flex-2") {
(match *global_state.modals_open.login.get() {
OpenState::Open => {
view! { cx,
(LOGIN_FORM.widget(cx, "",
LoginFormProps{
remember_me: true,
}
))
}
}
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, }
}
})
}
main(style = "my-8") {
// Body header
div {
@@ -59,7 +107,7 @@ pub fn Layout<'a, G: Html>(
}
}
}
// Actual body
// 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") {

View File

@@ -1,2 +1,4 @@
pub const MATCH: &str = "/api/post-match";
pub const USER: &str = "/api/post-user";
pub const REGISTER: &str = "/api/register";
pub const LOGIN: &str = "/api/login";
pub const LOGIN_TEST: &str = "/api/login-test";
pub const FORGOT_PASSWORD: &str = "/api/forgot-password";

View File

@@ -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 sea_orm::entity::prelude::*;

View File

@@ -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 serde::{Deserialize, Serialize};

View File

@@ -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;

View File

@@ -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_to_team_result::Entity as GameToTeamResult;

View File

@@ -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 serde::{Deserialize, Serialize};

View File

@@ -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 serde::{Deserialize, Serialize};

View File

@@ -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 serde::{Deserialize, Serialize};

View File

@@ -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 serde::{Deserialize, Serialize};
@@ -8,14 +8,16 @@ use serde::{Deserialize, Serialize};
pub struct Model {
#[sea_orm(primary_key)]
pub id: i32,
#[sea_orm(unique)]
pub username: String,
pub password: String,
pub salt: String,
pub creation_time: DateTimeWithTimeZone,
pub last_active_time: DateTimeWithTimeZone,
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)]

148
src/global_state.rs Normal file
View File

@@ -0,0 +1,148 @@
// 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, WebAuthInfo},
state_enums::{LoginState, OpenState},
};
cfg_if::cfg_if! {
if #[cfg(engine)] {
}
}
#[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 {
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.clone()));
self.auth_info.set(Some(auth_info));
self.state.set(LoginState::Authenticated);
}
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

@@ -4,6 +4,8 @@ mod endpoints;
#[allow(unused_imports)]
mod entity;
mod error_views;
mod global_state;
mod models;
#[cfg(engine)]
mod server;
mod state_enums;
@@ -21,9 +23,10 @@ cfg_if::cfg_if! {
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};
use crate::server::routes::register_routes;
use sea_orm::Database;
}
}
@@ -36,16 +39,24 @@ pub async fn dflt_server<M: MutableStore + 'static, T: TranslationsManager + 'st
let addr: SocketAddr = format!("{}:{}", host, port)
.parse()
.expect("Invalid address provided to bind to.");
let mut app = perseus_axum::get_router(turbine, opts).await;
app = register_routes(app);
let app = perseus_axum::get_router(turbine, opts).await;
// TODO -> Update to use environment variable
if let Err(err) = block_on(Database::connect(
"postgres://elo:elo@localhost:5432/elo_app",
)) {
panic!("{}", err);
}
// 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())
@@ -58,12 +69,14 @@ pub fn main<G: Html>() -> PerseusApp<G> {
env_logger::init();
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::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,

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,
}

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

@@ -0,0 +1,19 @@
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Clone)]
pub struct GenericResponse {
pub status: String,
}
impl GenericResponse {
pub fn ok() -> Self {
GenericResponse {
status: String::new(),
}
}
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,13 @@
use crate::{models::auth::ForgotPasswordRequest, server::server_state::ServerState};
use axum::{
extract::{Json, State},
http::{HeaderMap, StatusCode},
};
use sea_orm::DatabaseConnection;
pub async fn post_forgot_password(
State(state): State<ServerState>,
Json(password_request): Json<ForgotPasswordRequest>,
) -> StatusCode {
StatusCode::OK
}

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

@@ -0,0 +1,106 @@
use crate::entity::prelude::*;
use crate::models::auth::{Claims, LoginInfo, LoginResponse};
use crate::{
entity::user::{self, Entity},
models::auth::RegisterRequest,
server::server_state::ServerState,
};
use argon2::password_hash::rand_core::OsRng;
use argon2::password_hash::SaltString;
use argon2::Argon2;
use argon2::PasswordHash;
use argon2::PasswordHasher;
use argon2::PasswordVerifier;
use axum::{
extract::{Json, State},
http::{HeaderMap, StatusCode},
};
use futures::sink::Fanout;
use sea_orm::ColumnTrait;
use sea_orm::EntityTrait;
use sea_orm::InsertResult;
use sea_orm::QueryFilter;
use sea_orm::Set;
use jsonwebtoken::{decode, encode, DecodingKey, EncodingKey, Header, Validation};
pub async fn credentials_are_correct(username: &str, password: &str, state: &ServerState) -> bool {
// 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 false;
}
};
return Argon2::default()
.verify_password(
password.as_bytes(),
&PasswordHash::new(hash_to_check.as_str()).unwrap(),
)
.is_ok();
}
pub async fn post_login_user(
State(state): State<ServerState>,
Json(login_info): Json<LoginInfo>,
) -> Result<Json<LoginResponse>, StatusCode> {
let user_authenticated =
credentials_are_correct(&login_info.username, &login_info.password, &state);
match user_authenticated.await {
false => Err(StatusCode::UNAUTHORIZED),
true => {
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 Err(StatusCode::INTERNAL_SERVER_ERROR),
};
let resp = LoginResponse { token, expires };
Ok(Json(resp))
}
}
}
pub async fn post_test_login(
State(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
match decode::<Claims>(
&token,
&DecodingKey::from_secret("secret".as_ref()),
&Validation::default(),
) {
Ok(_) => return Ok(Json("Logged in".to_owned())),
Err(_) => {}
}
}
}
}
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,89 @@
use crate::entity::prelude::*;
use crate::models::generic::GenericResponse;
use argon2::password_hash::rand_core::OsRng;
use argon2::password_hash::SaltString;
use argon2::Argon2;
use argon2::PasswordHash;
use argon2::PasswordHasher;
use axum::{extract::State, http::StatusCode, Json};
use chrono::Utc;
use sea_orm::ColumnTrait;
use sea_orm::EntityTrait;
use sea_orm::InsertResult;
use sea_orm::QueryFilter;
use sea_orm::Set;
use crate::{
entity::user::{self, Entity},
models::auth::RegisterRequest,
server::server_state::ServerState,
};
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 == "" {
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 == "" {
None
} else {
Some(register_info.email)
}
}),
avatar: Set(None),
forgot_password_request: Set(None),
..Default::default()
};
// TODO -> error handling
let db_resp = user::Entity::insert(new_user)
.exec(&state.db_conn)
.await
.unwrap();
return (StatusCode::OK, Json(GenericResponse::ok()));
}

View File

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

View File

@@ -1,24 +1,23 @@
// (Server only) Routes
use crate::{
endpoints::{MATCH, USER},
entity::{game, user},
};
use axum::{
extract::Json,
routing::{post, Router},
use crate::endpoints::{FORGOT_PASSWORD, LOGIN, LOGIN_TEST, REGISTER};
use axum::routing::{post, Router};
use futures::executor::block_on;
use sea_orm::Database;
use super::{
auth::{
forgot_password::post_forgot_password,
login::{post_login_user, post_test_login},
register::post_register_user,
},
server_state::ServerState,
};
pub fn register_routes(app: Router) -> Router {
let app = app.route(USER, post(post_user));
app.route(MATCH, post(post_match))
}
async fn post_user(_user: String) -> Json<user::Model> {
// Update the store with the new match
todo!()
}
async fn post_match(_user: String) -> Json<game::Model> {
// Update the store with the new match
todo!()
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,
}

View File

@@ -6,8 +6,7 @@ use web_sys::Event;
cfg_if::cfg_if! {
if #[cfg(client)] {
use crate::templates::global_state::AppStateRx;
use crate::endpoints::{MATCH, USER};
use crate::global_state::AppStateRx;
use crate::templates::get_api_path;
use chrono::Utc;
}
@@ -85,8 +84,8 @@ async fn get_request_state(
_req: Request,
) -> Result<PageState, BlamedError<std::convert::Infallible>> {
Ok(PageState {
winner: "Ferris".to_string(),
new_user: "newguy".to_string(),
winner: "Ferris".to_owned(),
new_user: "newguy".to_owned(),
})
}

View File

@@ -1,70 +0,0 @@
// Not a page, global state that is shared between all pages
use perseus::{prelude::*, state::GlobalStateCreator};
use serde::{Deserialize, Serialize};
use crate::state_enums::{LoginState, OpenState};
cfg_if::cfg_if! {
if #[cfg(engine)] {
}
}
#[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,
}
#[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 {},
},
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,5 +1,4 @@
pub mod add_game_form;
pub mod global_state;
pub mod index;
pub mod one_v_one_board;
pub mod overall_board;
@@ -7,7 +6,6 @@ pub mod overall_board;
#[cfg(client)]
use perseus::utils::get_path_prefix_client;
#[allow(dead_code)]
pub fn get_api_path(path: &str) -> String {
#[cfg(engine)]
{

View File

@@ -1,6 +1,4 @@
use crate::{
components::layout::Layout, state_enums::GameState, templates::global_state::AppStateRx,
};
use crate::{components::layout::Layout, global_state::AppStateRx, state_enums::GameState};
use perseus::prelude::*;
use serde::{Deserialize, Serialize};