ldap_backend/src/methods/account_update.rs

87 lines
2.6 KiB
Rust
Raw Normal View History

use crate::State;
2023-07-30 02:50:13 +01:00
use ldap3::{exop::PasswordModify, LdapConn, Mod, Scope, SearchEntry};
use std::collections::HashSet;
2023-07-30 02:50:13 +01:00
use tide::{
prelude::{json, Deserialize},
Request,
};
#[derive(Debug, Deserialize)]
pub struct LdapUpdate {
user: String,
pass: String,
field: String,
value: String,
}
2023-06-04 12:19:17 +01:00
/// Handles updating a single field with the users own password
pub async fn post_update_ldap(mut req: Request<State>) -> tide::Result {
let LdapUpdate {
user,
pass,
field,
value,
} = req.body_json().await?;
// check that any mail is not using @skynet.ie
if field == "mail" && value.trim().ends_with("@skynet.ie") {
return Ok(json!({"result": "error", "error": "skynet email not valid contact address"}).into());
}
let config = &req.state().config;
// easier to give each request its own connection
let mut ldap = LdapConn::new(&config.ldap_host)?;
let dn = format!("uid={},ou=users,dc=skynet,dc=ie", user);
ldap.simple_bind(&dn, &pass)?.success()?;
// always assume insecure
let mut pw_keep_same = false;
// get the users current password hash
let (rs, _res) = ldap.search(&dn, Scope::Base, "(objectClass=*)", vec!["userPassword"])?.success()?;
if !rs.is_empty() {
let tmp = SearchEntry::construct(rs[0].clone());
if !tmp.attrs["userPassword"].is_empty() && tmp.attrs["userPassword"][0].starts_with("{SSHA512}") {
pw_keep_same = true;
}
}
// check if the password field itself is being updated
let pass_new = if &field != "userPassword" {
// if password is not being updated then just update the required field
let mods = vec![
// the value we are updating
Mod::Replace(field, HashSet::from([value])),
];
2023-07-17 00:14:48 +01:00
ldap.modify(&dn, mods)?.success()?;
// pass back the "old" and "new" passwords
// using this means we can create teh vars without them needing to be mutable
pass.clone()
} else {
// password is going to be updated, even if the old value is not starting with "{SSHA512}"
pw_keep_same = false;
value
};
// changing teh password because of an explicit request or upgrading teh security.
if !pw_keep_same {
// really easy to update password once ye know how
let tmp = PasswordModify {
// none as we are staying on the same connection
user_id: None,
old_pass: Some(&pass),
new_pass: Some(&pass_new),
};
ldap.extended(tmp)?.success()?;
};
ldap.unbind()?;
Ok(json!({"result": "success"}).into())
}