From c8de4473345ed581d373bece31486be46fc97bf9 Mon Sep 17 00:00:00 2001 From: Simon Bruder Date: Sun, 14 Jul 2024 13:38:36 +0200 Subject: [PATCH] Redirect to requested resource after login --- src/frontend/auth.rs | 13 +++++++++++-- src/middleware/error_handlers.rs | 6 +++++- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/src/frontend/auth.rs b/src/frontend/auth.rs index 0f5bed2..d2e4a79 100644 --- a/src/frontend/auth.rs +++ b/src/frontend/auth.rs @@ -49,10 +49,16 @@ struct LoginForm { password: String, } +#[derive(Deserialize)] +struct LoginQuery { + redirect_to: Option, +} + #[post("/login")] async fn login( req: HttpRequest, form: web::Form, + query: web::Query, ) -> Result { // Very basic authentication for now (only password, hardcoded in environment variable) if form.password @@ -61,9 +67,12 @@ async fn login( { Identity::login(&req.extensions(), "superuser".into()) .map_err(error::ErrorInternalServerError)?; - Ok(web::Redirect::to("/".to_owned()).see_other()) + Ok( + web::Redirect::to(query.into_inner().redirect_to.unwrap_or("/".to_string())) + .see_other(), + ) } else { - Ok(web::Redirect::to("/login".to_owned()).see_other()) + Ok(web::Redirect::to(req.uri().to_string()).see_other()) } } diff --git a/src/middleware/error_handlers.rs b/src/middleware/error_handlers.rs index 52c6bbe..91b5bc8 100644 --- a/src/middleware/error_handlers.rs +++ b/src/middleware/error_handlers.rs @@ -8,10 +8,14 @@ use actix_web::{dev::ServiceResponse, error, HttpResponse}; pub fn redirect_to_login( res: ServiceResponse, ) -> Result, error::Error> { + let redirect_to = format!( + "/login?{}", + serde_urlencoded::to_string(&[("redirect_to", res.request().uri().to_string())])? + ); Ok(ErrorHandlerResponse::Response( res.into_response( HttpResponse::SeeOther() - .insert_header(("Location", "/login")) + .insert_header(("Location", redirect_to)) .finish() .map_into_right_body(), ),