8 Commits

Author SHA1 Message Date
893a9b5a06 Merge branch 'ft/add-error-handling'
All checks were successful
Build Crate / build (push) Successful in 1m56s
2024-08-29 00:18:59 -04:00
d6e62b98aa Fix more clippy warnings
All checks were successful
Build Crate / build (push) Successful in 1m45s
2024-08-28 23:54:56 -04:00
aca0b83dd4 Implement login form error, more clippy fixes
All checks were successful
Build Crate / build (push) Successful in 1m47s
2024-08-28 23:45:10 -04:00
9a42ed5b80 Fix forget password
All checks were successful
Build Crate / build (push) Successful in 1m46s
2024-08-28 23:14:27 -04:00
ed780c9585 Fix more clippy issues, implement forgot password
All checks were successful
Build Crate / build (push) Successful in 1m48s
2024-08-28 23:03:52 -04:00
1faaf65aad Clean up imports
All checks were successful
Build Crate / build (push) Successful in 1m47s
2024-08-28 21:55:23 -04:00
df0d7d6c0d Add registration errors
All checks were successful
Build Crate / build (push) Successful in 1m48s
2024-08-28 17:29:51 -04:00
56ea1f12c7 Merge branch 'ft/add-db-and-auth'
All checks were successful
Build Crate / build (push) Successful in 1m45s
2024-08-28 16:54:39 -04:00
19 changed files with 323 additions and 147 deletions

View File

