🐛 (user): Vuelve a la página de origen tras envío
Un envío anónimo a una ruta que sólo admite POST llevaba, tras iniciar sesión, a un 405 en blanco. Ahora vuelve a la página del Referer, si es del mismo Host, y avisa de que el envío no se ha guardado.
This commit is contained in:
parent
d074f252a7
commit
87711e4a37
6 changed files with 100 additions and 18 deletions
|
|
@ -41,32 +41,50 @@ fn login_redirect(request: HttpRequest, next: &'static str) -> Response {
|
|||
}
|
||||
|
||||
// Respuesta a un usuario anónimo sin acceso a una ruta (acción `AnonymousDenied`): el formulario de
|
||||
// inicio de sesión, que vuelve después a la ruta pedida.
|
||||
// inicio de sesión, que vuelve después a la página de la que venía (ver `return_path()`). Si
|
||||
// enviaba algo, se le avisa de que no se ha guardado: el envío se pierde, y no se repite al volver.
|
||||
//
|
||||
// Una petición HTMX seguiría la redirección sin avisar y pintaría el formulario dentro del
|
||||
// fragmento que esperaba, así que se le pide con `HX-Redirect` que cargue la página completa.
|
||||
// Vuelve después a la página que tenía abierta el navegador (`HX-Current-URL`), no a la ruta del
|
||||
// fragmento, que puede no admitir `GET`.
|
||||
pub(crate) fn offer_login(request: &HttpRequest) -> Option<Response> {
|
||||
let is_htmx = request.is_htmx();
|
||||
let waypoint = if is_htmx {
|
||||
Waypoint::new(
|
||||
request
|
||||
.hx_current_url()
|
||||
.and_then(|url| url.parse::<web::http::Uri>().ok())
|
||||
.and_then(|uri| uri.path_and_query().map(|pq| pq.as_str().to_owned())),
|
||||
)
|
||||
} else {
|
||||
Waypoint::new(request.uri().to_owned())
|
||||
};
|
||||
let login = waypoint.append_to(Context::new(request.clone()).route(LOGIN_PATH));
|
||||
Some(if is_htmx {
|
||||
let cx = Context::new(request.clone());
|
||||
let login = Waypoint::new(return_path(request)).append_to(cx.route(LOGIN_PATH));
|
||||
let response = if request.is_htmx() {
|
||||
HtmxResponse::empty().redirect(login).into_response()
|
||||
} else {
|
||||
Redirect::see_other(login).into_response()
|
||||
};
|
||||
Some(if request.method().is_safe() {
|
||||
response
|
||||
} else {
|
||||
response.with_message(
|
||||
&cx,
|
||||
MessageLevel::Warning,
|
||||
Lc::t("msg-login-required", &LOCALES_USER),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
// Ruta a la que volver tras iniciar sesión: la pedida, si se puede abrir de nuevo. La de un
|
||||
// fragmento HTMX o la de un envío puede no admitir `GET`, así que entonces es la página que tenía
|
||||
// abierta el navegador (`HX-Current-URL` o `Referer`). Un `Referer` de otro sitio, posible con
|
||||
// `server.trusted_origins`, no dice nada de esta aplicación: se vuelve sin destino.
|
||||
fn return_path(request: &HttpRequest) -> Option<String> {
|
||||
use web::http::{Uri, header};
|
||||
|
||||
let path_of = |uri: Uri| uri.path_and_query().map(|pq| pq.as_str().to_owned());
|
||||
if request.is_htmx() {
|
||||
return path_of(request.hx_current_url()?.parse().ok()?);
|
||||
}
|
||||
if request.method().is_safe() {
|
||||
return Some(request.uri().to_owned());
|
||||
}
|
||||
let headers = request.headers();
|
||||
let referer: Uri = headers.get(header::REFERER)?.to_str().ok()?.parse().ok()?;
|
||||
let host = headers.get(header::HOST)?.to_str().ok()?;
|
||||
(referer.authority()?.as_str() == host).then(|| path_of(referer))?
|
||||
}
|
||||
|
||||
// **< profile_get >********************************************************************************
|
||||
|
||||
/// GET /user - Perfil del usuario autenticado. Redirige al formulario de inicio de sesión si no hay
|
||||
|
|
@ -187,8 +205,8 @@ pub(crate) async fn public_profile_get(
|
|||
request: HttpRequest,
|
||||
web::Path(id): web::Path<i32>,
|
||||
) -> Result<Response, ErrorPage> {
|
||||
// El permiso se comprueba antes de buscar al usuario para no revelar qué ids existen. Sin él, la
|
||||
// misma respuesta que una ruta sin acceso: el inicio de sesión a un anónimo y 403 al resto.
|
||||
// El permiso se comprueba antes de buscar al usuario para no revelar qué ids existen. Sin él,
|
||||
// la misma respuesta que una ruta sin acceso: el inicio de sesión a un anónimo y 403 al resto.
|
||||
if current_user_id(&request) != Some(id)
|
||||
&& !has_permission(&request, &UserPermission::ViewProfiles)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -74,6 +74,7 @@ msg-email-change-pending =
|
|||
|
||||
msg-confirm-email-change = Press the button to use this email address in your account.
|
||||
|
||||
msg-login-required = Sign in to continue. What you just sent has not been saved.
|
||||
msg-account-created = Your account has been created. You can now sign in.
|
||||
msg-email-verified = Your email address has been confirmed.
|
||||
msg-password-reset-done = Your password has been changed. Sign in with the new one.
|
||||
|
|
|
|||
|
|
@ -74,6 +74,7 @@ msg-email-change-pending =
|
|||
|
||||
msg-confirm-email-change = Pulsa el botón para usar esta dirección de correo en tu cuenta.
|
||||
|
||||
msg-login-required = Inicia sesión para continuar. Lo que acabas de enviar no se ha guardado.
|
||||
msg-account-created = Tu cuenta se ha creado. Ya puedes iniciar sesión.
|
||||
msg-email-verified = Tu dirección de correo se ha confirmado.
|
||||
msg-password-reset-done = Tu contraseña se ha cambiado. Inicia sesión con la nueva.
|
||||
|
|
|
|||
|
|
@ -828,4 +828,51 @@ async fn anonymous_visitors_are_offered_to_sign_in(client: &Client) {
|
|||
reply.header("hx-redirect"),
|
||||
"/user/login?waypoint=%2Fadmin%2Fuser%2Fusers%3Fsort%3Dname"
|
||||
);
|
||||
// Reading a page or a fragment loses nothing, so there is nothing to warn about.
|
||||
assert_eq!(reply.header("set-cookie"), "");
|
||||
|
||||
// A submission returns to the page it came from: its own route may only accept `POST`.
|
||||
let submit = || {
|
||||
web::test::TestRequest::post()
|
||||
.uri("/admin/user/users/new")
|
||||
.header("host", "app.example")
|
||||
};
|
||||
let reply = client
|
||||
.send(submit().header("referer", "https://app.example/admin/user/users?page=2"))
|
||||
.await;
|
||||
assert_eq!(reply.status, Status::SEE_OTHER);
|
||||
assert_eq!(
|
||||
reply.location(),
|
||||
"/user/login?waypoint=%2Fadmin%2Fuser%2Fusers%3Fpage%3D2"
|
||||
);
|
||||
// The login page warns that it was not saved.
|
||||
let flash = reply.header("set-cookie").split(';').next().unwrap();
|
||||
let page = client.get("/user/login", Some(flash)).await;
|
||||
assert!(page.body.contains("Sign in to continue"), "{}", page.body);
|
||||
|
||||
// Without a page to return to, or with one of another site, it signs in without a destination.
|
||||
for reply in [
|
||||
client.send(submit()).await,
|
||||
client
|
||||
.send(submit().header("referer", "https://other.example/admin/user/users"))
|
||||
.await,
|
||||
] {
|
||||
assert_eq!(reply.status, Status::SEE_OTHER);
|
||||
assert_eq!(reply.location(), "/user/login");
|
||||
assert!(reply.header("set-cookie").starts_with("pagetop_flash="));
|
||||
}
|
||||
|
||||
// With HTMX, a submission also warns, and returns to the page open in the browser.
|
||||
let reply = client
|
||||
.send(
|
||||
submit()
|
||||
.header("hx-request", "true")
|
||||
.header("hx-current-url", "https://app.example/admin/user/users"),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
reply.header("hx-redirect"),
|
||||
"/user/login?waypoint=%2Fadmin%2Fuser%2Fusers"
|
||||
);
|
||||
assert!(reply.header("set-cookie").starts_with("pagetop_flash="));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -125,12 +125,18 @@ pub struct HttpRequest(Arc<RequestParts>);
|
|||
// de los handlers, donde un tipo grande se copiaría en cada retorno.
|
||||
#[derive(Debug)]
|
||||
struct RequestParts {
|
||||
method: http::Method,
|
||||
uri: http::Uri,
|
||||
headers: http::HeaderMap,
|
||||
extensions: http::Extensions,
|
||||
}
|
||||
|
||||
impl HttpRequest {
|
||||
/// Devuelve el método HTTP de la petición.
|
||||
pub fn method(&self) -> &http::Method {
|
||||
&self.0.method
|
||||
}
|
||||
|
||||
/// Devuelve la URI completa de la petición, incluyendo la *query string* si la hay.
|
||||
pub fn uri(&self) -> &str {
|
||||
self.0
|
||||
|
|
@ -224,6 +230,7 @@ impl HttpRequest {
|
|||
// También la usa el *middleware* que comprueba el acceso de las rutas, antes del *handler*.
|
||||
pub(crate) fn from_parts(parts: &http::request::Parts) -> Self {
|
||||
HttpRequest(Arc::new(RequestParts {
|
||||
method: parts.method.clone(),
|
||||
uri: parts.uri.clone(),
|
||||
headers: parts.headers.clone(),
|
||||
extensions: parts.extensions.clone(),
|
||||
|
|
@ -631,6 +638,7 @@ pub mod test {
|
|||
pub fn to_http_request(self) -> super::HttpRequest {
|
||||
let uri = self.uri.parse().unwrap();
|
||||
super::HttpRequest(std::sync::Arc::new(super::RequestParts {
|
||||
method: self.method,
|
||||
uri,
|
||||
headers: self.headers,
|
||||
extensions: self.extensions,
|
||||
|
|
|
|||
|
|
@ -70,3 +70,10 @@ async fn a_form_request_without_fields_is_rejected() {
|
|||
let (status, _) = send(web::test::TestRequest::post()).await;
|
||||
assert!(status.is_client_error());
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn http_request_exposes_the_method() {
|
||||
let request = web::test::TestRequest::post().to_http_request();
|
||||
assert_eq!(request.method(), web::http::Method::POST);
|
||||
assert!(!request.method().is_safe());
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue