Skip to content

Commit

Permalink
Formated code after adding groups
Browse files Browse the repository at this point in the history
  • Loading branch information
keaz committed Dec 16, 2023
1 parent c861dec commit 995f5b5
Showing 1 changed file with 78 additions and 55 deletions.
133 changes: 78 additions & 55 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,15 @@
//!
//! # Documentation
//! * [Examples Repository](https://github.com/keaz/simple-ldap)
//!
//!
//! # Usage
//! Add this to your `Cargo.toml`:
//! ```toml
//! [dependencies]
//! simple-ldap = "1.3.0"
//!
//!
//! ```
//!
//!
//! ## Features
//! * [x] Authentication
//! * [x] Search
Expand All @@ -30,7 +30,7 @@
use std::collections::{HashMap, HashSet};

use deadpool::managed::Object;
use filter::{Filter, EqFilter};
use filter::{EqFilter, Filter};
use ldap3::{
log::{debug, error},
Ldap, LdapError, Mod, Scope, SearchEntry, StreamState,
Expand Down Expand Up @@ -790,32 +790,32 @@ impl LdapClient {

///
/// Create a new group in the LDAP server. The group will be created in the provided base DN.
///
///
/// # Arguments
/// * `group_name` - The name of the group
/// * `group_ou` - The ou of the group
/// * `description` - The description of the group
///
///
/// # Returns
/// * `Result<(), Error>` - Returns an error if the group creation fails
///
///
/// # Example
/// ```
/// use simple_ldap::LdapClient;
/// use simple_ldap::pool::LdapConfig;
///
///
/// let ldap_config = LdapConfig {
/// bind_dn: "cn=manager".to_string(),
/// bind_pw: "password".to_string(),
/// ldap_url: "ldap://ldap_server:1389/dc=example,dc=com".to_string(),
/// pool_size: 10,
/// };
///
///
/// let pool = pool::build_connection_pool(&ldap_config).await;
/// let mut ldap = pool.get_connection().await;
///
///
/// let result = ldap.create_group("test_group", "ou=groups,dc=example,dc=com", "test group").await;
///
///
/// ```
pub async fn create_group(
&mut self,
Expand All @@ -825,10 +825,12 @@ impl LdapClient {
) -> Result<(), Error> {
let dn = format!("cn={},{}", group_name, group_ou);

let data = vec![("objectClass", HashSet::from(["top", "groupOfNames"])),
("cn", HashSet::from([group_name])),
("ou", HashSet::from([group_ou])),
("description", HashSet::from([description]))];
let data = vec![
("objectClass", HashSet::from(["top", "groupOfNames"])),
("cn", HashSet::from([group_name])),
("ou", HashSet::from([group_ou])),
("description", HashSet::from([description])),
];
let save = self.ldap.add(dn.as_str(), data).await;
if let Err(err) = save {
return Err(Error::Create(
Expand All @@ -847,39 +849,42 @@ impl LdapClient {
let res = save.unwrap();
debug!("Sucessfully created group result: {:?}", res);
Ok(())
}

}

///
/// Add users to a group in the LDAP server. The group will be updated in the provided base DN.
///
///
/// # Arguments
/// * `users` - The list of users to add to the group
/// * `group_dn` - The dn of the group
///
///
/// # Returns
/// * `Result<(), Error>` - Returns an error if failed to add users to the group
///
///
/// # Example
/// ```
/// use simple_ldap::LdapClient;
/// use simple_ldap::pool::LdapConfig;
///
///
/// let ldap_config = LdapConfig {
/// bind_dn: "cn=manager".to_string(),
/// bind_pw: "password".to_string(),
/// ldap_url: "ldap://ldap_server:1389/dc=example,dc=com".to_string(),
/// pool_size: 10,
/// };
///
///
/// let pool = pool::build_connection_pool(&ldap_config).await;
/// let mut ldap = pool.get_connection().await;
///
///
/// let result = ldap.add_users_to_group(vec!["uid=bd9b91ec-7a69-4166-bf67-cc7e553b2fd9,ou=people,dc=example,dc=com"],
/// "cn=test_group,ou=groups,dc=example,dc=com").await;
///
///
/// ```
pub async fn add_users_to_group(&mut self, users: Vec<&str>,group_dn: &str) -> Result<(), Error> {
pub async fn add_users_to_group(
&mut self,
users: Vec<&str>,
group_dn: &str,
) -> Result<(), Error> {
let mut mods = Vec::new();
let users = users.iter().map(|user| *user).collect::<HashSet<&str>>();
mods.push(Mod::Replace("member", users));
Expand Down Expand Up @@ -915,43 +920,48 @@ impl LdapClient {

///
/// Get users of a group in the LDAP server. The group will be searched in the provided base DN.
///
///
/// # Arguments
/// * `group_dn` - The dn of the group
/// * `base_dn` - The base dn to search for the users
/// * `scope` - The scope of the search
/// * `attributes` - The attributes to return from the search
///
///
/// # Returns
/// * `Result<Vec<T>, Error>` - Returns a vector of structs of type T
///
///
/// # Example
/// ```
/// use simple_ldap::LdapClient;
/// use simple_ldap::pool::LdapConfig;
///
///
/// #[derive(Debug, Deserialize)]
/// struct User {
/// uid: String,
/// cn: String,
/// sn: String,
/// }
///
///
/// let ldap_config = LdapConfig {
/// bind_dn: "cn=manager".to_string(),
/// bind_pw: "password".to_string(),
/// ldap_url: "ldap://ldap_server:1389/dc=example,dc=com".to_string(),
/// pool_size: 10,
/// };
///
///
/// let pool = pool::build_connection_pool(&ldap_config).await;
/// let mut ldap = pool.get_connection().await;
///
///
/// let result = ldap.get_members::<User>("cn=test_group,ou=groups,dc=example,dc=com", "ou=people,dc=example,dc=com", self::ldap3::Scope::OneLevel, vec!["cn", "sn", "uid"]).await;
///
/// ```
pub async fn get_members<T: for<'a> serde::Deserialize<'a>>(&mut self, group_dn: &str,base_dn: &str, scope: Scope, attributes: &Vec<&str>) ->
Result<Vec<T>, Error> {
pub async fn get_members<T: for<'a> serde::Deserialize<'a>>(
&mut self,
group_dn: &str,
base_dn: &str,
scope: Scope,
attributes: &Vec<&str>,
) -> Result<Vec<T>, Error> {
let search = self
.ldap
.search(
Expand All @@ -961,7 +971,7 @@ impl LdapClient {
vec!["member"],
)
.await;

if let Err(error) = search {
return Err(Error::Query(
format!("Error searching for record: {:?}", error),
Expand Down Expand Up @@ -1002,23 +1012,23 @@ impl LdapClient {

let mut members = Vec::new();
for member in result.get("member").unwrap() {
let uid = member.split(",").collect::<Vec<&str>>()[0].split("=").collect::<Vec<&str>>();
let uid = member.split(",").collect::<Vec<&str>>()[0]
.split("=")
.collect::<Vec<&str>>();
let filter = EqFilter::from(uid[0].to_string(), uid[1].to_string());
let x = self.search::<T>(base_dn, scope, &filter, attributes).await;
match x {
Ok(x) => {
members.push(x);
},
}
Err(err) => {
error!("Error getting member {:?} error {:?}", member, err);
}
}
}

Ok(members)

}

}

///
Expand Down Expand Up @@ -1431,7 +1441,7 @@ mod tests {
}

#[tokio::test]
async fn test_create_group(){
async fn test_create_group() {
let ldap_config = LdapConfig {
bind_dn: "cn=manager".to_string(),
bind_pw: "password".to_string(),
Expand All @@ -1444,14 +1454,14 @@ mod tests {
let result = pool
.get_connection()
.await
.create_group("test_group", "dc=example,dc=com","Some Description")
.create_group("test_group", "dc=example,dc=com", "Some Description")
.await;

assert!(result.is_ok());
}

#[tokio::test]
async fn test_add_users_to_group(){
async fn test_add_users_to_group() {
let ldap_config = LdapConfig {
bind_dn: "cn=manager".to_string(),
bind_pw: "password".to_string(),
Expand All @@ -1464,23 +1474,27 @@ mod tests {
let _result = pool
.get_connection()
.await
.create_group("test_group_1", "dc=example,dc=com","Some Decription")
.create_group("test_group_1", "dc=example,dc=com", "Some Decription")
.await;

let result = pool
.get_connection()
.await
.add_users_to_group(vec!["uid=f92f4cb2-e821-44a4-bb13-b8ebadf4ecc5,ou=people,dc=example,dc=com",
"uid=e219fbc0-6df5-4bc3-a6ee-986843bb157e,ou=people,dc=example,dc=com"],
"cn=test_group_1,dc=example,dc=com")
.add_users_to_group(
vec![
"uid=f92f4cb2-e821-44a4-bb13-b8ebadf4ecc5,ou=people,dc=example,dc=com",
"uid=e219fbc0-6df5-4bc3-a6ee-986843bb157e,ou=people,dc=example,dc=com",
],
"cn=test_group_1,dc=example,dc=com",
)
.await;

// println!("{:?}", result.err().unwrap());
assert!(result.is_ok());
}

#[tokio::test]
async fn test_get_members(){
async fn test_get_members() {
let ldap_config = LdapConfig {
bind_dn: "cn=manager".to_string(),
bind_pw: "password".to_string(),
Expand All @@ -1494,23 +1508,32 @@ mod tests {
let _result = pool
.get_connection()
.await
.create_group("test_group_2", "dc=example,dc=com","Some Decription 2")
.create_group("test_group_2", "dc=example,dc=com", "Some Decription 2")
.await;

let result = pool
.get_connection()
.await
.add_users_to_group(vec!["uid=f92f4cb2-e821-44a4-bb13-b8ebadf4ecc5,ou=people,dc=example,dc=com",
"uid=e219fbc0-6df5-4bc3-a6ee-986843bb157e,ou=people,dc=example,dc=com"],
"cn=test_group_2,dc=example,dc=com")
.add_users_to_group(
vec![
"uid=f92f4cb2-e821-44a4-bb13-b8ebadf4ecc5,ou=people,dc=example,dc=com",
"uid=e219fbc0-6df5-4bc3-a6ee-986843bb157e,ou=people,dc=example,dc=com",
],
"cn=test_group_2,dc=example,dc=com",
)
.await;

let result = pool
.get_connection()
.await
.get_members::<User>("cn=test_group_2,dc=example,dc=com","dc=example,dc=com", Scope::Subtree, &vec!["cn", "sn", "uid"])
.get_members::<User>(
"cn=test_group_2,dc=example,dc=com",
"dc=example,dc=com",
Scope::Subtree,
&vec!["cn", "sn", "uid"],
)
.await;

assert!(result.is_ok());
let restult = result.unwrap();
assert_eq!(restult.len(), 2);
Expand Down

0 comments on commit 995f5b5

Please sign in to comment.