@@ -8,10 +8,16 @@ cfg_if::cfg_if! {
if #[cfg(client)] { if #[cfg(client)] {
use crate::{ use crate::{
state_enums::{ OpenState}, state_enums::{ OpenState},
templates::{get_api_path}, templates::get_api_path,
global_state::{self, AppStateRx}, global_state::{AppStateRx},
endpoints::FORGOT_PASSWORD,
models::{
auth::ForgotPasswordRequest,
generic::GenericResponse,
},
}; };
use reqwest::StatusCode; use reqwest::StatusCode;
} }
} }
@@ -25,6 +31,7 @@ lazy_static! {
struct ForgotPasswordFormState { struct ForgotPasswordFormState {
username: String, username: String,
how_to_reach: String, how_to_reach: String,
error: String,
} }
impl ForgotPasswordFormStateRx { impl ForgotPasswordFormStateRx {
@@ -32,6 +39,7 @@ impl ForgotPasswordFormStateRx {
fn reset(&self) { fn reset(&self) {
self.username.set(String::new()); self.username.set(String::new());
self.how_to_reach.set(String::new()); self.how_to_reach.set(String::new());
self.error.set(String::new());
} }
} }
@@ -49,7 +57,6 @@ fn forgot_password_form_capsule<G: Html>(
{ {
spawn_local_scoped(cx, async move { spawn_local_scoped(cx, async move {
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);
// Close modal // Close modal
state.reset(); state.reset();
global_state global_state
@@ -63,6 +70,26 @@ fn forgot_password_form_capsule<G: Html>(
#[cfg(client)] #[cfg(client)]
{ {
spawn_local_scoped(cx, async move { 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); let global_state = Reactor::<G>::from_cx(cx).get_global_state::<AppStateRx>(cx);
// Close modal // Close modal
@@ -81,11 +108,26 @@ fn forgot_password_form_capsule<G: Html>(
div (class="bg-white rounded-lg shadow relative dark:bg-gray-700"){ div (class="bg-white rounded-lg shadow relative dark:bg-gray-700"){
div (class="flex justify-end p-2"){ 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"){ 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" "Close"
} }
} }
div (class="space-y-6 px-6 lg:px-8 pb-4 sm:pb-6 xl:pb-8") { 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"} h3 (class="text-xl font-medium text-gray-900 dark:text-white"){"Forgot Password"}
(match state.error.get().as_ref() != "" {
true => { view!{cx,
div (role="alert") {
div (class="bg-red-500 text-white font-bold rounded-t px-4 py-2") {
"Error"
}
div (class="border border-t-0 border-red-400 rounded-b bg-red-100 px-4 py-3 text-red-700"){
p {(state.error.get())}
}
}
}},
false => {view!{cx,}},
})
div { div {
label (class="text-sm font-medium text-gray-900 block mb-2 dark:text-gray-300") {"Username"} 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") {} 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") {}
@@ -113,7 +155,8 @@ pub fn get_capsule<G: Html>() -> Capsule<G, ForgotPasswordFormProps> {
#[engine_only_fn] #[engine_only_fn]
async fn get_build_state(_info: StateGeneratorInfo<()>) -> ForgotPasswordFormState { async fn get_build_state(_info: StateGeneratorInfo<()>) -> ForgotPasswordFormState {
ForgotPasswordFormState { ForgotPasswordFormState {
username: "".to_owned(), username: String::new(),
how_to_reach: "".to_owned(), how_to_reach: String::new(),
error: String::new(),
} }
} }

View File

@@ -7,12 +7,12 @@ use web_sys::Event;
cfg_if::cfg_if! { cfg_if::cfg_if! {
if #[cfg(client)] { if #[cfg(client)] {
use crate::{ use crate::{
models::auth::{LoginInfo, LoginResponse},
endpoints::LOGIN, endpoints::LOGIN,
state_enums::{LoginState, OpenState}, global_state::{AppStateRx},
templates::{get_api_path}, models::auth::{LoginInfo, LoginResponse, WebAuthInfo},
global_state::{self, AppStateRx}, models::generic::GenericResponse,
models::auth::WebAuthInfo, state_enums::{OpenState},
templates::get_api_path,
}; };
use reqwest::StatusCode; use reqwest::StatusCode;
} }
@@ -28,6 +28,7 @@ struct LoginFormState {
username: String, username: String,
password: String, password: String,
remember_me: bool, remember_me: bool,
error: String,
} }
impl LoginFormStateRx { impl LoginFormStateRx {
@@ -36,6 +37,7 @@ impl LoginFormStateRx {
self.username.set(String::new()); self.username.set(String::new());
self.password.set(String::new()); self.password.set(String::new());
self.remember_me.set(false); self.remember_me.set(false);
self.error.set(String::new());
} }
} }
@@ -93,7 +95,7 @@ fn login_form_capsule<G: Html>(
#[cfg(client)] #[cfg(client)]
{ {
spawn_local_scoped(cx, async move { spawn_local_scoped(cx, async move {
let remember_me = state.remember_me.get().as_ref().clone(); let remember_me = *state.remember_me.get().as_ref();
let username = state.username.get().as_ref().clone(); let username = state.username.get().as_ref().clone();
let login_info = LoginInfo { let login_info = LoginInfo {
username: username.clone(), username: username.clone(),
@@ -113,8 +115,9 @@ fn login_form_capsule<G: Html>(
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);
if response.status() != StatusCode::OK { if response.status() != StatusCode::OK {
// todo update to some type of alert let response = response.json::<GenericResponse>().await.unwrap();
state.username.set(response.status().to_string()); state.error.set(response.status.to_string());
state.reset();
return; return;
} }
@@ -141,11 +144,26 @@ fn login_form_capsule<G: Html>(
div (class="bg-white rounded-lg shadow relative dark:bg-gray-700"){ div (class="bg-white rounded-lg shadow relative dark:bg-gray-700"){
div (class="flex justify-end p-2"){ 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"){ 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" "Close"
} }
} }
div (class="space-y-6 px-6 lg:px-8 pb-4 sm:pb-6 xl:pb-8") { 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"} h3 (class="text-xl font-medium text-gray-900 dark:text-white"){"Sign in"}
(match state.error.get().as_ref() != "" {
true => { view!{cx,
div (role="alert") {
div (class="bg-red-500 text-white font-bold rounded-t px-4 py-2") {
"Error"
}
div (class="border border-t-0 border-red-400 rounded-b bg-red-100 px-4 py-3 text-red-700"){
p {(state.error.get())}
}
}
}},
false => {view!{cx,}},
})
div { div {
label (class="text-sm font-medium text-gray-900 block mb-2 dark:text-gray-300") {"Username"} 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") {} 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") {}
@@ -191,8 +209,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_owned(), username: String::new(),
password: "".to_owned(), password: String::new(),
remember_me: false, remember_me: false,
error: String::new(),
} }
} }

View File

@@ -9,10 +9,12 @@ cfg_if::cfg_if! {
use crate::{ use crate::{
models::auth::{RegisterRequest}, models::auth::{RegisterRequest},
endpoints::REGISTER, endpoints::REGISTER,
state_enums::{LoginState, OpenState}, state_enums::OpenState,
templates::{get_api_path}, templates::get_api_path,
global_state::{self, AppStateRx}, global_state::AppStateRx,
models::auth::WebAuthInfo, models::{
generic::GenericResponse
},
}; };
use reqwest::StatusCode; use reqwest::StatusCode;
} }
@@ -30,6 +32,7 @@ struct RegisterFormState {
nickname: String, nickname: String,
registration_code: String, registration_code: String,
email: String, email: String,
error: String,
} }
impl RegisterFormStateRx { impl RegisterFormStateRx {
@@ -40,6 +43,7 @@ impl RegisterFormStateRx {
self.nickname.set(String::new()); self.nickname.set(String::new());
self.registration_code.set(String::new()); self.registration_code.set(String::new());
self.email.set(String::new()); self.email.set(String::new());
self.error.set(String::new());
} }
} }
@@ -90,10 +94,11 @@ fn register_form_capsule<G: Html>(
.unwrap(); .unwrap();
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);
let status = response.status();
if response.status() != StatusCode::OK { let response_data = response.json::<GenericResponse>().await.unwrap();
if status != StatusCode::OK {
// todo update to some type of alert // todo update to some type of alert
state.username.set(response.status().to_string()); state.error.set(response_data.status);
return; return;
} }
@@ -114,11 +119,27 @@ fn register_form_capsule<G: Html>(
div (class="bg-white rounded-lg shadow relative dark:bg-gray-700"){ div (class="bg-white rounded-lg shadow relative dark:bg-gray-700"){
div (class="flex justify-end p-2"){ 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"){ 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" "Close"
} }
} }
div (class="space-y-6 px-6 lg:px-8 pb-4 sm:pb-6 xl:pb-8") { 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"} h3 (class="text-xl font-medium text-gray-900 dark:text-white"){"Register"}
(match state.error.get().as_ref() != "" {
true => { view!{cx,
div (role="alert") {
div (class="bg-red-500 text-white font-bold rounded-t px-4 py-2") {
"Error"
}
div (class="border border-t-0 border-red-400 rounded-b bg-red-100 px-4 py-3 text-red-700"){
p {(state.error.get())}
}
}
}},
false => {view!{cx,}},
})
div { div {
label (class="text-sm font-medium text-gray-900 block mb-2 dark:text-gray-300") {"Username"} 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") {} 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") {}
@@ -174,6 +195,7 @@ async fn get_build_state(_info: StateGeneratorInfo<()>) -> RegisterFormState {
RegisterFormState { RegisterFormState {
username: String::new(), username: String::new(),
password: String::new(), password: String::new(),
error: String::new(),
nickname: String::new(), nickname: String::new(),
registration_code: String::new(), registration_code: String::new(),
email: String::new(), email: String::new(),

View File

@@ -1,28 +1,27 @@
use std::sync::Arc;
use perseus::prelude::*; use perseus::prelude::*;
use sycamore::prelude::*; use sycamore::prelude::*;
use web_sys::Event; use web_sys::Event;
use crate::{ use crate::{
capsules::{
forgot_password_form::{ForgotPasswordFormProps, FORGOT_PASSWORD_FORM},
login_form::{LoginFormProps, LOGIN_FORM},
},
endpoints::LOGIN,
global_state::AppStateRx, global_state::AppStateRx,
models::auth::LoginInfo, state_enums::{GameState, LoginState},
state_enums::{GameState, LoginState, OpenState},
}; };
cfg_if::cfg_if! {
if #[cfg(client)] {
use crate::{
state_enums::OpenState,
};
}
}
#[derive(Prop)] #[derive(Prop)]
pub struct HeaderProps<'a> { pub struct HeaderProps {
pub game: GameState, pub game: GameState,
pub title: &'a str,
} }
#[component] #[component]
pub fn Header<'a, G: Html>(cx: Scope<'a>, HeaderProps { game, title }: HeaderProps<'a>) -> View<G> { pub fn Header<G: Html>(cx: Scope, props: HeaderProps) -> View<G> {
// Get global state to get authentication info // 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);
@@ -63,7 +62,7 @@ pub fn Header<'a, G: Html>(cx: Scope<'a>, HeaderProps { game, title }: HeaderPro
// Title // Title
div(class = "text-gray-700 text-2xl font-semibold py-2") { div(class = "text-gray-700 text-2xl font-semibold py-2") {
"Pool Elo - Season 1" (props.game.to_string()) " - Season 1"
} }
// Login / register or user buttons // Login / register or user buttons

View File

@@ -4,18 +4,16 @@ use crate::{
login_form::{LoginFormProps, LOGIN_FORM}, login_form::{LoginFormProps, LOGIN_FORM},
register_form::{RegisterFormProps, REGISTER_FORM}, register_form::{RegisterFormProps, REGISTER_FORM},
}, },
components::header::{Header, HeaderProps}, components::header::Header,
global_state::AppStateRx, global_state::AppStateRx,
state_enums::{GameState, LoginState, OpenState}, state_enums::{GameState, 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 game: GameState, pub game: GameState,
pub title: &'a str,
pub children: Children<'a, G>, pub children: Children<'a, G>,
} }
@@ -24,11 +22,7 @@ pub struct LayoutProps<'a, G: Html> {
#[component] #[component]
pub fn Layout<'a, G: Html>( pub fn Layout<'a, G: Html>(
cx: Scope<'a>, cx: Scope<'a>,
LayoutProps { LayoutProps { game, children }: LayoutProps<'a, G>,
game,
title,
children,
}: LayoutProps<'a, G>,
) -> View<G> { ) -> View<G> {
let children = children.call(cx); let children = children.call(cx);
@@ -40,7 +34,7 @@ pub fn Layout<'a, G: Html>(
view! { cx, view! { cx,
// Main page header, including login functionality // Main page header, including login functionality
Header(game = game, title = title) Header(game = game)
// Modals // Modals
section(class = "flex-2") { section(class = "flex-2") {

View File

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

View File

@@ -4,16 +4,10 @@ use perseus::{prelude::*, state::GlobalStateCreator};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::{ use crate::{
models::auth::{Claims, WebAuthInfo}, models::auth::WebAuthInfo,
state_enums::{LoginState, OpenState}, state_enums::{LoginState, OpenState},
}; };
cfg_if::cfg_if! {
if #[cfg(engine)] {
}
}
#[derive(Serialize, Deserialize, ReactiveState, Clone)] #[derive(Serialize, Deserialize, ReactiveState, Clone)]
#[rx(alias = "AppStateRx")] #[rx(alias = "AppStateRx")]
pub struct AppState { pub struct AppState {
@@ -33,6 +27,7 @@ pub struct AuthData {
} }
impl AuthDataRx { impl AuthDataRx {
#[cfg(client)]
pub fn handle_log_in(&self, auth_info: WebAuthInfo) { pub fn handle_log_in(&self, auth_info: WebAuthInfo) {
// Save new token to persistent storage // Save new token to persistent storage
if auth_info.remember_me { if auth_info.remember_me {
@@ -52,11 +47,11 @@ impl AuthDataRx {
// Save token to session storage // Save token to session storage
self.username.set(Some(auth_info.username.clone())); self.username.set(Some(auth_info.username.clone()));
self.remember_me.set(Some(auth_info.remember_me.clone())); self.remember_me.set(Some(auth_info.remember_me));
self.auth_info.set(Some(auth_info)); self.auth_info.set(Some(auth_info));
self.state.set(LoginState::Authenticated); self.state.set(LoginState::Authenticated);
} }
#[cfg(client)]
pub fn handle_log_out(&self) { pub fn handle_log_out(&self) {
// Delete persistent storage // Delete persistent storage
// TODO -> handle error if local storage is not readable in browser // TODO -> handle error if local storage is not readable in browser

View File

@@ -6,11 +6,13 @@ pub struct GenericResponse {
} }
impl GenericResponse { impl GenericResponse {
#[cfg(engine)]
pub fn ok() -> Self { pub fn ok() -> Self {
GenericResponse { GenericResponse {
status: String::new(), status: String::new(),
} }
} }
#[cfg(engine)]
pub fn err(msg: &str) -> Self { pub fn err(msg: &str) -> Self {
GenericResponse { GenericResponse {
status: msg.to_string(), status: msg.to_string(),

View File

@@ -1,13 +1,40 @@
use crate::{models::auth::ForgotPasswordRequest, server::server_state::ServerState}; use crate::{
entity::{prelude::*, user},
models::{auth::ForgotPasswordRequest, generic::GenericResponse},
server::server_state::ServerState,
};
use axum::{ use axum::{
extract::{Json, State}, extract::{Json, State},
http::{HeaderMap, StatusCode}, http::StatusCode,
}; };
use sea_orm::DatabaseConnection; use sea_orm::{ActiveModelTrait, ColumnTrait, EntityTrait, IntoActiveModel, QueryFilter, Set};
pub async fn post_forgot_password( pub async fn post_forgot_password(
State(state): State<ServerState>, State(state): State<ServerState>,
Json(password_request): Json<ForgotPasswordRequest>, Json(password_request): Json<ForgotPasswordRequest>,
) -> StatusCode { ) -> (StatusCode, Json<GenericResponse>) {
StatusCode::OK // 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")),
),
}
} }

View File

@@ -1,30 +1,27 @@
use crate::entity::prelude::*;
use crate::models::auth::{Claims, LoginInfo, LoginResponse};
use crate::{ use crate::{
entity::user::{self, Entity}, entity::{
models::auth::RegisterRequest, prelude::*,
user::{self},
},
models::{
auth::{Claims, LoginInfo, LoginResponse},
generic::GenericResponse,
},
server::server_state::ServerState, server::server_state::ServerState,
}; };
use argon2::password_hash::rand_core::OsRng; use argon2::{Argon2, PasswordHash, PasswordVerifier};
use argon2::password_hash::SaltString;
use argon2::Argon2;
use argon2::PasswordHash;
use argon2::PasswordHasher;
use argon2::PasswordVerifier;
use axum::{ use axum::{
extract::{Json, State}, extract::{Json, State},
http::{HeaderMap, StatusCode}, 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}; 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) -> bool { pub async fn credentials_are_correct(
username: &str,
password: &str,
state: &ServerState,
) -> Result<(), String> {
// Get user // Get user
let existing_user: Option<user::Model> = User::find() let existing_user: Option<user::Model> = User::find()
.filter(user::Column::Username.eq(username)) .filter(user::Column::Username.eq(username))
@@ -35,28 +32,35 @@ pub async fn credentials_are_correct(username: &str, password: &str, state: &Ser
Some(user) => user.password_hash_and_salt, Some(user) => user.password_hash_and_salt,
None => { None => {
// @todo make dummy password hash // @todo make dummy password hash
return false; return Err("Username doesn't exist".to_owned());
} }
}; };
return Argon2::default() match Argon2::default().verify_password(
.verify_password(
password.as_bytes(), password.as_bytes(),
&PasswordHash::new(hash_to_check.as_str()).unwrap(), &PasswordHash::new(hash_to_check.as_str()).unwrap(),
) ) {
.is_ok(); Ok(_) => Ok(()),
Err(_) => Err("Invalid credentials".to_owned()),
}
} }
pub async fn post_login_user( pub async fn post_login_user(
State(state): State<ServerState>, State(state): State<ServerState>,
Json(login_info): Json<LoginInfo>, Json(login_info): Json<LoginInfo>,
) -> Result<Json<LoginResponse>, StatusCode> { ) -> (
StatusCode,
Result<Json<LoginResponse>, Json<GenericResponse>>,
) {
let user_authenticated = let user_authenticated =
credentials_are_correct(&login_info.username, &login_info.password, &state); credentials_are_correct(&login_info.username, &login_info.password, &state);
match user_authenticated.await { match user_authenticated.await {
false => Err(StatusCode::UNAUTHORIZED), Err(why) => (
true => { StatusCode::UNAUTHORIZED,
Err(Json(GenericResponse::err(why.as_str()))),
),
Ok(_) => {
let expires = match login_info.remember_me { let expires = match login_info.remember_me {
true => chrono::Utc::now() + chrono::Duration::days(365), true => chrono::Utc::now() + chrono::Duration::days(365),
false => chrono::Utc::now() + chrono::Duration::days(1), false => chrono::Utc::now() + chrono::Duration::days(1),
@@ -73,17 +77,21 @@ pub async fn post_login_user(
&EncodingKey::from_secret("secret".as_ref()), &EncodingKey::from_secret("secret".as_ref()),
) { ) {
Ok(token) => token, Ok(token) => token,
Err(_) => return Err(StatusCode::INTERNAL_SERVER_ERROR), Err(_) => {
return (
StatusCode::INTERNAL_SERVER_ERROR,
Err(Json(GenericResponse::err("Failed to get token"))),
)
}
}; };
let resp = LoginResponse { token, expires }; (StatusCode::OK, Ok(Json(LoginResponse { token, expires })))
Ok(Json(resp))
} }
} }
} }
pub async fn post_test_login( pub async fn post_test_login(
State(state): State<ServerState>, State(_): State<ServerState>,
header_map: HeaderMap, header_map: HeaderMap,
) -> Result<Json<String>, StatusCode> { ) -> Result<Json<String>, StatusCode> {
if let Some(auth_header) = header_map.get("Authorization") { if let Some(auth_header) = header_map.get("Authorization") {
@@ -91,13 +99,14 @@ pub async fn post_test_login(
if auth_header_str.starts_with("Bearer ") { if auth_header_str.starts_with("Bearer ") {
let token = auth_header_str.trim_start_matches("Bearer ").to_string(); let token = auth_header_str.trim_start_matches("Bearer ").to_string();
// @todo change secret // @todo change secret
match decode::<Claims>( if decode::<Claims>(
&token, &token,
&DecodingKey::from_secret("secret".as_ref()), &DecodingKey::from_secret("secret".as_ref()),
&Validation::default(), &Validation::default(),
) { )
Ok(_) => return Ok(Json("Logged in".to_owned())), .is_ok()
Err(_) => {} {
return Ok(Json("Logged in".to_owned()));
} }
} }
} }

View File

@@ -1,23 +1,15 @@
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::{ use crate::{
entity::user::{self, Entity}, entity::{prelude::*, user},
models::auth::RegisterRequest, models::{auth::RegisterRequest, generic::GenericResponse},
server::server_state::ServerState, 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( pub async fn post_register_user(
State(state): State<ServerState>, State(state): State<ServerState>,
@@ -59,7 +51,7 @@ pub async fn post_register_user(
username: Set(username), username: Set(username),
password_hash_and_salt: Set(phc_string), password_hash_and_salt: Set(phc_string),
nickname: Set({ nickname: Set({
if register_info.nickname == "" { if register_info.nickname.is_empty() {
None None
} else { } else {
Some(register_info.nickname) Some(register_info.nickname)
@@ -69,7 +61,7 @@ pub async fn post_register_user(
last_active_time: Set(Utc::now().naive_utc()), last_active_time: Set(Utc::now().naive_utc()),
is_admin: Set(false), is_admin: Set(false),
email: Set({ email: Set({
if register_info.email == "" { if register_info.email.is_empty() {
None None
} else { } else {
Some(register_info.email) Some(register_info.email)
@@ -79,11 +71,16 @@ pub async fn post_register_user(
forgot_password_request: Set(None), forgot_password_request: Set(None),
..Default::default() ..Default::default()
}; };
// TODO -> error handling let db_resp = user::Entity::insert(new_user).exec(&state.db_conn).await;
let db_resp = user::Entity::insert(new_user) match db_resp {
.exec(&state.db_conn) Ok(_) => {}
.await Err(_) => {
.unwrap(); return (
StatusCode::INTERNAL_SERVER_ERROR,
return (StatusCode::OK, Json(GenericResponse::ok())); Json(GenericResponse::err("Database error")),
);
}
};
(StatusCode::OK, Json(GenericResponse::ok()))
} }

View File

@@ -1,8 +1,6 @@
// (Server only) Routes // (Server only) Routes
use crate::endpoints::{FORGOT_PASSWORD, LOGIN, LOGIN_TEST, REGISTER}; use crate::endpoints::{FORGOT_PASSWORD, LOGIN, LOGIN_TEST, REGISTER};
use axum::routing::{post, Router}; use axum::routing::{post, Router};
use futures::executor::block_on;
use sea_orm::Database;
use super::{ use super::{
auth::{ auth::{

View File

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

View File

@@ -4,14 +4,6 @@ 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::global_state::AppStateRx;
use crate::templates::get_api_path;
use chrono::Utc;
}
}
// Reactive page // Reactive page
#[derive(Serialize, Deserialize, Clone, ReactiveState)] #[derive(Serialize, Deserialize, Clone, ReactiveState)]
@@ -39,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", game = GameState::Pool) { Layout(game = GameState::Pool) {
div (class = "flex flex-wrap") { div (class = "flex flex-wrap") {
select { select {
option (value="red") option (value="red")

View File

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

View File

@@ -4,7 +4,7 @@ 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", game = GameState::Pool) { Layout(game = GameState::Pool) {
// 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 {}

View File

@@ -6,15 +6,9 @@ pub mod overall_board;
#[cfg(client)] #[cfg(client)]
use perseus::utils::get_path_prefix_client; use perseus::utils::get_path_prefix_client;
pub fn get_api_path(path: &str) -> String {
#[cfg(engine)]
{
path.to_string()
}
#[cfg(client)] #[cfg(client)]
{ pub fn get_api_path(path: &str) -> String {
let origin = web_sys::window().unwrap().origin(); let origin = web_sys::window().unwrap().origin();
let base_path = get_path_prefix_client(); let base_path = get_path_prefix_client();
format!("{}{}{}", origin, base_path, path) format!("{}{}{}", origin, base_path, path)
} }
}

View File

@@ -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", game = GameState::Pool) { Layout(game = GameState::Pool) {
p { "leaderboard" } p { "leaderboard" }
} }
} }

View File

@@ -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", game = GameState::Pool) { Layout(game = GameState::Pool) {
ul { ul {
(View::new_fragment( (View::new_fragment(
vec![], vec![],