fmt: clippy and fmt

This commit is contained in:
silver 2023-07-30 00:48:15 +01:00
parent 2b96d498a7
commit e21af089d1
2 changed files with 62 additions and 99 deletions

View file

@ -1,18 +1,15 @@
use chrono::{DateTime, SecondsFormat, Utc}; use chrono::{DateTime, SecondsFormat, Utc};
use skynet_ldap_backend::{get_config, Config, db_init, Accounts, AccountsNew};
use std::error::Error;
use sqlx::{Pool, Sqlite};
use rand::{thread_rng, Rng};
use rand::distributions::Alphanumeric;
use lettre::{ use lettre::{
message::{header, MultiPart, SinglePart}, message::{header, MultiPart, SinglePart},
SmtpTransport, Message, Transport, transport::smtp::{authentication::Credentials, response::Response},
transport::smtp::{ Message, SmtpTransport, Transport,
authentication::Credentials,
response::Response
},
}; };
use maud::html; use maud::html;
use rand::distributions::Alphanumeric;
use rand::{thread_rng, Rng};
use skynet_ldap_backend::{db_init, get_config, Accounts, AccountsNew, Config};
use sqlx::{Pool, Sqlite};
use std::error::Error;
#[async_std::main] #[async_std::main]
async fn main() { async fn main() {
@ -20,34 +17,31 @@ async fn main() {
let db = db_init(&config).await.unwrap(); let db = db_init(&config).await.unwrap();
let now = Utc::now(); let now = Utc::now();
if let Ok(records) = read_csv(&config){ if let Ok(records) = read_csv(&config) {
for record in records { for record in records {
// check if the email is already in the db // check if the email is already in the db
if !check(&db, &record.email).await { if !check(&db, &record.email).await {
continue; continue;
} }
// generate a auth key // generate a auth key
let auth = generate_auth(); let auth = generate_auth();
match send_mail(&config, &record, &auth) { match send_mail(&config, &record, &auth) {
Ok(_) => { Ok(_) => match save_to_db(&db, now, &record, &auth).await {
match save_to_db(&db, now, &record, &auth).await { Ok(_) => {}
Ok(_) => {} Err(e) => {
Err(e) => { println!("Unable to save to db {} {e:?}", &record.email);
println!("Unable to save to db {} {e:?}", &record.email); }
} },
Err(e) => {
println!("Unable to send mail to {} {e:?}", &record.email);
} }
}
Err(e) => {
println!("Unable to send mail to {} {e:?}", &record.email);
}
} }
} }
} }
} }
#[derive(Debug, serde::Deserialize)] #[derive(Debug, serde::Deserialize)]
struct Record { struct Record {
#[serde(rename = "MemID")] #[serde(rename = "MemID")]
@ -72,7 +66,7 @@ fn read_csv(config: &Config) -> Result<Vec<Record>, Box<dyn Error>> {
// Notice that we need to provide a type hint for automatic // Notice that we need to provide a type hint for automatic
// deserialization. // deserialization.
let record: Record = result?; let record: Record = result?;
if record.mem_id == "" { if record.mem_id.is_empty() {
continue; continue;
} }
records.push(record); records.push(record);
@ -93,11 +87,11 @@ async fn check_users(db: &Pool<Sqlite>, mail: &str) -> bool {
WHERE mail == ? WHERE mail == ?
"#, "#,
) )
.bind(mail) .bind(mail)
.fetch_all(db) .fetch_all(db)
.await .await
.unwrap_or(vec![]) .unwrap_or(vec![])
.is_empty() .is_empty()
} }
async fn check_pending(db: &Pool<Sqlite>, mail: &str) -> bool { async fn check_pending(db: &Pool<Sqlite>, mail: &str) -> bool {
sqlx::query_as::<_, Accounts>( sqlx::query_as::<_, Accounts>(
@ -107,20 +101,16 @@ async fn check_pending(db: &Pool<Sqlite>, mail: &str) -> bool {
WHERE mail == ? WHERE mail == ?
"#, "#,
) )
.bind(mail) .bind(mail)
.fetch_all(db) .fetch_all(db)
.await .await
.unwrap_or(vec![]) .unwrap_or(vec![])
.is_empty() .is_empty()
} }
// from https://rust-lang-nursery.github.io/rust-cookbook/algorithms/randomness.html#create-random-passwords-from-a-set-of-alphanumeric-characters // from https://rust-lang-nursery.github.io/rust-cookbook/algorithms/randomness.html#create-random-passwords-from-a-set-of-alphanumeric-characters
fn generate_auth() -> String { fn generate_auth() -> String {
thread_rng() thread_rng().sample_iter(&Alphanumeric).take(30).map(char::from).collect()
.sample_iter(&Alphanumeric)
.take(30)
.map(char::from)
.collect()
} }
// using https://github.com/lettre/lettre/blob/57886c367d69b4d66300b322c94bd910b1eca364/examples/maud_html.rs // using https://github.com/lettre/lettre/blob/57886c367d69b4d66300b322c94bd910b1eca364/examples/maud_html.rs
@ -145,7 +135,7 @@ fn send_mail(config: &Config, record: &Record, auth: &str) -> Result<Response, l
h2 { "Hello from Skynet!" } h2 { "Hello from Skynet!" }
// Substitute in the name of our recipient. // Substitute in the name of our recipient.
p { "Hi " (recipient) "," } p { "Hi " (recipient) "," }
p { p {
"If you are a new member please use the following link:" "If you are a new member please use the following link:"
br; br;
a href=(link_new) { (link_new) } a href=(link_new) { (link_new) }
@ -160,7 +150,7 @@ fn send_mail(config: &Config, record: &Record, auth: &str) -> Result<Response, l
br; br;
a href=(discord) { (discord) } a href=(discord) { (discord) }
} }
p { p {
"UL Computer Society" "UL Computer Society"
br; br;
@ -168,7 +158,7 @@ fn send_mail(config: &Config, record: &Record, auth: &str) -> Result<Response, l
} }
} }
}; };
let body_text = format!( let body_text = format!(
r#" r#"
Hi {recipient} Hi {recipient}
@ -189,57 +179,40 @@ fn send_mail(config: &Config, record: &Record, auth: &str) -> Result<Response, l
// Build the message. // Build the message.
let email = Message::builder() let email = Message::builder()
.from(sender.parse().unwrap()) .from(sender.parse().unwrap())
.to(mail.parse().unwrap()) .to(mail.parse().unwrap())
.subject("Skynet: New Account.") .subject("Skynet: New Account.")
.multipart( .multipart(
// This is composed of two parts. // This is composed of two parts.
// also helps not trip spam settings (uneven number of url's // also helps not trip spam settings (uneven number of url's
MultiPart::alternative() MultiPart::alternative()
.singlepart( .singlepart(SinglePart::builder().header(header::ContentType::TEXT_PLAIN).body(body_text))
SinglePart::builder() .singlepart(SinglePart::builder().header(header::ContentType::TEXT_HTML).body(html.into_string())),
.header(header::ContentType::TEXT_PLAIN) )
.body(body_text), .expect("failed to build email");
)
.singlepart(
SinglePart::builder()
.header(header::ContentType::TEXT_HTML)
.body(html.into_string()),
),
)
.expect("failed to build email");
let creds = Credentials::new(config.mail_user.clone(), config.mail_pass.clone()); let creds = Credentials::new(config.mail_user.clone(), config.mail_pass.clone());
// Open a remote connection to gmail using STARTTLS // Open a remote connection to gmail using STARTTLS
let mailer = SmtpTransport::starttls_relay(&config.mail_smtp) let mailer = SmtpTransport::starttls_relay(&config.mail_smtp).unwrap().credentials(creds).build();
.unwrap()
.credentials(creds)
.build();
// Send the email // Send the email
mailer.send(&email) mailer.send(&email)
} }
async fn save_to_db(db: &Pool<Sqlite>, now: DateTime<Utc>, record: &Record, auth: &str) -> Result<Option<AccountsNew>, sqlx::Error> { async fn save_to_db(db: &Pool<Sqlite>, now: DateTime<Utc>, record: &Record, auth: &str) -> Result<Option<AccountsNew>, sqlx::Error> {
sqlx::query_as::<_, AccountsNew>( sqlx::query_as::<_, AccountsNew>(
" "
INSERT OR REPLACE INTO accounts_new (mail, auth_code, date_iso, date_expiry, name_first, name_surname) INSERT OR REPLACE INTO accounts_new (mail, auth_code, date_iso, date_expiry, name_first, name_surname)
VALUES (?1, ?2, ?3, ?4, ?5, ?6) VALUES (?1, ?2, ?3, ?4, ?5, ?6)
", ",
) )
.bind(record.email.to_owned()) .bind(record.email.to_owned())
.bind(auth.to_owned()) .bind(auth.to_owned())
.bind(now.to_rfc3339_opts(SecondsFormat::Millis, true)) .bind(now.to_rfc3339_opts(SecondsFormat::Millis, true))
.bind(record.expiry.to_owned()) .bind(record.expiry.to_owned())
.bind(record.name_first.to_owned()) .bind(record.name_first.to_owned())
.bind(record.name_second.to_owned()) .bind(record.name_second.to_owned())
.fetch_optional(db) .fetch_optional(db)
.await .await
} }

