From 825f1cd8dfee30ad70d67726d9758c0c3b693b12 Mon Sep 17 00:00:00 2001 From: Ethan Girouard Date: Tue, 2 Apr 2024 15:32:43 -0400 Subject: [PATCH] Add check_auth and require_auth server functions --- src/auth.rs | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/src/auth.rs b/src/auth.rs index d290885..2eda7cf 100644 --- a/src/auth.rs +++ b/src/auth.rs @@ -87,3 +87,36 @@ pub async fn logout() -> Result<(), ServerFnError> { Ok(()) } +/// Check if a user is logged in +/// Returns a Result with a boolean indicating if the user is logged in +#[server(endpoint = "check_auth")] +pub async fn check_auth() -> Result { + let auth_session = extract::>().await + .map_err(|e| ServerFnError::::ServerError(format!("Error getting auth session: {}", e)))?; + + Ok(auth_session.user.is_some()) +} + +/// Require that a user is logged in +/// Returns a Result with the error message if the user is not logged in +/// Intended to be used at the start of a protected route, to ensure the user is logged in: +/// ```rust +/// use leptos::*; +/// use libretunes::auth::require_auth; +/// #[server(endpoint = "protected_route")] +/// pub async fn protected_route() -> Result<(), ServerFnError> { +/// require_auth().await?; +/// // Continue with protected route +/// Ok(()) +/// } +/// ``` +#[cfg(feature = "ssr")] +pub async fn require_auth() -> Result<(), ServerFnError> { + check_auth().await.and_then(|logged_in| { + if logged_in { + Ok(()) + } else { + Err(ServerFnError::::ServerError(format!("Unauthorized"))) + } + }) +}