From dd21d419bdc1aa581fc30de1d28d165551c8762a Mon Sep 17 00:00:00 2001 From: Alex Wright Date: Sat, 29 Feb 2020 20:56:50 +0100 Subject: [PATCH] Using Flash for login error message. --- src/main.rs | 27 ++++++++++++++++++++------- templates/login_form.html.tera | 3 +++ 2 files changed, 23 insertions(+), 7 deletions(-) diff --git a/src/main.rs b/src/main.rs index 8bd49dd..c456560 100644 --- a/src/main.rs +++ b/src/main.rs @@ -26,7 +26,14 @@ use num::BigUint; use openssl::rsa::Rsa; use ldap3::{ LdapConn, Scope, SearchEntry }; -use rocket::request::Form; +use rocket::request::{ + FlashMessage, + Form, +}; +use rocket::response::{ + Flash, + Redirect, +}; use rocket_contrib::json::Json; use rocket_contrib::templates::Template; @@ -110,24 +117,30 @@ struct LoginData { } #[derive(Serialize)] -struct EmptyContext { +struct LoginFormContext { + message: Option, } #[get("/login")] -fn login_form() -> Template { - let context = EmptyContext {}; +fn login_form(flash: Option>) -> Template { + let context = LoginFormContext { + message: match flash { + Some(ref msg) => Some(msg.msg().to_string()), + _ => None, + }, + }; Template::render("login_form", &context) } #[post("/login", data = "")] -fn login(form_data: Form) -> String { +fn login(form_data: Form) -> Result> { let auth = BasicAuthentication { username: form_data.username.to_owned(), password: form_data.password.to_owned(), }; match auth_user(&auth) { - Ok(ldap_user) => format!("OK! {:?}", ldap_user), - _ => format!("Bad :("), + Ok(_ldap_user) => Ok(Redirect::to("/")), + _ => Err(Flash::error(Redirect::to(uri!(login_form)), "Not able to authenticate with given credentials.")), } } diff --git a/templates/login_form.html.tera b/templates/login_form.html.tera index e696abd..194f175 100644 --- a/templates/login_form.html.tera +++ b/templates/login_form.html.tera @@ -3,6 +3,9 @@ {% block content %}

Login

+ {% if message %} + {{ message }} + {% endif %}
Login