fix: better strucurter in other modules

This commit is contained in:
silver 2023-08-06 14:42:09 +01:00
parent 3165f67e4c
commit 9d28d89eee
3 changed files with 334 additions and 338 deletions

View file

@ -1,6 +1,6 @@
use skynet_ldap_backend::{ use skynet_ldap_backend::{
db_init, get_config, db_init, get_config,
methods::{account_new, account_recover, account_update::post_update_ldap}, methods::{account_new, account_recover, account_update},
State, State,
}; };
@ -20,9 +20,9 @@ async fn main() -> tide::Result<()> {
let mut app = tide::with_state(state); let mut app = tide::with_state(state);
app.at("/ldap/update").post(post_update_ldap); app.at("/ldap/update").post(account_update::submit);
app.at("/ldap/new/email").post(account_new::post::email::submit); app.at("/ldap/new/email").post(account_new::email::submit);
app.at("/ldap/new/account").post(account_new::post::account::submit); app.at("/ldap/new/account").post(account_new::account::submit);
app.at("/ldap/recover/password").post(account_recover::password::reset); app.at("/ldap/recover/password").post(account_recover::password::reset);
app.at("/ldap/recover/password/auth").post(account_recover::password::auth); app.at("/ldap/recover/password/auth").post(account_recover::password::auth);

View file

@ -13,161 +13,158 @@ use tide::{
Request, Request,
}; };
pub mod post { pub mod email {
use super::*; use super::*;
pub mod email { #[derive(Debug, Deserialize)]
use super::*; struct SignupEmail {
email: String,
}
#[derive(Debug, Deserialize)] pub async fn submit(mut req: Request<State>) -> tide::Result {
struct SignupEmail { let SignupEmail {
email: String, email,
} } = req.body_json().await?;
pub async fn submit(mut req: Request<State>) -> tide::Result { let config = &req.state().config;
let SignupEmail { let db = &req.state().db;
email,
} = req.body_json().await?;
let config = &req.state().config; for record in get_wolves_mail(db, &email).await {
let db = &req.state().db; // skynet emails not permitted
if record.email.trim().ends_with("@skynet.ie") {
for record in get_wolves_mail(db, &email).await { continue;
// skynet emails not permitted
if record.email.trim().ends_with("@skynet.ie") {
continue;
}
// check if the email is already in the db
if !check(db, &record.email).await {
continue;
}
// generate a auth key
let auth = random_string(75);
match send_mail(config, &record, &auth) {
Ok(_) => match save_to_db(db, &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);
}
}
} }
Ok(json!({"result": "success"}).into()) // check if the email is already in the db
if !check(db, &record.email).await {
continue;
}
// generate a auth key
let auth = random_string(75);
match send_mail(config, &record, &auth) {
Ok(_) => match save_to_db(db, &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);
}
}
} }
async fn get_wolves_mail(db: &Pool<Sqlite>, mail: &str) -> Vec<AccountWolves> { Ok(json!({"result": "success"}).into())
sqlx::query_as::<_, AccountWolves>( }
r#"
async fn get_wolves_mail(db: &Pool<Sqlite>, mail: &str) -> Vec<AccountWolves> {
sqlx::query_as::<_, AccountWolves>(
r#"
SELECT * SELECT *
FROM accounts_wolves FROM accounts_wolves
WHERE email = ? WHERE email = ?
"#, "#,
) )
.bind(mail) .bind(mail)
.fetch_all(db) .fetch_all(db)
.await .await
.unwrap_or(vec![]) .unwrap_or(vec![])
} }
async fn check(db: &Pool<Sqlite>, mail: &str) -> bool { async fn check(db: &Pool<Sqlite>, mail: &str) -> bool {
check_pending(db, mail).await && check_users(db, mail).await check_pending(db, mail).await && check_users(db, mail).await
} }
async fn check_users(db: &Pool<Sqlite>, mail: &str) -> bool { async fn check_users(db: &Pool<Sqlite>, mail: &str) -> bool {
sqlx::query_as::<_, Accounts>( sqlx::query_as::<_, Accounts>(
r#" r#"
SELECT * SELECT *
FROM accounts FROM accounts
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::<_, AccountsNew>( sqlx::query_as::<_, AccountsNew>(
r#" r#"
SELECT * SELECT *
FROM accounts_new FROM accounts_new
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()
} }
// using https://github.com/lettre/lettre/blob/57886c367d69b4d66300b322c94bd910b1eca364/examples/maud_html.rs // using https://github.com/lettre/lettre/blob/57886c367d69b4d66300b322c94bd910b1eca364/examples/maud_html.rs
fn send_mail(config: &Config, record: &AccountWolves, auth: &str) -> Result<lettre::transport::smtp::response::Response, lettre::transport::smtp::Error> { fn send_mail(config: &Config, record: &AccountWolves, auth: &str) -> Result<lettre::transport::smtp::response::Response, lettre::transport::smtp::Error> {
let recipient = &record.name_first; let recipient = &record.name_first;
let mail = &record.email; let mail = &record.email;
let url_base = "https://sso.skynet.ie"; let url_base = "https://sso.skynet.ie";
let link_new = format!("{url_base}/register?auth={auth}"); let link_new = format!("{url_base}/register?auth={auth}");
let link_mod = format!("{url_base}/modify"); let link_mod = format!("{url_base}/modify");
let discord = "https://discord.gg/mkuKJkCuyM"; let discord = "https://discord.gg/mkuKJkCuyM";
let sender = format!("UL Computer Society <{}>", &config.mail_user); let sender = format!("UL Computer Society <{}>", &config.mail_user);
// Create the html we want to send. // Create the html we want to send.
let html = html! { let html = html! {
head { head {
title { "Hello from Skynet!" } title { "Hello from Skynet!" }
style type="text/css" { style type="text/css" {
"h2, h4 { font-family: Arial, Helvetica, sans-serif; }" "h2, h4 { font-family: Arial, Helvetica, sans-serif; }"
}
} }
div style="display: flex; flex-direction: column; align-items: center;" { }
h2 { "Hello from Skynet!" } div style="display: flex; flex-direction: column; align-items: center;" {
// Substitute in the name of our recipient. h2 { "Hello from Skynet!" }
p { "Hi " (recipient) "," } // Substitute in the name of our recipient.
p { p { "Hi " (recipient) "," }
"As part of the UL Computer Society you get an account on our Skynet cluster." p {
br; "As part of the UL Computer Society you get an account on our Skynet cluster."
"This gives you access to some of teh various services we offer:" br;
ul { "This gives you access to some of teh various services we offer:"
li { "Email" } ul {
li { "Gitlab" } li { "Email" }
li { "Linux Webhost" } li { "Gitlab" }
} li { "Linux Webhost" }
br;
"The following invite will remain active until the end of year."
}
p {
"If you are a new member please use the following link:"
br;
a href=(link_new) { (link_new) }
}
p {
"If you are a returning user please set an email for your account at:"
br;
a href=(link_mod) { (link_mod) }
}
p {
"If you have issues please refer to our Discord server:"
br;
a href=(discord) { (discord) }
}
p {
"Skynet Team"
br;
"UL Computer Society"
} }
br;
"The following invite will remain active until the end of year."
}
p {
"If you are a new member please use the following link:"
br;
a href=(link_new) { (link_new) }
}
p {
"If you are a returning user please set an email for your account at:"
br;
a href=(link_mod) { (link_mod) }
}
p {
"If you have issues please refer to our Discord server:"
br;
a href=(discord) { (discord) }
} }
};
let body_text = format!( p {
r#" "Skynet Team"
br;
"UL Computer Society"
}
}
};
let body_text = format!(
r#"
Hi {recipient} Hi {recipient}
As part of the UL Computer Society you get an account on our Skynet cluster. As part of the UL Computer Society you get an account on our Skynet cluster.
@ -189,270 +186,269 @@ pub mod post {
Skynet Team Skynet Team
UL Computer Society UL Computer Society
"# "#
); );
// 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::builder().header(header::ContentType::TEXT_PLAIN).body(body_text)) .singlepart(SinglePart::builder().header(header::ContentType::TEXT_PLAIN).body(body_text))
.singlepart(SinglePart::builder().header(header::ContentType::TEXT_HTML).body(html.into_string())), .singlepart(SinglePart::builder().header(header::ContentType::TEXT_HTML).body(html.into_string())),
) )
.expect("failed to build email"); .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).unwrap().credentials(creds).build(); let mailer = SmtpTransport::starttls_relay(&config.mail_smtp).unwrap().credentials(creds).build();
// Send the email // Send the email
mailer.send(&email) mailer.send(&email)
} }
async fn save_to_db(db: &Pool<Sqlite>, record: &AccountWolves, auth: &str) -> Result<Option<AccountsNew>, sqlx::Error> { async fn save_to_db(db: &Pool<Sqlite>, record: &AccountWolves, 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, id_student) INSERT OR REPLACE INTO accounts_new (mail, auth_code, date_iso, date_expiry, name_first, name_surname, id_student)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)
", ",
) )
.bind(record.email.to_owned()) .bind(record.email.to_owned())
.bind(auth.to_owned()) .bind(auth.to_owned())
.bind(get_now_iso(false)) .bind(get_now_iso(false))
.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())
.bind(record.id_student.to_owned()) .bind(record.id_student.to_owned())
.fetch_optional(db) .fetch_optional(db)
.await .await
} }
}
pub mod account {
use super::*;
#[derive(Debug, Deserialize)]
struct LdapNewUser {
auth: String,
user: String,
pass: String,
} }
pub mod account { /// Handles initial detail entering page
use super::*; /// Verify users have access to said email
/// Get users to set username and password.
pub async fn submit(mut req: Request<State>) -> tide::Result {
let LdapNewUser {
auth,
user,
pass,
} = req.body_json().await?;
#[derive(Debug, Deserialize)] let config = &req.state().config;
struct LdapNewUser { let db = &req.state().db;
auth: String,
user: String, // ensure there are no old requests
pass: String, db_pending_clear_expired(db).await?;
let user_db = if let Some(x) = db_get_user(db, &auth).await {
x
} else {
return Ok(json!({"result": "error", "error": "Invalid auth"}).into());
};
if let Some(error) = is_valid_name(&user) {
return Ok(json!({"result": "error", "error": error}).into());
} }
/// Handles initial detail entering page // easier to give each request its own connection
/// Verify users have access to said email let mut ldap = LdapConn::new(&config.ldap_host)?;
/// Get users to set username and password.
pub async fn submit(mut req: Request<State>) -> tide::Result {
let LdapNewUser {
auth,
user,
pass,
} = req.body_json().await?;
let config = &req.state().config; // ldap3 docs say a blank username and pass is an anon bind
let db = &req.state().db; ldap.simple_bind("", "")?.success()?;
// ensure there are no old requests let filter_dn = format!("(uid={})", &user);
db_pending_clear_expired(db).await?; if let Ok(x) = ldap.search("ou=users,dc=skynet,dc=ie", Scope::OneLevel, &filter_dn, vec!["*"]) {
if let Ok((rs, _res)) = x.success() {
let user_db = if let Some(x) = db_get_user(db, &auth).await { if !rs.is_empty() {
x return Ok(json!({"result": "error", "error": "username not available"}).into());
} else {
return Ok(json!({"result": "error", "error": "Invalid auth"}).into());
};
if let Some(error) = is_valid_name(&user) {
return Ok(json!({"result": "error", "error": error}).into());
}
// easier to give each request its own connection
let mut ldap = LdapConn::new(&config.ldap_host)?;
// ldap3 docs say a blank username and pass is an anon bind
ldap.simple_bind("", "")?.success()?;
let filter_dn = format!("(uid={})", &user);
if let Ok(x) = ldap.search("ou=users,dc=skynet,dc=ie", Scope::OneLevel, &filter_dn, vec!["*"]) {
if let Ok((rs, _res)) = x.success() {
if !rs.is_empty() {
return Ok(json!({"result": "error", "error": "username not available"}).into());
}
} }
} }
// done with anon ldap
ldap.unbind()?;
ldap_create_account(config, db, user_db, &user, &pass).await?;
// account now created, delete from the new table
account_verification_clear_pending(db, &auth).await?;
Ok(json!({"result": "success"}).into())
} }
// clear the db of expired ones before checking for username and validating inputs // done with anon ldap
async fn db_pending_clear_expired(pool: &Pool<Sqlite>) -> Result<Vec<AccountsNew>, Error> { ldap.unbind()?;
sqlx::query_as::<_, AccountsNew>(
r#" ldap_create_account(config, db, user_db, &user, &pass).await?;
// account now created, delete from the new table
account_verification_clear_pending(db, &auth).await?;
Ok(json!({"result": "success"}).into())
}
// clear the db of expired ones before checking for username and validating inputs
async fn db_pending_clear_expired(pool: &Pool<Sqlite>) -> Result<Vec<AccountsNew>, Error> {
sqlx::query_as::<_, AccountsNew>(
r#"
DELETE DELETE
FROM accounts_new FROM accounts_new
WHERE date_expiry < ? WHERE date_expiry < ?
"#, "#,
) )
.bind(get_now_iso(true)) .bind(get_now_iso(true))
.fetch_all(pool) .fetch_all(pool)
.await .await
}
fn is_valid_name(name: &str) -> Option<String> {
// max length is 31 chars
if name.len() >= 32 {
return Some(String::from("Too long, max len 31"));
} }
fn is_valid_name(name: &str) -> Option<String> { for (index, letter) in name.chars().enumerate() {
// max length is 31 chars // no uppercase characters allowed
if name.len() >= 32 { if letter.is_ascii_uppercase() {
return Some(String::from("Too long, max len 31")); return Some(String::from("Has uppercase"));
} }
for (index, letter) in name.chars().enumerate() { if index == 0 {
// no uppercase characters allowed // first character ahs to be either a letter or underscore
if letter.is_ascii_uppercase() { if !(letter.is_ascii_alphabetic() || letter == '_') {
return Some(String::from("Has uppercase")); return Some(String::from("Does not start with letter or _"));
} }
} else {
if index == 0 { // after first character options are more relaxed
// first character ahs to be either a letter or underscore if !(letter.is_ascii_alphabetic() || letter.is_ascii_digit() || letter == '_' || letter == '-') {
if !(letter.is_ascii_alphabetic() || letter == '_') { return Some(String::from("Contains character that is not letter, number, _ or -"));
return Some(String::from("Does not start with letter or _"));
}
} else {
// after first character options are more relaxed
if !(letter.is_ascii_alphabetic() || letter.is_ascii_digit() || letter == '_' || letter == '-') {
return Some(String::from("Contains character that is not letter, number, _ or -"));
}
} }
} }
None
} }
async fn db_get_user(pool: &Pool<Sqlite>, auth: &str) -> Option<AccountsNew> { None
if let Ok(res) = sqlx::query_as::<_, AccountsNew>( }
r#"
async fn db_get_user(pool: &Pool<Sqlite>, auth: &str) -> Option<AccountsNew> {
if let Ok(res) = sqlx::query_as::<_, AccountsNew>(
r#"
SELECT * SELECT *
FROM accounts_new FROM accounts_new
WHERE auth_code == ? WHERE auth_code == ?
"#, "#,
) )
.bind(auth) .bind(auth)
.fetch_all(pool) .fetch_all(pool)
.await .await
{ {
if !res.is_empty() { if !res.is_empty() {
return Some(res[0].to_owned()); return Some(res[0].to_owned());
}
} }
None
} }
async fn ldap_create_account(config: &Config, db: &Pool<Sqlite>, user: AccountsNew, username: &str, pass: &str) -> Result<(), ldap3::LdapError> { None
let mut ldap = LdapConn::new(&config.ldap_host)?; }
ldap.simple_bind(&config.ldap_admin, &config.ldap_admin_pw)?.success()?;
let dn = format!("uid={},ou=users,dc=skynet,dc=ie", username); async fn ldap_create_account(config: &Config, db: &Pool<Sqlite>, user: AccountsNew, username: &str, pass: &str) -> Result<(), ldap3::LdapError> {
let cn = format!("{} {}", &user.name_first, &user.name_surname); let mut ldap = LdapConn::new(&config.ldap_host)?;
let home_directory = format!("/home/{}", username); ldap.simple_bind(&config.ldap_admin, &config.ldap_admin_pw)?.success()?;
let password_tmp = random_string(50);
let labeled_uri = format!("ldap:///ou=groups,dc=skynet,dc=ie??sub?(&(objectclass=posixgroup)(memberuid={}))", username);
let sk_mail = format!("{}@skynet.ie", username);
let sk_created = get_sk_created();
let uid_number = get_max_uid_number(db).await;
// create user let dn = format!("uid={},ou=users,dc=skynet,dc=ie", username);
ldap.add( let cn = format!("{} {}", &user.name_first, &user.name_surname);
&dn, let home_directory = format!("/home/{}", username);
vec![ let password_tmp = random_string(50);
("objectClass", HashSet::from(["top", "person", "posixaccount", "ldapPublicKey", "inetOrgPerson", "skPerson"])), let labeled_uri = format!("ldap:///ou=groups,dc=skynet,dc=ie??sub?(&(objectclass=posixgroup)(memberuid={}))", username);
// top let sk_mail = format!("{}@skynet.ie", username);
("ou", HashSet::from(["users"])), let sk_created = get_sk_created();
// person let uid_number = get_max_uid_number(db).await;
("uid", HashSet::from([username])),
("cn", HashSet::from([cn.as_str()])),
// posixaccount
("uidNumber", HashSet::from([uid_number.to_string().as_str()])),
("gidNumber", HashSet::from(["1001"])),
("homedirectory", HashSet::from([home_directory.as_str()])),
("userpassword", HashSet::from([password_tmp.as_str()])),
// inetOrgPerson
("mail", HashSet::from([user.mail.as_str()])),
("sn", HashSet::from([user.name_surname.as_str()])),
// skPerson
("labeledURI", HashSet::from([labeled_uri.as_str()])),
("skMail", HashSet::from([sk_mail.as_str()])),
("skID", HashSet::from([user.id_student.as_str()])),
("skCreated", HashSet::from([sk_created.as_str()])),
// 1 = secure, automatic since its a new account
("skSecure", HashSet::from(["1"])),
// quotas
("quotaEmail", HashSet::from(["10737418240"])),
("quotaDisk", HashSet::from(["10737418240"])),
],
)?
.success()?;
// now to properly set teh password // create user
let tmp = PasswordModify { ldap.add(
user_id: Some(&dn), &dn,
old_pass: None, vec![
new_pass: Some(pass), ("objectClass", HashSet::from(["top", "person", "posixaccount", "ldapPublicKey", "inetOrgPerson", "skPerson"])),
}; // top
("ou", HashSet::from(["users"])),
// person
("uid", HashSet::from([username])),
("cn", HashSet::from([cn.as_str()])),
// posixaccount
("uidNumber", HashSet::from([uid_number.to_string().as_str()])),
("gidNumber", HashSet::from(["1001"])),
("homedirectory", HashSet::from([home_directory.as_str()])),
("userpassword", HashSet::from([password_tmp.as_str()])),
// inetOrgPerson
("mail", HashSet::from([user.mail.as_str()])),
("sn", HashSet::from([user.name_surname.as_str()])),
// skPerson
("labeledURI", HashSet::from([labeled_uri.as_str()])),
("skMail", HashSet::from([sk_mail.as_str()])),
("skID", HashSet::from([user.id_student.as_str()])),
("skCreated", HashSet::from([sk_created.as_str()])),
// 1 = secure, automatic since its a new account
("skSecure", HashSet::from(["1"])),
// quotas
("quotaEmail", HashSet::from(["10737418240"])),
("quotaDisk", HashSet::from(["10737418240"])),
],
)?
.success()?;
ldap.extended(tmp).unwrap(); // now to properly set teh password
let tmp = PasswordModify {
user_id: Some(&dn),
old_pass: None,
new_pass: Some(pass),
};
ldap.unbind()?; ldap.extended(tmp).unwrap();
Ok(()) ldap.unbind()?;
}
fn get_sk_created() -> String { Ok(())
use chrono::Utc; }
let now = Utc::now();
format!("{}", now.format("%Y%m%d%H%M%SZ")) fn get_sk_created() -> String {
} use chrono::Utc;
let now = Utc::now();
async fn get_max_uid_number(db: &Pool<Sqlite>) -> i64 { format!("{}", now.format("%Y%m%d%H%M%SZ"))
if let Ok(results) = sqlx::query_as::<_, Accounts>( }
r#"
async fn get_max_uid_number(db: &Pool<Sqlite>) -> i64 {
if let Ok(results) = sqlx::query_as::<_, Accounts>(
r#"
SELECT * SELECT *
FROM accounts FROM accounts
ORDER BY uid DESC ORDER BY uid DESC
LIMIT 1 LIMIT 1
"#, "#,
) )
.fetch_all(db) .fetch_all(db)
.await .await
{ {
if !results.is_empty() { if !results.is_empty() {
return results[0].uid + 1; return results[0].uid + 1;
}
} }
9999
} }
async fn account_verification_clear_pending(db: &Pool<Sqlite>, auth_code: &str) -> Result<Vec<AccountsNew>, Error> { 9999
sqlx::query_as::<_, AccountsNew>( }
r#"
async fn account_verification_clear_pending(db: &Pool<Sqlite>, auth_code: &str) -> Result<Vec<AccountsNew>, Error> {
sqlx::query_as::<_, AccountsNew>(
r#"
DELETE FROM accounts_new DELETE FROM accounts_new
WHERE auth_code == ? WHERE auth_code == ?
"#, "#,
) )
.bind(auth_code) .bind(auth_code)
.fetch_all(db) .fetch_all(db)
.await .await
}
} }
} }

View file

@ -25,7 +25,7 @@ pub struct ModifyResult {
} }
/// Handles updating a single field with the users own password /// Handles updating a single field with the users own password
pub async fn post_update_ldap(mut req: Request<State>) -> tide::Result { pub async fn submit(mut req: Request<State>) -> tide::Result {
let LdapUpdate { let LdapUpdate {
user, user,
pass, pass,