Move lib to root dir
This commit is contained in:
parent
88b21fc08d
commit
0d26e9326a
13 changed files with 2 additions and 1 deletions
47
src/middleware.rs
Normal file
47
src/middleware.rs
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
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()
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue