From fa26ee40ed1ecd3df5ee03cdca728a23489cf270 Mon Sep 17 00:00:00 2001 From: Ethan Girouard Date: Sun, 19 May 2024 12:20:50 -0400 Subject: [PATCH] Add auth functions for checking admin status --- src/auth.rs | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/src/auth.rs b/src/auth.rs index 20de5c3..8c33347 100644 --- a/src/auth.rs +++ b/src/auth.rs @@ -121,3 +121,37 @@ pub async fn require_auth() -> Result<(), ServerFnError> { } }) } + +/// Check if a user is an admin +/// Returns a Result with a boolean indicating if the user is logged in and an admin +#[server(endpoint = "check_admin")] +pub async fn check_admin() -> Result { + let auth_session = extract::>().await + .map_err(|e| ServerFnError::::ServerError(format!("Error getting auth session: {}", e)))?; + + Ok(auth_session.user.as_ref().map(|u| u.admin).unwrap_or(false)) +} + +/// Require that a user is logged in and an admin +/// Returns a Result with the error message if the user is not logged in or is not an admin +/// Intended to be used at the start of a protected route, to ensure the user is logged in and an admin: +/// ```rust +/// use leptos::*; +/// use libretunes::auth::require_admin; +/// #[server(endpoint = "protected_admin_route")] +/// pub async fn protected_admin_route() -> Result<(), ServerFnError> { +/// require_admin().await?; +/// // Continue with protected route +/// Ok(()) +/// } +/// ``` +#[cfg(feature = "ssr")] +pub async fn require_admin() -> Result<(), ServerFnError> { + check_admin().await.and_then(|is_admin| { + if is_admin { + Ok(()) + } else { + Err(ServerFnError::::ServerError(format!("Unauthorized"))) + } + }) +}