Avoid panics (#392)
- Use `Result` as much as possible - Display errors instead of panicking TODO (maybe in another PR? this one is already quite big): - Find a way to merge Ructe/ErrorPage types, so that we can have routes returning `Result<X, ErrorPage>` instead of panicking when we have an `Error` - Display more details about the error, to make it easier to debug (sorry, this isn't going to be fun to review, the diff is huge, but it is always the same changes)
This commit is contained in:
+12
-7
@@ -14,6 +14,7 @@ use plume_models::{
|
||||
users::{User, AUTH_COOKIE}
|
||||
};
|
||||
|
||||
|
||||
#[get("/login?<m>")]
|
||||
pub fn new(user: Option<User>, conn: DbConn, m: Option<String>, intl: I18n) -> Ructe {
|
||||
render!(session::login(
|
||||
@@ -35,30 +36,34 @@ pub struct LoginForm {
|
||||
#[post("/login", data = "<form>")]
|
||||
pub fn create(conn: DbConn, form: LenientForm<LoginForm>, flash: Option<FlashMessage>, mut cookies: Cookies, intl: I18n) -> Result<Redirect, Ructe> {
|
||||
let user = User::find_by_email(&*conn, &form.email_or_name)
|
||||
.or_else(|| User::find_local(&*conn, &form.email_or_name));
|
||||
.or_else(|_| User::find_local(&*conn, &form.email_or_name));
|
||||
let mut errors = match form.validate() {
|
||||
Ok(_) => ValidationErrors::new(),
|
||||
Err(e) => e
|
||||
};
|
||||
|
||||
if let Some(user) = user.clone() {
|
||||
let user_id = if let Ok(user) = user {
|
||||
if !user.auth(&form.password) {
|
||||
let mut err = ValidationError::new("invalid_login");
|
||||
err.message = Some(Cow::from("Invalid username or password"));
|
||||
errors.add("email_or_name", err)
|
||||
errors.add("email_or_name", err);
|
||||
user.id.to_string()
|
||||
} else {
|
||||
String::new()
|
||||
}
|
||||
} else {
|
||||
// Fake password verification, only to avoid different login times
|
||||
// that could be used to see if an email adress is registered or not
|
||||
User::get(&*conn, 1).map(|u| u.auth(&form.password));
|
||||
User::get(&*conn, 1).map(|u| u.auth(&form.password)).expect("No user is registered");
|
||||
|
||||
let mut err = ValidationError::new("invalid_login");
|
||||
err.message = Some(Cow::from("Invalid username or password"));
|
||||
errors.add("email_or_name", err)
|
||||
}
|
||||
errors.add("email_or_name", err);
|
||||
String::new()
|
||||
};
|
||||
|
||||
if errors.is_empty() {
|
||||
cookies.add_private(Cookie::build(AUTH_COOKIE, user.unwrap().id.to_string())
|
||||
cookies.add_private(Cookie::build(AUTH_COOKIE, user_id)
|
||||
.same_site(SameSite::Lax)
|
||||
.finish());
|
||||
|
||||
|
||||
Reference in New Issue
Block a user