fmt: split the new account creation into several sub functions, will be re using a few for the email password reset

This commit is contained in:
silver 2023-06-04 23:42:09 +01:00
parent c11b520c77
commit 57e07d49a7
2 changed files with 109 additions and 84 deletions

View file

@ -12,9 +12,12 @@ use tide::prelude::*;
pub struct AccountsPending { pub struct AccountsPending {
user: String, user: String,
mail: String, mail: String,
name_first: String, cn: String,
name_second: String, sn: String,
auth_code: String, auth_code: String,
// action will be what to do with it
action: String,
// will only last for a few hours // will only last for a few hours
expiry: i64, expiry: i64,
} }
@ -38,8 +41,9 @@ pub async fn db_init(config: &Config) -> Result<Pool<Sqlite>, Error> {
"CREATE TABLE IF NOT EXISTS accounts_pending ( "CREATE TABLE IF NOT EXISTS accounts_pending (
user text primary key, user text primary key,
mail text not null, mail text not null,
name_first text not null, cn text not null,
name_second text not null, sn text not null,
action text not null,
auth_code text not null, auth_code text not null,
expiry integer not null expiry integer not null
)", )",

View file

@ -1,7 +1,8 @@
use crate::{get_now, Accounts, AccountsPending, State}; use crate::{get_now, Accounts, AccountsPending, State};
use ldap3::exop::PasswordModify; use ldap3::exop::PasswordModify;
use ldap3::result::ExopResult;
use ldap3::{LdapConn, Scope}; use ldap3::{LdapConn, Scope};
use sqlx::{Pool, Sqlite}; use sqlx::{Error, Pool, Sqlite};
use std::collections::HashSet; use std::collections::HashSet;
use tide::prelude::{json, Deserialize}; use tide::prelude::{json, Deserialize};
use tide::Request; use tide::Request;
@ -67,7 +68,7 @@ pub async fn post_new_account(mut req: Request<State>) -> tide::Result {
// setup the pool, going to need it for the rest of it // setup the pool, going to need it for the rest of it
let pool = &req.state().db; let pool = &req.state().db;
db_pending_clear_expired(pool).await; db_pending_clear_expired(pool).await?;
// now check local // now check local
if let Ok(results) = sqlx::query_as::<_, AccountsPending>( if let Ok(results) = sqlx::query_as::<_, AccountsPending>(
@ -112,21 +113,22 @@ pub async fn post_new_account(mut req: Request<State>) -> tide::Result {
if not generate tuhe user and send email if not generate tuhe user and send email
*/ */
let cn = format!("{} {}", name_first, name_second);
let auth_code = create_random_string(50); let auth_code = create_random_string(50);
// 1 hour expiry // 1 hour expiry
let expiry = get_now() + (60 * 60); let expiry = get_now() + (60 * 60);
sqlx::query_as::<_, AccountsPending>( sqlx::query_as::<_, AccountsPending>(
r#" r#"
INSERT OR REPLACE INTO accounts_pending (user, mail, name_first, name_second, auth_code, expiry) INSERT OR REPLACE INTO accounts_pending (user, mail, cn, sn, action, auth_code, expiry)
VALUES (?1, ?2, ?3, ?4, ?5, ?6) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)
"#, "#,
) )
.bind(&user) .bind(&user)
.bind(&mail) .bind(&mail)
.bind(&name_first) .bind(&cn)
.bind(&name_second) .bind(&name_second)
.bind("account_new")
.bind(&auth_code) .bind(&auth_code)
.bind(expiry) .bind(expiry)
.fetch_optional(pool) .fetch_optional(pool)
@ -139,9 +141,9 @@ pub async fn post_new_account(mut req: Request<State>) -> tide::Result {
} }
// clear the db of expired ones before checking for username and validating inputs // clear the db of expired ones before checking for username and validating inputs
async fn db_pending_clear_expired(pool: &Pool<Sqlite>) { async fn db_pending_clear_expired(pool: &Pool<Sqlite>) -> Result<Vec<AccountsPending>, Error> {
let now = get_now(); let now = get_now();
if let Ok(results) = sqlx::query_as::<_, AccountsPending>( sqlx::query_as::<_, AccountsPending>(
r#" r#"
DELETE DELETE
FROM accounts_pending FROM accounts_pending
@ -151,9 +153,6 @@ async fn db_pending_clear_expired(pool: &Pool<Sqlite>) {
.bind(now) .bind(now)
.fetch_all(pool) .fetch_all(pool)
.await .await
{
println!("{:?}", results)
}
} }
fn create_random_string(length: usize) -> String { fn create_random_string(length: usize) -> String {
@ -164,17 +163,14 @@ fn create_random_string(length: usize) -> String {
} }
#[derive(Debug, Deserialize)] #[derive(Debug, Deserialize)]
pub struct LdapNewUserVerify { pub struct LdapUserVerify {
auth_code: String, auth_code: String,
password: String, password: String,
} }
/// Handles the verification that a user has access to the email /// Handles the verification that a user has access to the email
pub async fn post_new_account_confirmation(mut req: Request<State>) -> tide::Result { pub async fn post_new_account_confirmation(mut req: Request<State>) -> tide::Result {
let LdapNewUserVerify { let user_verify: LdapUserVerify = req.body_json().await?;
auth_code,
password,
} = req.body_json().await?;
let State { let State {
db, db,
@ -182,43 +178,96 @@ pub async fn post_new_account_confirmation(mut req: Request<State>) -> tide::Res
.. ..
} = &req.state(); } = &req.state();
// setup ldap connection
let mut ldap = LdapConn::new(&config.ldap_host)?;
ldap.simple_bind(&config.ldap_admin, &config.ldap_admin_pw)?.success()?;
// make sure to clear out the expired ones first // make sure to clear out the expired ones first
db_pending_clear_expired(db).await; db_pending_clear_expired(db).await?;
// search db for auth_code // search db for auth_code
let results = sqlx::query_as::<_, AccountsPending>( let results = account_verification_find_pending(db, "account_new", &user_verify.auth_code).await;
r#"
SELECT *
FROM accounts_pending
WHERE auth_code == ?
"#,
)
.bind(&auth_code)
.fetch_all(db)
.await
.unwrap_or(vec![]);
if results.is_empty() { if results.is_empty() {
return Ok(json!({"result": "error"}).into()); return Ok(json!({"result": "error"}).into());
} }
let mut ldap = LdapConn::new(&config.ldap_host)?; let user_details = &results[0];
let uid_number = get_max_uid_number(db).await;
// need to bind as admin // create teh new user account in ldap
ldap.simple_bind(&config.ldap_admin, &config.ldap_admin_pw)?.success()?; account_verification_new_account(&mut ldap, user_details, uid_number).await?;
// now to properly set teh password
account_verification_reset_password_admin(&mut ldap, &user_details.user, &user_verify.password)?;
// done with ldap
ldap.unbind()?;
// delete from tmp db
account_verification_clear_pending(db, &user_verify.auth_code).await?;
// add new users to teh local database
account_verification_add_local(db, &user_details.user, uid_number).await?;
// frontend tells user that initial password ahs been sent to tehm
Ok(json!({"result": "success"}).into())
}
fn get_sk_created() -> String {
use chrono::Utc;
let now = Utc::now();
format!("{}", now.format("%Y%m%d%H%M%SZ"))
}
async fn get_max_uid_number(db: &Pool<Sqlite>) -> i64 {
if let Ok(results) = sqlx::query_as::<_, Accounts>(
r#"
SELECT *
FROM accounts
ORDER BY uid_number DESC
LIMIT 1
"#,
)
.fetch_all(db)
.await
{
if !results.is_empty() {
return results[0].uid_number + 1;
}
}
9999
}
async fn account_verification_find_pending(db: &Pool<Sqlite>, action: &str, auth_code: &str) -> Vec<AccountsPending> {
sqlx::query_as::<_, AccountsPending>(
r#"
SELECT *
FROM accounts_pending
WHERE auth_code == ? AND action == ?
"#,
)
.bind(auth_code)
.bind(action)
.fetch_all(db)
.await
.unwrap_or(vec![])
}
async fn account_verification_new_account(ldap: &mut LdapConn, user_details: &AccountsPending, uid_number: i64) -> Result<(), ldap3::LdapError> {
let AccountsPending { let AccountsPending {
user, user,
mail, mail,
name_first, cn,
name_second, sn,
.. ..
} = &results[0]; } = user_details;
let dn = format!("uid={},ou=users,dc=skynet,dc=ie", user); let dn = format!("uid={},ou=users,dc=skynet,dc=ie", user);
let uid_number = get_max_uid_number(db).await;
let home_directory = format!("/home/{}", user); let home_directory = format!("/home/{}", user);
let password_tmp = create_random_string(50); let password_tmp = create_random_string(50);
let cn = format!("{} {}", name_first, name_second);
let labeled_uri = format!("ldap:///ou=groups,dc=skynet,dc=ie??sub?(&(objectclass=posixgroup)(memberuid={}))", user); let labeled_uri = format!("ldap:///ou=groups,dc=skynet,dc=ie??sub?(&(objectclass=posixgroup)(memberuid={}))", user);
let sk_mail = format!("{}@skynet.ie", user); let sk_mail = format!("{}@skynet.ie", user);
let sk_created = get_sk_created(); let sk_created = get_sk_created();
@ -240,7 +289,7 @@ pub async fn post_new_account_confirmation(mut req: Request<State>) -> tide::Res
("userpassword", HashSet::from([password_tmp.as_str()])), ("userpassword", HashSet::from([password_tmp.as_str()])),
// inetOrgPerson // inetOrgPerson
("mail", HashSet::from([mail.as_str()])), ("mail", HashSet::from([mail.as_str()])),
("sn", HashSet::from([name_second.as_str()])), ("sn", HashSet::from([sn.as_str()])),
// skPerson // skPerson
("labeledURI", HashSet::from([labeled_uri.as_str()])), ("labeledURI", HashSet::from([labeled_uri.as_str()])),
("skMail", HashSet::from([sk_mail.as_str()])), ("skMail", HashSet::from([sk_mail.as_str()])),
@ -251,32 +300,35 @@ pub async fn post_new_account_confirmation(mut req: Request<State>) -> tide::Res
)? )?
.success()?; .success()?;
Ok(())
}
fn account_verification_reset_password_admin(ldap: &mut LdapConn, user: &str, pass: &str) -> Result<ExopResult, ldap3::LdapError> {
let dn = format!("uid={},ou=users,dc=skynet,dc=ie", user);
// now to properly set teh password // now to properly set teh password
let tmp = PasswordModify { let tmp = PasswordModify {
user_id: Some(&dn), user_id: Some(&dn),
old_pass: Some(&password_tmp), old_pass: None,
new_pass: Some(&password), new_pass: Some(pass),
}; };
ldap.extended(tmp)?.success()?;
// done with ldap ldap.extended(tmp)
ldap.unbind()?; }
// delete from tmp db async fn account_verification_clear_pending(db: &Pool<Sqlite>, auth_code: &str) -> Result<Vec<AccountsPending>, Error> {
if let Ok(results) = sqlx::query_as::<_, AccountsPending>( sqlx::query_as::<_, AccountsPending>(
r#" r#"
DELETE FROM accounts_pending DELETE FROM accounts_pending
WHERE auth_code == ? WHERE auth_code == ?
"#, "#,
) )
.bind(&auth_code) .bind(auth_code)
.fetch_all(db) .fetch_all(db)
.await .await
{ }
println!("{:?}", results)
}
// add new users to teh local database async fn account_verification_add_local(db: &Pool<Sqlite>, user: &str, uid_number: i64) -> Result<Option<Accounts>, Error> {
sqlx::query_as::<_, Accounts>( sqlx::query_as::<_, Accounts>(
" "
INSERT OR REPLACE INTO accounts (user, uid_number, enabled) INSERT OR REPLACE INTO accounts (user, uid_number, enabled)
@ -288,35 +340,4 @@ pub async fn post_new_account_confirmation(mut req: Request<State>) -> tide::Res
.bind(false) .bind(false)
.fetch_optional(db) .fetch_optional(db)
.await .await
.ok();
// frontend tells user that initial password ahs been sent to tehm
Ok(json!({"result": "success"}).into())
}
fn get_sk_created() -> String {
use chrono::Utc;
let now = Utc::now();
format!("{}", now.format("%Y%m%d%H%M%SZ"))
}
pub async fn get_max_uid_number(db: &Pool<Sqlite>) -> i64 {
if let Ok(results) = sqlx::query_as::<_, Accounts>(
r#"
SELECT *
FROM accounts
ORDER BY uid_number DESC
LIMIT 1
"#,
)
.fetch_all(db)
.await
{
if !results.is_empty() {
return results[0].uid_number + 1;
}
}
9999
} }