47 lines
1.5 KiB
Rust
47 lines
1.5 KiB
Rust
use axum::{
|
|
extract::Request,
|
|
middleware::Next,
|
|
response::{IntoResponse, Redirect, Response},
|
|
};
|
|
use tower_sessions::Session;
|
|
|
|
use crate::config::SfAuthConfig;
|
|
|
|
/// Middleware function that enforces SF authentication.
|
|
///
|
|
/// This middleware checks if the user has valid session credentials (`sf_username` and `sf_user_id`).
|
|
/// If not authenticated, it redirects to the SF authentication endpoint.
|
|
///
|
|
/// # Example
|
|
///
|
|
/// ```ignore
|
|
/// use axum::{routing::get, Router, middleware};
|
|
/// use sf_auth_middleware_axum::{SfAuthConfig, sf_auth_middleware};
|
|
///
|
|
/// let config = SfAuthConfig::new("https://myapp.com/dashboard");
|
|
///
|
|
/// let app = Router::new()
|
|
/// .route("/protected", get(|| async { "Protected!" }))
|
|
/// .layer(middleware::from_fn(move |session, req, next| {
|
|
/// sf_auth_middleware(config.clone(), session, req, next)
|
|
/// }));
|
|
/// ```
|
|
pub async fn sf_auth_middleware(
|
|
config: SfAuthConfig,
|
|
session: Session,
|
|
req: Request,
|
|
next: Next,
|
|
) -> Response {
|
|
// Try to get username and user_id from session
|
|
let username: Option<String> = session.get("sf_username").await.unwrap_or(None);
|
|
let user_id: Option<String> = session.get("sf_user_id").await.unwrap_or(None);
|
|
|
|
// Check if both are present
|
|
if username.is_some() && user_id.is_some() {
|
|
// User is authenticated, proceed with the request
|
|
next.run(req).await
|
|
} else {
|
|
// User is not authenticated, redirect to auth endpoint
|
|
Redirect::to(&config.auth_url()).into_response()
|
|
}
|
|
}
|