feat: simplify session_auth_axumby removing custom handlers

This commit is contained in:
Greg Johnston
2025-05-30 18:32:22 -04:00
parent 1da833a0aa
commit 0df6cd74ee
3 changed files with 21 additions and 82 deletions

View File

@@ -185,7 +185,7 @@ pub async fn foo() -> Result<String, ServerFnError> {
pub async fn get_user() -> Result<Option<User>, ServerFnError> { pub async fn get_user() -> Result<Option<User>, ServerFnError> {
use crate::todo::ssr::auth; use crate::todo::ssr::auth;
let auth = auth()?; let auth = auth().await?;
Ok(auth.current_user) Ok(auth.current_user)
} }
@@ -199,7 +199,7 @@ pub async fn login(
use self::ssr::*; use self::ssr::*;
let pool = pool()?; let pool = pool()?;
let auth = auth()?; let auth = auth().await?;
let (user, UserPasshash(expected_passhash)) = let (user, UserPasshash(expected_passhash)) =
User::get_from_username_with_passhash(username, &pool) User::get_from_username_with_passhash(username, &pool)
@@ -229,7 +229,7 @@ pub async fn signup(
use self::ssr::*; use self::ssr::*;
let pool = pool()?; let pool = pool()?;
let auth = auth()?; let auth = auth().await?;
if password != password_confirmation { if password != password_confirmation {
return Err(ServerFnError::ServerError( return Err(ServerFnError::ServerError(
@@ -264,7 +264,7 @@ pub async fn signup(
pub async fn logout() -> Result<(), ServerFnError> { pub async fn logout() -> Result<(), ServerFnError> {
use self::ssr::*; use self::ssr::*;
let auth = auth()?; let auth = auth().await?;
auth.logout_user(); auth.logout_user();
leptos_axum::redirect("/"); leptos_axum::redirect("/");

View File

@@ -1,62 +1,12 @@
use axum::{ use axum::Router;
body::Body as AxumBody,
extract::{Path, State},
http::Request,
response::{IntoResponse, Response},
routing::get,
Router,
};
use axum_session::{SessionConfig, SessionLayer, SessionStore}; use axum_session::{SessionConfig, SessionLayer, SessionStore};
use axum_session_auth::{AuthConfig, AuthSessionLayer}; use axum_session_auth::{AuthConfig, AuthSessionLayer};
use axum_session_sqlx::SessionSqlitePool; use axum_session_sqlx::SessionSqlitePool;
use leptos::{ use leptos::{config::get_configuration, logging::log};
config::get_configuration, logging::log, prelude::provide_context, use leptos_axum::{generate_route_list, LeptosRoutes};
}; use session_auth_axum::{auth::User, state::AppState, todo::*};
use leptos_axum::{
generate_route_list, handle_server_fns_with_context, LeptosRoutes,
};
use session_auth_axum::{
auth::{ssr::AuthSession, User},
state::AppState,
todo::*,
};
use sqlx::{sqlite::SqlitePoolOptions, SqlitePool}; use sqlx::{sqlite::SqlitePoolOptions, SqlitePool};
async fn server_fn_handler(
State(app_state): State<AppState>,
auth_session: AuthSession,
path: Path<String>,
request: Request<AxumBody>,
) -> impl IntoResponse {
log!("{:?}", path);
handle_server_fns_with_context(
move || {
provide_context(auth_session.clone());
provide_context(app_state.pool.clone());
},
request,
)
.await
}
async fn leptos_routes_handler(
auth_session: AuthSession,
state: State<AppState>,
req: Request<AxumBody>,
) -> Response {
let State(app_state) = state.clone();
let handler = leptos_axum::render_route_with_context(
app_state.routes.clone(),
move || {
provide_context(auth_session.clone());
provide_context(app_state.pool.clone());
},
move || shell(app_state.leptos_options.clone()),
);
handler(state, req).await.into_response()
}
#[tokio::main] #[tokio::main]
async fn main() { async fn main() {
simple_logger::init_with_level(log::Level::Info) simple_logger::init_with_level(log::Level::Info)
@@ -82,18 +32,6 @@ async fn main() {
eprintln!("{e:?}"); eprintln!("{e:?}");
} }
// Explicit server function registration is no longer required
// on the main branch. On 0.3.0 and earlier, uncomment the lines
// below to register the server functions.
// _ = GetTodos::register();
// _ = AddTodo::register();
// _ = DeleteTodo::register();
// _ = Login::register();
// _ = Logout::register();
// _ = Signup::register();
// _ = GetUser::register();
// _ = Foo::register();
// Setting this to None means we'll be using cargo-leptos and its env vars // Setting this to None means we'll be using cargo-leptos and its env vars
let conf = get_configuration(None).unwrap(); let conf = get_configuration(None).unwrap();
let leptos_options = conf.leptos_options; let leptos_options = conf.leptos_options;
@@ -108,11 +46,10 @@ async fn main() {
// build our application with a route // build our application with a route
let app = Router::new() let app = Router::new()
.route( .leptos_routes(&app_state, routes, {
"/api/{fn_name}", let options = app_state.leptos_options.clone();
get(server_fn_handler).post(server_fn_handler), move || shell(options.clone())
) })
.leptos_routes_with_handler(routes, get(leptos_routes_handler))
.fallback(leptos_axum::file_and_error_handler::<AppState, _>(shell)) .fallback(leptos_axum::file_and_error_handler::<AppState, _>(shell))
.layer( .layer(
AuthSessionLayer::<User, i64, SessionSqlitePool, SqlitePool>::new( AuthSessionLayer::<User, i64, SessionSqlitePool, SqlitePool>::new(

View File

@@ -16,19 +16,21 @@ pub struct Todo {
#[cfg(feature = "ssr")] #[cfg(feature = "ssr")]
pub mod ssr { pub mod ssr {
use super::Todo; use super::Todo;
use crate::auth::{ssr::AuthSession, User}; use crate::{
auth::{ssr::AuthSession, User},
state::AppState,
};
use leptos::prelude::*; use leptos::prelude::*;
use sqlx::SqlitePool; use sqlx::SqlitePool;
pub fn pool() -> Result<SqlitePool, ServerFnError> { pub fn pool() -> Result<SqlitePool, ServerFnError> {
use_context::<SqlitePool>() with_context::<AppState, _>(|state| state.pool.clone())
.ok_or_else(|| ServerFnError::ServerError("Pool missing.".into())) .ok_or_else(|| ServerFnError::ServerError("Pool missing.".into()))
} }
pub fn auth() -> Result<AuthSession, ServerFnError> { pub async fn auth() -> Result<AuthSession, ServerFnError> {
use_context::<AuthSession>().ok_or_else(|| { let auth = leptos_axum::extract().await?;
ServerFnError::ServerError("Auth session missing.".into()) Ok(auth)
})
} }
#[derive(sqlx::FromRow, Clone)] #[derive(sqlx::FromRow, Clone)]
@@ -165,7 +167,7 @@ pub fn TodoApp() -> impl IntoView {
", " ", "
<A href="/login">"Login"</A> <A href="/login">"Login"</A>
", " ", "
<span>{format!("Login error: {}", e)}</span> <span>{format!("Login error: {e}")}</span>
} }
.into_any() .into_any()
} }