ldap.rs 2.48 KB
Newer Older
1
use crate::config::{CONFIG, SECRETS};
tec's avatar
tec committed
2 3 4 5 6 7 8 9 10 11 12
use ldap3::{LdapConn, LdapConnSettings, Scope, SearchEntry};

#[derive(Debug)]
pub struct LDAPUser {
    pub username: String,
    pub name: String,
    pub when_created: String,
}

pub fn ldap_search(username: &str) -> Option<LDAPUser> {
    let settings = LdapConnSettings::new().set_no_tls_verify(true);
13 14
    let ldap =
        LdapConn::with_settings(settings, &CONFIG.bind_address).expect("Unable to connect to LDAP");
tec's avatar
tec committed
15 16
    ldap.simple_bind(
        "cn=ucc-discord-bot,cn=Users,dc=ad,dc=ucc,dc=gu,dc=uwa,dc=edu,dc=au",
17
        &SECRETS.ldap_pass,
tec's avatar
tec committed
18 19 20 21 22 23 24 25 26 27 28 29 30 31
    )
    .expect("Unable to attempt to bind to LDAP")
    .success()
    .expect("Unable to bind to LDAP");
    let (rs, _res) = ldap
        .search(
            "cn=Users,dc=ad,dc=ucc,dc=gu,dc=uwa,dc=edu,dc=au",
            Scope::Subtree,
            &format!("(cn={})", username),
            vec!["when_created", "displayName", "name"],
        )
        .expect("LDAP error")
        .success()
        .expect("LDAP search error");
32
    if rs.is_empty() {
Ash's avatar
cleanup  
Ash committed
33
        return None
tec's avatar
tec committed
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
    }
    let result = SearchEntry::construct(rs[0].clone()).attrs;
    Some(LDAPUser {
        username: result
            .get("name")
            .expect("LDAP failed to get 'name' field")
            .join(""),
        name: result
            .get("displayName")
            .expect("LDAP failed to get 'displayName' field")
            .join(""),
        when_created: "".to_string() // result
            // .get("whenCreated")
            // .expect("LDAP failed to get 'whenCreated' field")
            // .join(""),
    })
}

pub fn ldap_exists(username: &str) -> bool {
53
    ldap_search(username).is_some()
tec's avatar
tec committed
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
}

#[derive(Debug)]
pub struct TLA {
    pub tla: Option<String>,
    pub name: String,
    pub username: String,
}

pub fn tla_search(term: &str) -> Option<TLA> {
    let tla_search = String::from_utf8(
        std::process::Command::new("tla")
            .arg(term)
            .output()
            .expect("failed to execute tla")
            .stdout,
    )
    .expect("unable to parse stdout to String");
    let tla_results = tla_search.split("\n").collect::<Vec<&str>>();
    if tla_results.len() != 4 {
        return None;
    }
    let mut the_tla = Some(tla_results[0].replace("TLA: ", "")[1..4].to_string());
    if the_tla == Some(String::from("???")) {
        the_tla = None;
    }
    Some(TLA {
        tla: the_tla,
        name: tla_results[1].replace("Name: ", ""),
        username: tla_results[2].replace("Login: ", ""),
    })
}