diff --git a/src/api/auth.rs b/src/api/auth.rs new file mode 100644 index 0000000..1abd587 --- /dev/null +++ b/src/api/auth.rs @@ -0,0 +1,49 @@ +use dioxus::prelude::*; + +use crate::models::user::{User, UserCredentials}; +use crate::util::error::Result; + +cfg_if::cfg_if! { +if #[cfg(feature = "server")] { + +use dioxus::server::axum::Extension; + +use crate::server::auth::AuthSession; +use crate::util::error::{AuthError, Contextualize, Error, ErrorType}; + +} +} + +#[post("/api/v1/auth/login", mut auth: Extension)] +pub async fn login(credentials: UserCredentials) -> Result { + let db_user = match auth.authenticate(credentials).await { + Ok(Some(db_user)) => Ok(db_user), + Ok(None) => Err(Error::new_here(ErrorType::Auth( + AuthError::InvalidCredentials, + ))), + Err(axum_login::Error::Session(e)) => Err(Error::new_here(ErrorType::Auth( + AuthError::Error(format!("Session error: {e}")), + ))), + Err(axum_login::Error::Backend(e)) => Err(e), + } + .err_context("Error authenticating")?; + + auth.login(&db_user) + .await + .map_err(|e| Error::new_here(ErrorType::Auth(AuthError::Error(e.to_string())))) + .err_context("Error logging in")?; + + Ok(db_user.into()) +} + +#[post("/api/v1/auth/logout", mut auth: Extension)] +pub async fn logout() -> Result<()> { + match auth.logout().await { + Ok(_) => Ok(()), + Err(axum_login::Error::Session(e)) => Err(Error::new_here(ErrorType::Auth( + AuthError::Error(format!("Session error: {e}")), + ))), + Err(axum_login::Error::Backend(e)) => Err(e), + } + .err_context("Error logging out") +} diff --git a/src/api/mod.rs b/src/api/mod.rs index 8b13789..0e4a05d 100644 --- a/src/api/mod.rs +++ b/src/api/mod.rs @@ -1 +1 @@ - +pub mod auth;