From 4209e4b23cf1e350b953fbec33116587b9b73a5e Mon Sep 17 00:00:00 2001 From: Xander Bil Date: Tue, 12 Nov 2024 17:51:55 +0100 Subject: [PATCH] fix auth middleware bug --- src/main.rs | 8 ++++---- src/routes/middelware.rs | 23 ++++++++++++++++++----- 2 files changed, 22 insertions(+), 9 deletions(-) diff --git a/src/main.rs b/src/main.rs index 6d5b455..60b7333 100644 --- a/src/main.rs +++ b/src/main.rs @@ -15,7 +15,7 @@ use axum::{ use config::Config; use migration::{Migrator, MigratorTrait}; use models::user::UserSession; -use routes::{auth, middelware::auth_guard, user::update_password}; +use routes::{auth, middelware::auth, user::update_password}; use axum::response::IntoResponse; use sea_orm::Database; @@ -33,8 +33,8 @@ async fn index(Extension(user): Extension) -> impl IntoResponse {

Good day {}

- - + +
@@ -62,7 +62,7 @@ async fn main() { .route("/", get(index)) .route("/index", get(index)) .route("/update_password", post(update_password)) - .route_layer(axum::middleware::from_fn(auth_guard)) + .route_layer(axum::middleware::from_fn(auth)) .route("/login", get(login)) .route("/oauth/callback", get(callback)) .with_state(state); diff --git a/src/routes/middelware.rs b/src/routes/middelware.rs index e88f7a4..ee895e3 100644 --- a/src/routes/middelware.rs +++ b/src/routes/middelware.rs @@ -2,7 +2,7 @@ use axum::{ extract::Request, http::{HeaderMap, StatusCode}, middleware::Next, - response::{IntoResponse, Redirect}, + response::{IntoResponse, Redirect, Response}, }; use axum_extra::extract::SignedCookieJar; @@ -21,12 +21,22 @@ pub struct JwkSet { pub keys: Vec, } -pub async fn auth_guard( +pub async fn auth(headers: HeaderMap, req: Request, next: Next) -> impl IntoResponse { + let redirect = req.uri().clone(); + match auth_guard(headers, req, next).await { + Ok(r) => r, + Err(e) => { + eprintln!("{}", e); + Redirect::to(&format!("/login?redirect={}", redirect)).into_response() + } + } +} + +async fn auth_guard( headers: HeaderMap, mut req: Request, next: Next, -) -> Result { - let redirect = req.uri().clone(); +) -> Result { let jar = SignedCookieJar::from_headers(&headers, Config::get().cookies_key.clone()); let token = jar @@ -68,5 +78,8 @@ pub async fn auth_guard( } } - Ok(Redirect::to(&format!("/login?redirect={}", redirect)).into_response()) + Err(ThisError::Generic { + code: StatusCode::UNAUTHORIZED, + message: "unauthorized".to_string(), + }) }