From 08f1b95c18c3a59c8fc443d7e6dd05b100dab13d Mon Sep 17 00:00:00 2001 From: Ethan Girouard Date: Fri, 10 May 2024 20:26:59 -0400 Subject: [PATCH] Add get_user auth function --- src/auth.rs | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/src/auth.rs b/src/auth.rs index 2eda7cf..58ba6f4 100644 --- a/src/auth.rs +++ b/src/auth.rs @@ -120,3 +120,26 @@ pub async fn require_auth() -> Result<(), ServerFnError> { } }) } + +/// Get the current logged-in user +/// Returns a Result with the user if they are logged in +/// Returns an error if the user is not logged in, or if there is an error getting the user +/// Intended to be used in a route to get the current user: +/// ```rust +/// use leptos::*; +/// use libretunes::auth::get_user; +/// #[server(endpoint = "user_route")] +/// pub async fn user_route() -> Result<(), ServerFnError> { +/// let user = get_user().await?; +/// println!("Logged in as: {}", user.username); +/// // Do something with the user +/// Ok(()) +/// } +/// ``` +#[cfg(feature = "ssr")] +pub async fn get_user() -> Result { + let auth_session = extract::>().await + .map_err(|e| ServerFnError::::ServerError(format!("Error getting auth session: {}", e)))?; + + auth_session.user.ok_or(ServerFnError::::ServerError("User not logged in".to_string())) +}