diff --git a/src/game.rs b/src/game.rs index d444240..5c15d75 100644 --- a/src/game.rs +++ b/src/game.rs @@ -3,11 +3,12 @@ use axum::{ extract::{Path, State}, http::HeaderMap, response::{IntoResponse, Redirect, Response}, - routing::get, - Router, + routing::{get, post}, + Form, Router, }; use axum_extra::extract::CookieJar; use maud::{html, Markup, PreEscaped}; +use serde::Deserialize; use std::sync::Arc; use uuid::Uuid; @@ -40,7 +41,7 @@ async fn index( ", do you want to be named something different? No worries, change here 👇" } - form { + form action="/name" method="post" { fieldset role="group" { input name="name" @@ -126,8 +127,29 @@ async fn not_found(cookies: CookieJar, headers: HeaderMap) -> Markup { ) } +#[derive(Deserialize)] +struct NameForm { + name: String, +} + +async fn set_name( + State(backend): State>, + cookies: CookieJar, + Form(form): Form, +) -> Response { + let (cookies, client) = backend.client(cookies).await; + + // Update the client's name in the backend + // TODO: handle succ/err msg + let _ = backend.set_client_name(&client, &form.name).await; + + // Redirect back to the game page + (cookies, Redirect::to("/game")).into_response() +} + pub(super) fn routes() -> Router> { Router::new() .route("/game", get(index)) + .route("/name", post(set_name)) .route("/{*uuid}", get(game)) } diff --git a/src/main.rs b/src/main.rs index 7828561..8409c0c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -90,6 +90,30 @@ impl Backend { let lang = language::language(&cookies, headers); (cookies, Req { client, lang }) } + + async fn set_client_name(&self, client: &Client, name: &str) -> Result<(), String> { + if name.len() > 25 { + return Err("Maximum 25 chars are allowed".into()); + } + if name.len() < 3 { + return Err("Minimum of 3 chars needed".into()); + } + + match self { + Backend::Sqlite(db) => { + sqlx::query!( + "UPDATE client SET name = ? WHERE uuid = ?;", + name, + client.uuid + ) + .execute(db) + .await + .unwrap(); + } + } + + Ok(()) + } } #[tokio::main]