Files
LibreTunes/src/util/require_auth.rs
Ethan Girouard 297c22d832
Some checks failed
Push Workflows / docs (push) Successful in 1m35s
Push Workflows / rustfmt (push) Successful in 11s
Push Workflows / clippy (push) Failing after 58s
Push Workflows / leptos-test (push) Successful in 3m4s
Push Workflows / test (push) Successful in 3m22s
Push Workflows / build (push) Successful in 4m43s
Push Workflows / docker-build (push) Failing after 14m42s
Push Workflows / nix-build (push) Successful in 17m22s
Run rustfmt
2025-04-29 22:27:24 +00:00

60 lines
1.6 KiB
Rust

use axum::body::Body;
use axum::extract::Request;
use axum::middleware::Next;
use axum::response::Response;
use axum_login::AuthSession;
use http::StatusCode;
use crate::util::auth_backend::AuthBackend;
use axum::extract::FromRequestParts;
// Things in pkg/ are allowed automatically. This includes the CSS/JS/WASM files
const ALLOWED_PATHS: [&str; 5] = [
"/login",
"/signup",
"/api/login",
"/api/signup",
"/favicon.ico",
];
/**
* Middleware to require authentication for all paths except those in `ALLOWED_PATHS`
*
* If a user is not authenticated, they will be redirected to the login page
*/
pub async fn require_auth_middleware(
req: Request,
next: Next,
) -> Result<Response<Body>, (StatusCode, &'static str)> {
let path = req.uri().path();
if !ALLOWED_PATHS.contains(&path) {
let (mut parts, body) = req.into_parts();
let auth_session = AuthSession::<AuthBackend>::from_request_parts(&mut parts, &()).await?;
if auth_session.user.is_none() {
let response = Response::builder()
.status(StatusCode::TEMPORARY_REDIRECT)
.header("Location", "/login")
.body(Body::empty())
.map_err(|_| {
(
StatusCode::INTERNAL_SERVER_ERROR,
"Failed to build response",
)
})?;
return Ok(response);
}
let req = Request::from_parts(parts, body);
let response = next.run(req).await;
Ok(response)
} else {
let response = next.run(req).await;
Ok(response)
}
}