From 62a7103423b89f15deda42bf550aafdfa3a1df2d Mon Sep 17 00:00:00 2001 From: Ethan Girouard Date: Sat, 27 Jun 2026 22:34:07 -0400 Subject: [PATCH] Add signup endpoint --- src/api/auth.rs | 35 ++++++++++++++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/src/api/auth.rs b/src/api/auth.rs index 1abd587..be0fa89 100644 --- a/src/api/auth.rs +++ b/src/api/auth.rs @@ -8,12 +8,45 @@ if #[cfg(feature = "server")] { use dioxus::server::axum::Extension; -use crate::server::auth::AuthSession; +use crate::server::{auth::{AuthSession, create_user}, config::Config, database::DbPool}; use crate::util::error::{AuthError, Contextualize, Error, ErrorType}; } } +#[post("/api/v1/auth/signup", mut auth: Extension, db_pool: Extension, config: Extension)] +pub async fn signup(credentials: UserCredentials) -> Result { + if !config.auth.open_signup { + return Err(Error::new_here(ErrorType::Auth(AuthError::Unauthorized))); + } + + // Don't allow signup when already logged in + if auth.user.is_some() { + return Err(Error::new_here(ErrorType::Auth(AuthError::Unauthorized))); + } + + let hashed_creds = credentials + .try_hash() + .map_err(|e| Error::message_here(e.to_string())) + .err_context("Error hashing new user credentials")?; + + let mut db_conn = db_pool + .get() + .await + .err_context("Failed to get database pool connection")?; + + let new_user = create_user(&mut db_conn, &hashed_creds) + .await + .err_context("Error creating user")?; + + // Don't return this to the client, logging in immediately isn't strictly necessary + if let Err(e) = auth.login(&new_user).await { + tracing::warn!("Failed to log in user after creating: {e}"); + } + + Ok(new_user.into()) +} + #[post("/api/v1/auth/login", mut auth: Extension)] pub async fn login(credentials: UserCredentials) -> Result { let db_user = match auth.authenticate(credentials).await {