View file

@ -40,7 +40,7 @@ pub struct Accounts {
mail: String, mail: String,
student_id: String, student_id: String,
enabled: bool, enabled: bool,
secure: bool, secure: bool,
} }
pub async fn db_init(config: &Config) -> Result<Pool<Sqlite>, Error> { pub async fn db_init(config: &Config) -> Result<Pool<Sqlite>, Error> {
@ -74,12 +74,12 @@ pub async fn db_init(config: &Config) -> Result<Pool<Sqlite>, Error> {
name_surname integer not null name_surname integer not null
)", )",
) )
.execute(&pool) .execute(&pool)
.await?; .await?;
sqlx::query("CREATE INDEX IF NOT EXISTS index_auth_code ON accounts_new (auth_code)") sqlx::query("CREATE INDEX IF NOT EXISTS index_auth_code ON accounts_new (auth_code)")
.execute(&pool) .execute(&pool)
.await?; .await?;
// this is for active use // this is for active use
sqlx::query( sqlx::query(
@ -96,9 +96,7 @@ pub async fn db_init(config: &Config) -> Result<Pool<Sqlite>, Error> {
.execute(&pool) .execute(&pool)
.await?; .await?;
sqlx::query("CREATE INDEX IF NOT EXISTS index_uid_number ON accounts (uid)") sqlx::query("CREATE INDEX IF NOT EXISTS index_uid_number ON accounts (uid)").execute(&pool).await?;
.execute(&pool)
.await?;
update_accounts(&pool, config).await; update_accounts(&pool, config).await;
@ -190,12 +188,7 @@ async fn update_accounts(pool: &Pool<Sqlite>, config: &Config) {
ldap.simple_bind(&config.ldap_admin, &config.ldap_admin_pw).unwrap().success().unwrap(); ldap.simple_bind(&config.ldap_admin, &config.ldap_admin_pw).unwrap().success().unwrap();
// use this to pre load a large chunk of data // use this to pre load a large chunk of data
if let Ok(x) = ldap.search( if let Ok(x) = ldap.search("ou=users,dc=skynet,dc=ie", Scope::OneLevel, "(objectClass=*)", vec!["uid", "uidNumber", "skDiscord", "skMemberOf", "mail", "skID", "skSecure"]) {
"ou=users,dc=skynet,dc=ie",
Scope::OneLevel,
"(objectClass=*)",
vec!["uid", "uidNumber", "skDiscord", "skMemberOf", "mail", "skID", "skSecure"]
) {
if let Ok((rs, _res)) = x.success() { if let Ok((rs, _res)) = x.success() {
for entry in rs { for entry in rs {
let tmp = SearchEntry::construct(entry); let tmp = SearchEntry::construct(entry);
@ -226,10 +219,7 @@ async fn update_accounts(pool: &Pool<Sqlite>, config: &Config) {
if tmp.attrs.contains_key("skID") && !tmp.attrs["skID"].is_empty() { if tmp.attrs.contains_key("skID") && !tmp.attrs["skID"].is_empty() {
tmp_account.student_id = tmp.attrs["skID"][0].clone(); tmp_account.student_id = tmp.attrs["skID"][0].clone();
} }
if tmp.attrs.contains_key("skMemberOf") if tmp.attrs.contains_key("skMemberOf") && !tmp.attrs["skMemberOf"].is_empty() && tmp.attrs["skMemberOf"].contains(&String::from("cn=skynet-users-linux,ou=groups,dc=skynet,dc=ie")) {
&& !tmp.attrs["skMemberOf"].is_empty()
&& tmp.attrs["skMemberOf"].contains(&String::from("cn=skynet-users-linux,ou=groups,dc=skynet,dc=ie"))
{
tmp_account.enabled = true; tmp_account.enabled = true;
} }
if tmp.attrs.contains_key("skSecure") && !tmp.attrs["skSecure"].is_empty() { if tmp.attrs.contains_key("skSecure") && !tmp.attrs["skSecure"].is_empty() {