fmt: clippy and fmt
This commit is contained in:
parent
2b96d498a7
commit
e21af089d1
2 changed files with 62 additions and 99 deletions
|
@ -1,18 +1,15 @@
|
|||
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::{
|
||||
message::{header, MultiPart, SinglePart},
|
||||
SmtpTransport, Message, Transport,
|
||||
transport::smtp::{
|
||||
authentication::Credentials,
|
||||
response::Response
|
||||
},
|
||||
transport::smtp::{authentication::Credentials, response::Response},
|
||||
Message, SmtpTransport, Transport,
|
||||
};
|
||||
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 fn main() {
|
||||
|
@ -20,7 +17,7 @@ async fn main() {
|
|||
let db = db_init(&config).await.unwrap();
|
||||
let now = Utc::now();
|
||||
|
||||
if let Ok(records) = read_csv(&config){
|
||||
if let Ok(records) = read_csv(&config) {
|
||||
for record in records {
|
||||
// check if the email is already in the db
|
||||
if !check(&db, &record.email).await {
|
||||
|
@ -31,23 +28,20 @@ async fn main() {
|
|||
let auth = generate_auth();
|
||||
|
||||
match send_mail(&config, &record, &auth) {
|
||||
Ok(_) => {
|
||||
match save_to_db(&db, now, &record, &auth).await {
|
||||
Ok(_) => {}
|
||||
Err(e) => {
|
||||
println!("Unable to save to db {} {e:?}", &record.email);
|
||||
}
|
||||
Ok(_) => match save_to_db(&db, now, &record, &auth).await {
|
||||
Ok(_) => {}
|
||||
Err(e) => {
|
||||
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)]
|
||||
struct Record {
|
||||
#[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
|
||||
// deserialization.
|
||||
let record: Record = result?;
|
||||
if record.mem_id == "" {
|
||||
if record.mem_id.is_empty() {
|
||||
continue;
|
||||
}
|
||||
records.push(record);
|
||||
|
@ -93,11 +87,11 @@ async fn check_users(db: &Pool<Sqlite>, mail: &str) -> bool {
|
|||
WHERE mail == ?
|
||||
"#,
|
||||
)
|
||||
.bind(mail)
|
||||
.fetch_all(db)
|
||||
.await
|
||||
.unwrap_or(vec![])
|
||||
.is_empty()
|
||||
.bind(mail)
|
||||
.fetch_all(db)
|
||||
.await
|
||||
.unwrap_or(vec![])
|
||||
.is_empty()
|
||||
}
|
||||
async fn check_pending(db: &Pool<Sqlite>, mail: &str) -> bool {
|
||||
sqlx::query_as::<_, Accounts>(
|
||||
|
@ -107,20 +101,16 @@ async fn check_pending(db: &Pool<Sqlite>, mail: &str) -> bool {
|
|||
WHERE mail == ?
|
||||
"#,
|
||||
)
|
||||
.bind(mail)
|
||||
.fetch_all(db)
|
||||
.await
|
||||
.unwrap_or(vec![])
|
||||
.is_empty()
|
||||
.bind(mail)
|
||||
.fetch_all(db)
|
||||
.await
|
||||
.unwrap_or(vec![])
|
||||
.is_empty()
|
||||
}
|
||||
|
||||
// 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 {
|
||||
thread_rng()
|
||||
.sample_iter(&Alphanumeric)
|
||||
.take(30)
|
||||
.map(char::from)
|
||||
.collect()
|
||||
thread_rng().sample_iter(&Alphanumeric).take(30).map(char::from).collect()
|
||||
}
|
||||
|
||||
// using https://github.com/lettre/lettre/blob/57886c367d69b4d66300b322c94bd910b1eca364/examples/maud_html.rs
|
||||
|
@ -189,57 +179,40 @@ fn send_mail(config: &Config, record: &Record, auth: &str) -> Result<Response, l
|
|||
|
||||
// Build the message.
|
||||
let email = Message::builder()
|
||||
.from(sender.parse().unwrap())
|
||||
.to(mail.parse().unwrap())
|
||||
.subject("Skynet: New Account.")
|
||||
.multipart(
|
||||
// This is composed of two parts.
|
||||
// also helps not trip spam settings (uneven number of url's
|
||||
MultiPart::alternative()
|
||||
.singlepart(
|
||||
SinglePart::builder()
|
||||
.header(header::ContentType::TEXT_PLAIN)
|
||||
.body(body_text),
|
||||
)
|
||||
.singlepart(
|
||||
SinglePart::builder()
|
||||
.header(header::ContentType::TEXT_HTML)
|
||||
.body(html.into_string()),
|
||||
),
|
||||
)
|
||||
.expect("failed to build email");
|
||||
|
||||
.from(sender.parse().unwrap())
|
||||
.to(mail.parse().unwrap())
|
||||
.subject("Skynet: New Account.")
|
||||
.multipart(
|
||||
// This is composed of two parts.
|
||||
// also helps not trip spam settings (uneven number of url's
|
||||
MultiPart::alternative()
|
||||
.singlepart(SinglePart::builder().header(header::ContentType::TEXT_PLAIN).body(body_text))
|
||||
.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());
|
||||
|
||||
// Open a remote connection to gmail using STARTTLS
|
||||
let mailer = SmtpTransport::starttls_relay(&config.mail_smtp)
|
||||
.unwrap()
|
||||
.credentials(creds)
|
||||
.build();
|
||||
let mailer = SmtpTransport::starttls_relay(&config.mail_smtp).unwrap().credentials(creds).build();
|
||||
|
||||
// Send the 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>(
|
||||
"
|
||||
INSERT OR REPLACE INTO accounts_new (mail, auth_code, date_iso, date_expiry, name_first, name_surname)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6)
|
||||
",
|
||||
)
|
||||
.bind(record.email.to_owned())
|
||||
.bind(auth.to_owned())
|
||||
.bind(now.to_rfc3339_opts(SecondsFormat::Millis, true))
|
||||
.bind(record.expiry.to_owned())
|
||||
.bind(record.name_first.to_owned())
|
||||
.bind(record.name_second.to_owned())
|
||||
.fetch_optional(db)
|
||||
.await
|
||||
.bind(record.email.to_owned())
|
||||
.bind(auth.to_owned())
|
||||
.bind(now.to_rfc3339_opts(SecondsFormat::Millis, true))
|
||||
.bind(record.expiry.to_owned())
|
||||
.bind(record.name_first.to_owned())
|
||||
.bind(record.name_second.to_owned())
|
||||
.fetch_optional(db)
|
||||
.await
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
|
24
src/lib.rs
24
src/lib.rs
|
@ -74,12 +74,12 @@ pub async fn db_init(config: &Config) -> Result<Pool<Sqlite>, Error> {
|
|||
name_surname integer not null
|
||||
)",
|
||||
)
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
|
||||
sqlx::query("CREATE INDEX IF NOT EXISTS index_auth_code ON accounts_new (auth_code)")
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
|
||||
// this is for active use
|
||||
sqlx::query(
|
||||
|
@ -96,9 +96,7 @@ pub async fn db_init(config: &Config) -> Result<Pool<Sqlite>, Error> {
|
|||
.execute(&pool)
|
||||
.await?;
|
||||
|
||||
sqlx::query("CREATE INDEX IF NOT EXISTS index_uid_number ON accounts (uid)")
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
sqlx::query("CREATE INDEX IF NOT EXISTS index_uid_number ON accounts (uid)").execute(&pool).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();
|
||||
|
||||
// use this to pre load a large chunk of data
|
||||
if let Ok(x) = ldap.search(
|
||||
"ou=users,dc=skynet,dc=ie",
|
||||
Scope::OneLevel,
|
||||
"(objectClass=*)",
|
||||
vec!["uid", "uidNumber", "skDiscord", "skMemberOf", "mail", "skID", "skSecure"]
|
||||
) {
|
||||
if let Ok(x) = ldap.search("ou=users,dc=skynet,dc=ie", Scope::OneLevel, "(objectClass=*)", vec!["uid", "uidNumber", "skDiscord", "skMemberOf", "mail", "skID", "skSecure"]) {
|
||||
if let Ok((rs, _res)) = x.success() {
|
||||
for entry in rs {
|
||||
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() {
|
||||
tmp_account.student_id = tmp.attrs["skID"][0].clone();
|
||||
}
|
||||
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"))
|
||||
{
|
||||
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_account.enabled = true;
|
||||
}
|
||||
if tmp.attrs.contains_key("skSecure") && !tmp.attrs["skSecure"].is_empty() {
|
||||
|
|
Loading…
Reference in a new issue