From b155c1733703c33254b4c079433eac695bf7f87e Mon Sep 17 00:00:00 2001 From: finga Date: Fri, 28 Aug 2020 22:27:54 +0200 Subject: [PATCH] Refactor `reset_prepare()` to reduce indents --- src/main.rs | 71 +++++++++++++++++++++++------------------------------ 1 file changed, 31 insertions(+), 40 deletions(-) diff --git a/src/main.rs b/src/main.rs index ab195e9..16674f7 100644 --- a/src/main.rs +++ b/src/main.rs @@ -58,49 +58,40 @@ fn reset_prepare(config: &Ldap0rConfig, keys: &Keys, email_address: &str) -> Res ldap.unbind()?; let (rs, _res) = result.success()?; - if rs.len() == 1 { - // generate key - let mut rng = rand::thread_rng(); - let key: String = (0..64) - .map(|_| BASE62[rng.gen::() % 62] as char) - .collect(); - - // store key with id - let keys = Arc::clone(&keys.keys); - if let Ok(mut keys) = keys.lock() { - keys.insert(key.to_string(), email_address.to_string()); - debug!("Generated new key for '{}'", email_address); - - // generate email - let email = EmailBuilder::new() - .to(email_address) - .from("ldap0r@example.com") - .subject("LDAP password reset") - .text(format!( - "Use following url to set a new password: {}/reset/{}", - config.domain, key - )) - .build()?; - - // send email - let mut mailer = SmtpClient::new_unencrypted_localhost()?.transport(); - let result = mailer.send(email.into()); - - if result.is_ok() { - info!("Password reset email was sent to '{}'", email_address); - } else { - bail!( - "Sending password reset email with reset URL to '{}' failed", - email_address - ); - } - } else { - bail!("Could not aquire lock for keys"); - }; - } else { + if rs.len() != 1 { bail!("Invalid password reset request for '{}'", email_address); } + // generate key + let mut rng = rand::thread_rng(); + let key: String = (0..64) + .map(|_| BASE62[rng.gen::() % 62] as char) + .collect(); + + // store key with id + let keys = Arc::clone(&keys.keys); + let mut keys = keys + .lock() + .map_err(|e| anyhow!("Could not aquire lock for keys: {}", e))?; + keys.insert(key.to_string(), email_address.to_string()); + debug!("Generated new key for '{}'", email_address); + + // generate email + let email = EmailBuilder::new() + .to(email_address) + .from("ldap0r@example.com") + .subject("LDAP password reset") + .text(format!( + "Use following url to set a new password: {}/reset/{}", + config.domain, key + )) + .build()?; + + // send email + let mut mailer = SmtpClient::new_unencrypted_localhost()?.transport(); + mailer.send(email.into())?; + info!("Password reset email was sent to '{}'", email_address); + Ok(()) }