Using Flash for login error message.

This commit is contained in:
Alex Wright 2020-02-29 20:56:50 +01:00
parent 9eaf121454
commit dd21d419bd
2 changed files with 23 additions and 7 deletions

View File

@ -26,7 +26,14 @@ use num::BigUint;
use openssl::rsa::Rsa; use openssl::rsa::Rsa;
use ldap3::{ LdapConn, Scope, SearchEntry }; 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::json::Json;
use rocket_contrib::templates::Template; use rocket_contrib::templates::Template;
@ -110,24 +117,30 @@ struct LoginData {
} }
#[derive(Serialize)] #[derive(Serialize)]
struct EmptyContext { struct LoginFormContext {
message: Option<String>,
} }
#[get("/login")] #[get("/login")]
fn login_form() -> Template { fn login_form(flash: Option<FlashMessage<'_, '_>>) -> Template {
let context = EmptyContext {}; let context = LoginFormContext {
message: match flash {
Some(ref msg) => Some(msg.msg().to_string()),
_ => None,
},
};
Template::render("login_form", &context) Template::render("login_form", &context)
} }
#[post("/login", data = "<form_data>")] #[post("/login", data = "<form_data>")]
fn login(form_data: Form<LoginData>) -> String { fn login(form_data: Form<LoginData>) -> Result<Redirect, Flash<Redirect>> {
let auth = BasicAuthentication { let auth = BasicAuthentication {
username: form_data.username.to_owned(), username: form_data.username.to_owned(),
password: form_data.password.to_owned(), password: form_data.password.to_owned(),
}; };
match auth_user(&auth) { match auth_user(&auth) {
Ok(ldap_user) => format!("OK! {:?}", ldap_user), Ok(_ldap_user) => Ok(Redirect::to("/")),
_ => format!("Bad :("), _ => Err(Flash::error(Redirect::to(uri!(login_form)), "Not able to authenticate with given credentials.")),
} }
} }

View File

@ -3,6 +3,9 @@
{% block content %} {% block content %}
<h1>Login</h1> <h1>Login</h1>
<form action="/login" method="POST"> <form action="/login" method="POST">
{% if message %}
<strong>{{ message }}</strong>
{% endif %}
<fieldset> <fieldset>
<legend>Login</legend> <legend>Login</legend>
<div class="form-group"> <div class="form-group">