#11 signup email #36
2 changed files with 186 additions and 178 deletions
|
@ -1,6 +1,9 @@
|
||||||
use skynet_ldap_backend::{
|
use skynet_ldap_backend::{
|
||||||
db_init, get_config,
|
db_init, get_config,
|
||||||
methods::{account_new::post_new_account, account_update::post_update_ldap},
|
methods::{
|
||||||
|
account_new::post::{account, email},
|
||||||
|
account_update::post_update_ldap,
|
||||||
|
},
|
||||||
State,
|
State,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -21,7 +24,8 @@ 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(post_update_ldap);
|
||||||
app.at("/ldap/new").post(post_new_account);
|
app.at("/ldap/new/email").post(email::submit);
|
||||||
|
app.at("/ldap/new/account").post(account::submit);
|
||||||
|
|
||||||
app.listen(host_port).await?;
|
app.listen(host_port).await?;
|
||||||
Ok(())
|
Ok(())
|
||||||
|
|
|
@ -232,223 +232,227 @@ pub mod post {
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
pub mod account {
|
||||||
struct LdapNewUser {
|
use super::*;
|
||||||
auth: String,
|
|
||||||
user: String,
|
|
||||||
pass: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Handles initial detail entering page
|
#[derive(Debug, Deserialize)]
|
||||||
/// Verify users have access to said email
|
struct LdapNewUser {
|
||||||
/// Get users to set username and password.
|
auth: String,
|
||||||
pub async fn post_new_account(mut req: Request<State>) -> tide::Result {
|
user: String,
|
||||||
let LdapNewUser {
|
pass: String,
|
||||||
auth,
|
|
||||||
user,
|
|
||||||
pass,
|
|
||||||
} = req.body_json().await?;
|
|
||||||
|
|
||||||
let config = &req.state().config;
|
|
||||||
let db = &req.state().db;
|
|
||||||
|
|
||||||
// ensure there are no old requests
|
|
||||||
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());
|
|
||||||
}
|
|
||||||
|
|
||||||
// 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
|
/// Handles initial detail entering page
|
||||||
ldap.unbind()?;
|
/// 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?;
|
||||||
|
|
||||||
ldap_create_account(config, db, user_db, &user, &pass).await?;
|
let config = &req.state().config;
|
||||||
|
let db = &req.state().db;
|
||||||
|
|
||||||
// account now created, delete from the new table
|
// ensure there are no old requests
|
||||||
account_verification_clear_pending(db, &auth).await?;
|
db_pending_clear_expired(db).await?;
|
||||||
|
|
||||||
Ok(json!({"result": "success"}).into())
|
let user_db = if let Some(x) = db_get_user(db, &auth).await {
|
||||||
}
|
x
|
||||||
|
} else {
|
||||||
|
return Ok(json!({"result": "error", "error": "Invalid auth"}).into());
|
||||||
|
};
|
||||||
|
|
||||||
// clear the db of expired ones before checking for username and validating inputs
|
if let Some(error) = is_valid_name(&user) {
|
||||||
async fn db_pending_clear_expired(pool: &Pool<Sqlite>) -> Result<Vec<AccountsNew>, Error> {
|
return Ok(json!({"result": "error", "error": error}).into());
|
||||||
sqlx::query_as::<_, AccountsNew>(
|
}
|
||||||
r#"
|
|
||||||
|
// 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
|
||||||
|
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"));
|
|
||||||
}
|
|
||||||
|
|
||||||
for (index, letter) in name.chars().enumerate() {
|
|
||||||
// no uppercase characters allowed
|
|
||||||
if letter.is_ascii_uppercase() {
|
|
||||||
return Some(String::from("Has uppercase"));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if index == 0 {
|
fn is_valid_name(name: &str) -> Option<String> {
|
||||||
// first character ahs to be either a letter or underscore
|
// max length is 31 chars
|
||||||
if !(letter.is_ascii_alphabetic() || letter == '_') {
|
if name.len() >= 32 {
|
||||||
return Some(String::from("Does not start with letter or _"));
|
return Some(String::from("Too long, max len 31"));
|
||||||
}
|
}
|
||||||
} else {
|
|
||||||
// after first character options are more relaxed
|
for (index, letter) in name.chars().enumerate() {
|
||||||
if !(letter.is_ascii_alphabetic() || letter.is_ascii_digit() || letter == '_' || letter == '-') {
|
// no uppercase characters allowed
|
||||||
return Some(String::from("Contains character that is not letter, number, _ or -"));
|
if letter.is_ascii_uppercase() {
|
||||||
|
return Some(String::from("Has uppercase"));
|
||||||
|
}
|
||||||
|
|
||||||
|
if index == 0 {
|
||||||
|
// first character ahs to be either a letter or underscore
|
||||||
|
if !(letter.is_ascii_alphabetic() || letter == '_') {
|
||||||
|
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
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
None
|
async fn db_get_user(pool: &Pool<Sqlite>, auth: &str) -> Option<AccountsNew> {
|
||||||
}
|
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
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
None
|
async fn ldap_create_account(config: &Config, db: &Pool<Sqlite>, user: AccountsNew, username: &str, pass: &str) -> Result<(), ldap3::LdapError> {
|
||||||
}
|
let mut ldap = LdapConn::new(&config.ldap_host)?;
|
||||||
|
ldap.simple_bind(&config.ldap_admin, &config.ldap_admin_pw)?.success()?;
|
||||||
|
|
||||||
async fn ldap_create_account(config: &Config, db: &Pool<Sqlite>, user: AccountsNew, username: &str, pass: &str) -> Result<(), ldap3::LdapError> {
|
let dn = format!("uid={},ou=users,dc=skynet,dc=ie", username);
|
||||||
let mut ldap = LdapConn::new(&config.ldap_host)?;
|
let cn = format!("{} {}", &user.name_first, &user.name_surname);
|
||||||
ldap.simple_bind(&config.ldap_admin, &config.ldap_admin_pw)?.success()?;
|
let home_directory = format!("/home/{}", username);
|
||||||
|
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;
|
||||||
|
|
||||||
let dn = format!("uid={},ou=users,dc=skynet,dc=ie", username);
|
// create user
|
||||||
let cn = format!("{} {}", &user.name_first, &user.name_surname);
|
ldap.add(
|
||||||
let home_directory = format!("/home/{}", username);
|
&dn,
|
||||||
let password_tmp = random_string(50);
|
vec![
|
||||||
let labeled_uri = format!("ldap:///ou=groups,dc=skynet,dc=ie??sub?(&(objectclass=posixgroup)(memberuid={}))", username);
|
("objectClass", HashSet::from(["top", "person", "posixaccount", "ldapPublicKey", "inetOrgPerson", "skPerson"])),
|
||||||
let sk_mail = format!("{}@skynet.ie", username);
|
// top
|
||||||
let sk_created = get_sk_created();
|
("ou", HashSet::from(["users"])),
|
||||||
let uid_number = get_max_uid_number(db).await;
|
// 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()?;
|
||||||
|
|
||||||
// create user
|
// now to properly set teh password
|
||||||
ldap.add(
|
let tmp = PasswordModify {
|
||||||
&dn,
|
user_id: Some(&dn),
|
||||||
vec![
|
old_pass: None,
|
||||||
("objectClass", HashSet::from(["top", "person", "posixaccount", "ldapPublicKey", "inetOrgPerson", "skPerson"])),
|
new_pass: Some(pass),
|
||||||
// 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()?;
|
|
||||||
|
|
||||||
// now to properly set teh password
|
ldap.extended(tmp).unwrap();
|
||||||
let tmp = PasswordModify {
|
|
||||||
user_id: Some(&dn),
|
|
||||||
old_pass: None,
|
|
||||||
new_pass: Some(pass),
|
|
||||||
};
|
|
||||||
|
|
||||||
ldap.extended(tmp).unwrap();
|
ldap.unbind()?;
|
||||||
|
|
||||||
ldap.unbind()?;
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
Ok(())
|
fn get_sk_created() -> String {
|
||||||
}
|
use chrono::Utc;
|
||||||
|
let now = Utc::now();
|
||||||
|
|
||||||
fn get_sk_created() -> String {
|
format!("{}", now.format("%Y%m%d%H%M%SZ"))
|
||||||
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#"
|
||||||
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
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
9999
|
async fn account_verification_clear_pending(db: &Pool<Sqlite>, auth_code: &str) -> Result<Vec<AccountsNew>, Error> {
|
||||||
}
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in a new issue