1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
use std::collections::{HashMap, HashSet};

use ldap3::{
    log::{debug, error},
    Ldap, LdapConnAsync, LdapError, Mod, Scope, SearchEntry, StreamState,
};

pub extern crate ldap3;

const LDAP_ENTRY_DN: [&str; 1] = ["entryDN"];

///
/// Simple wrapper ontop of ldap3 crate. This wrapper provides a simple interface to perform LDAP operations
/// including authentication.
/// 
/// 
pub struct LdapClient {
    ldap: Ldap,
}

impl LdapClient {
    ///
    /// Returns the ldap3 client
    /// 
    pub fn get_inner(&self) -> Ldap {
        self.ldap.clone()
    }
}

impl LdapClient {

    ///
    /// Open a connection to an LDAP server specified by `url`.
    /// 
    pub async fn from(url: &str, bind_dn: &str, bind_pw: &str) -> Self {

        let (conn, mut ldap) = LdapConnAsync::new(url).await.unwrap();

        ldap3::drive!(conn);
        ldap.simple_bind(bind_dn, bind_pw)
            .await
            .unwrap()
            .success()
            .unwrap();

        LdapClient { ldap }
    }

    ///
    /// Create a new LdapClient from an existing Ldap connection.
    /// 
    pub fn from_ldap(ldap: Ldap) -> Self {
        LdapClient { ldap }
    }

    pub async fn unbind(&mut self) -> Result<(), String> {
        match self.ldap.unbind().await {
            Ok(_) => Ok(()),
            Err(error) => Err(format!("Failed to unbind {:?}", error)),
        }
    }

    ///
    /// The user is authenticated by searching for the user in the LDAP server.
    /// The search is performed using the provided filter. The filter should be a filter that matches a single user.
    ///
    pub async fn authenticate(
        &mut self,
        base: &str,
        uid: String,
        password: &String,
        filter: Box<dyn Filter>,
    ) -> Result<(), Error> {
        let rs = self
            .ldap
            .search(
                base,
                Scope::OneLevel,
                filter.filter().as_str(),
                LDAP_ENTRY_DN,
            )
            .await
            .unwrap();
        let (data, _rs) = rs.success().unwrap();
        if data.is_empty() {
            return Err(Error::NotFound(format!("No user found {:?}", uid)));
        }

        if data.len() > 1 {
            return Err(Error::MultipleResults(format!(
                "Found multiple users for uid {:?}",
                uid
            )));
        }

        let user_record = data.get(0).unwrap().to_owned();
        let user_record = SearchEntry::construct(user_record);
        let result: HashMap<&str, String> = user_record
            .attrs
            .iter()
            .filter(|(_, value)| !value.is_empty())
            .map(|(arrta, value)| (arrta.as_str(), value.get(0).unwrap().clone()))
            .collect();

        let entry_dn = result.get("entryDN").unwrap();

        let result = self.ldap.simple_bind(entry_dn, password).await;
        if result.is_err() {
            return Err(Error::AuthenticationFailed(format!(
                "Error authenticating user: {:?}",
                uid
            )));
        }

        let result = result.unwrap().success();
        if result.is_err() {
            return Err(Error::AuthenticationFailed(format!(
                "Error authenticating user: {:?}",
                uid
            )));
        }

        Ok(())
    }

    async fn search_innter(
        &mut self,
        base: &str,
        scope: Scope,
        filter: &dyn Filter,
        attributes: Vec<&str>,
    ) -> Result<SearchEntry, Error> {
        let search = self
            .ldap
            .search(base, scope, filter.filter().as_str(), attributes)
            .await;
        if let Err(error) = search {
            return Err(Error::Query(
                format!("Error searching for user: {:?}", error),
                error,
            ));
        }
        let result = search.unwrap().success();
        if let Err(error) = result {
            return Err(Error::Query(
                format!("Error searching for user: {:?}", error),
                error,
            ));
        }

        let records = result.unwrap().0;

        if records.len() > 0 {
            return Err(Error::MultipleResults(format!(
                "Found multiple records for the search criteria"
            )));
        }

        if records.len() == 0 {
            return Err(Error::NotFound(format!(
                "No records found for the search criteria"
            )));
        }

        let record = records.get(0).unwrap();

        Ok(SearchEntry::construct(record.to_owned()))
    }

    ///
    /// Search a single value from the LDAP server. The search is performed using the provided filter.
    /// The filter should be a filter that matches a single user. if the filter matches multiple users, an error is returned.
    /// This operatrion is useful when records has single value attributes. 
    /// Result will be mapped to a struct of type T.
    /// 
    pub async fn search<T: for<'a> serde::Deserialize<'a>>(
        &mut self,
        base: &str,
        scope: Scope,
        filter: &dyn Filter,
        attributes: Vec<&str>,
    ) -> Result<T, Error> {
        let search_entry = self.search_innter(base, scope, filter, attributes).await?;

        let json = LdapClient::create_json_signle_value(search_entry)?;
        LdapClient::map_to_struct(json)
    }

    ///
    /// Search a single value from the LDAP server. The search is performed using the provided filter.
    /// The filter should be a filter that matches a single user. if the filter matches multiple users, an error is returned.
    /// This operatrion is useful when records has multi value attributes. 
    /// Result will be mapped to a struct of type T.
    /// 
    pub async fn search_multi_valued<T: for<'a> serde::Deserialize<'a>>(
        &mut self,
        base: &str,
        scope: Scope,
        filter: &dyn Filter,
        attributes: Vec<&str>,
    ) -> Result<T, Error> {
        let search_entry = self.search_innter(base, scope, filter, attributes).await?;
        let json = LdapClient::create_json_multi_value(search_entry)?;

        LdapClient::map_to_struct(json)
    }

    fn map_to_struct<T: for<'a> serde::Deserialize<'a>>(json: String) -> Result<T, Error> {
        let result: Result<T, serde_json::Error> = serde_json::from_str(&json);
        match result {
            Ok(result) => Ok(result),
            Err(error) => Err(Error::Mapping(format!(
                "Error converting search result to object: {:?}",
                error
            ))),
        }
    }

    fn create_json_signle_value(search_entry: SearchEntry) -> Result<String, Error> {
        let result: HashMap<&str, Option<&String>> = search_entry
            .attrs
            .iter()
            .filter(|(_, value)| !value.is_empty())
            .map(|(arrta, value)| (arrta.as_str(), value.get(0).to_owned()))
            .collect();
        let json = serde_json::to_string(&result);
        match json {
            Ok(json) => Ok(json),
            Err(error) => Err(Error::Mapping(format!(
                "Error converting search result to json: {:?}",
                error
            ))),
        }
    }

    fn create_json_multi_value(search_entry: SearchEntry) -> Result<String, Error> {
        let result: HashMap<&str, Vec<String>> = search_entry
            .attrs
            .iter()
            .filter(|(_, value)| !value.is_empty())
            .map(|(arrta, value)| (arrta.as_str(), value.to_owned()))
            .collect();

        let json = serde_json::to_string(&result);
        match json {
            Ok(json) => Ok(json),
            Err(error) => Err(Error::Mapping(format!(
                "Error converting search result to json: {:?}",
                error
            ))),
        }
    }

    async fn streaming_search_inner(
        &mut self,
        base: &str,
        scope: Scope,
        filter: &dyn Filter,
        limit: i32,
        attributes: Vec<&str>,
    ) -> Result<Vec<SearchEntry>, Error> {
        let search_stream = self
            .ldap
            .streaming_search(base, scope, filter.filter().as_str(), attributes)
            .await;
        if let Err(error) = search_stream {
            return Err(Error::Query(
                format!("Error searching for user: {:?}", error),
                error,
            ));
        }
        let mut search_stream = search_stream.unwrap();

        let mut entries = Vec::new();
        let mut count = 0;

        loop {
            let next = search_stream.next().await;
            if next.is_err() {
                break;
            }

            if search_stream.state() != StreamState::Active {
                break;
            }

            let entry = next.unwrap();
            if entry.is_none() {
                break;
            }
            if let Some(entry) = entry {
                entries.push(SearchEntry::construct(entry));
                count += 1;
            }

            if count == limit {
                break;
            }
        }

        let _res = search_stream.finish().await;
        let msgid = search_stream.ldap_handle().last_id();
        self.ldap.abandon(msgid).await.unwrap();

        Ok(entries)
    }

    ///
    /// This method is used to search multiple records from the LDAP server. The search is performed using the provided filter.
    /// This operatrion is useful when records has multi value attributes. 
    /// Method will return a vector of structs of type T. return vector will be maximum of the limit provided.
    /// 
    pub async fn streaming_search<T: for<'a> serde::Deserialize<'a>>(
        &mut self,
        base: &str,
        scope: Scope,
        filter: &dyn Filter,
        limit: i32,
        attributes: Vec<&str>,
    ) -> Result<Vec<T>, Error> {
        let entries = self
            .streaming_search_inner(base, scope, filter, limit, attributes)
            .await?;

        let jsons = entries
            .iter()
            .map(|entry| LdapClient::create_json_signle_value(entry.to_owned()).unwrap())
            .collect::<Vec<String>>();

        let data = jsons
            .iter()
            .map(|json| LdapClient::map_to_struct::<T>(json.to_owned()).unwrap())
            .collect::<Vec<T>>();

        Ok(data)
    }

    ///
    /// This method is used to search multiple records from the LDAP server. The search is performed using the provided filter.
    /// This operatrion is useful when records has single value attributes. 
    /// Method will return a vector of structs of type T. return vector will be maximum of the limit provided.
    /// 
    pub async fn streaming_search_multi_valued<T: for<'a> serde::Deserialize<'a>>(
        &mut self,
        base: &str,
        scope: Scope,
        filter: &dyn Filter,
        limit: i32,
        attributes: Vec<&str>,
    ) -> Result<Vec<T>, Error> {
        let entries = self
            .streaming_search_inner(base, scope, filter, limit, attributes)
            .await?;

        let jsons = entries
            .iter()
            .map(|entry| LdapClient::create_json_multi_value(entry.to_owned()).unwrap())
            .collect::<Vec<String>>();

        let data = jsons
            .iter()
            .map(|json| LdapClient::map_to_struct::<T>(json.to_owned()).unwrap())
            .collect::<Vec<T>>();

        Ok(data)
    }

    ///
    /// base = "ou=people,dc=example,dc=com"
    ///
    pub async fn create<T: for<'a> serde::Deserialize<'a>>(
        &mut self,
        uid: &str,
        base: &str,
        data: Vec<(&str, HashSet<&str>)>,
    ) -> Result<(), Error> {
        let dn = format!("uid={},{}", uid, base);
        let save = self.ldap.add(dn.as_str(), data).await;
        if let Err(err) = save {
            return Err(Error::Create(format!("Error saving user: {:?}", err), err));
        }
        let save = save.unwrap().success();

        if let Err(err) = save {
            return Err(Error::Create(format!("Error saving user: {:?}", err), err));
        }
        let res = save.unwrap();
        debug!("Sucessfully created record result: {:?}", res);
        Ok(())
    }

    pub async fn update(
        &mut self,
        uid: &str,
        base: &str,
        data: Vec<Mod<&str>>,
        new_udid: Option<&str>,
    ) -> Result<(), Error> {
        let dn = format!("uid={},{}", uid, base);

        let res = self.ldap.modify(dn.as_str(), data).await;
        if let Err(err) = res {
            return Err(Error::Update(
                format!("Error updating user: {:?}", err),
                err,
            ));
        }

        let res = res.unwrap().success();
        if let Err(err) = res {
            return Err(Error::Update(
                format!("Error updating user: {:?}", err),
                err,
            ));
        }

        if new_udid.is_none() {
            return Ok(());
        }

        let new_udid = new_udid.unwrap();
        if !uid.eq_ignore_ascii_case(new_udid) {
            let new_dn = format!("uid={}", new_udid);
            let dn_update = self
                .ldap
                .modifydn(dn.as_str(), new_dn.as_str(), true, None)
                .await;
            if let Err(err) = dn_update {
                error!("Failed to update dn for user {:?} error {:?}", uid, err);
                return Err(Error::Update(
                    format!("Failed to update dn for user {:?}", uid),
                    err,
                ));
            }

            let dn_update = dn_update.unwrap().success();
            if let Err(err) = dn_update {
                error!("Failed to update dn for user {:?} error {:?}", uid, err);
                return Err(Error::Update(
                    format!("Failed to update dn for user {:?}", uid),
                    err,
                ));
            }

            let res = dn_update.unwrap();
            debug!("Sucessfully updated dn result: {:?}", res);
        }

        Ok(())
    }

    pub async fn delete(&mut self, uid: &str, base: &str) -> Result<(), Error> {
        let dn = format!("uid={},{}", uid, base);
        let delete = self.ldap.delete(dn.as_str()).await;

        if let Err(err) = delete {
            return Err(Error::Delete(
                format!("Error deleting user: {:?}", err),
                err,
            ));
        }
        let delete = delete.unwrap().success();
        if let Err(err) = delete {
            return Err(Error::Delete(
                format!("Error deleting user: {:?}", err),
                err,
            ));
        }
        let delete = delete.unwrap();
        debug!("Sucessfully deleted record result: {:?}", delete);
        Ok(())
    }
}

pub trait Filter {
    fn filter(&self) -> String;
}

pub struct AndFilter {
    filters: Vec<Box<dyn Filter>>,
}

impl AndFilter {
    pub fn new() -> Self {
        AndFilter {
            filters: Vec::new(),
        }
    }

    pub fn add(&mut self, filter: Box<dyn Filter>) {
        self.filters.push(filter);
    }
}

impl Filter for AndFilter {
    fn filter(&self) -> String {
        let mut filter = String::from("(&");
        for f in &self.filters {
            filter.push_str(&f.filter());
        }
        filter.push(')');
        filter
    }
}

pub struct OrFilter {
    filters: Vec<Box<dyn Filter>>,
}

impl OrFilter {
    pub fn new() -> Self {
        OrFilter {
            filters: Vec::new(),
        }
    }

    pub fn add(&mut self, filter: Box<dyn Filter>) {
        self.filters.push(filter);
    }
}

impl Filter for OrFilter {
    fn filter(&self) -> String {
        let mut filter = String::from("(|");
        for f in &self.filters {
            filter.push_str(&f.filter());
        }
        filter.push(')');
        filter
    }
}

pub struct EqFilter {
    attribute: String,
    value: String,
}

impl Filter for EqFilter {
    fn filter(&self) -> String {
        format!("({}={})", self.attribute, self.value)
    }
}

pub struct NotFilter {
    filter: Box<dyn Filter>,
}

impl NotFilter {
    pub fn new(filter: Box<dyn Filter>) -> Self {
        NotFilter { filter }
    }
}

impl Filter for NotFilter {
    fn filter(&self) -> String {
        format!("(!{})", self.filter.filter())
    }
}

pub struct LikeFilter {
    attribute: String,
    value: String,
}

impl Filter for LikeFilter {
    fn filter(&self) -> String {
        format!("({}~={})", self.attribute, self.value)
    }
}

#[derive(Debug)]
pub enum Error {
    Query(String, LdapError),
    NotFound(String),
    MultipleResults(String),
    AuthenticationFailed(String),
    Create(String, LdapError),
    Update(String, LdapError),
    Delete(String, LdapError),
    Mapping(String),
}

#[cfg(test)]
mod tests {
    use serde::Deserialize;

    use super::*;

    #[test]
    fn create_json_multi_value_test() {
        let mut map: HashMap<String, Vec<String>> = HashMap::new();
        map.insert(
            "key1".to_string(),
            vec!["value1".to_string(), "value2".to_string()],
        );
        map.insert(
            "key2".to_string(),
            vec!["value3".to_string(), "value4".to_string()],
        );
        let entry = SearchEntry {
            dn: "dn".to_string(),
            attrs: map,
            bin_attrs: HashMap::new(),
        };

        let json = LdapClient::create_json_multi_value(entry).unwrap();
        let test = LdapClient::map_to_struct::<TestMultiValued>(json);
        assert!(test.is_ok());
        let test = test.unwrap();
        assert_eq!(test.key1, vec!["value1".to_string(), "value2".to_string()]);
        assert_eq!(test.key2, vec!["value3".to_string(), "value4".to_string()]);
    }

    #[test]
    fn create_json_single_value_test() {
        let mut map: HashMap<String, Vec<String>> = HashMap::new();
        map.insert("key1".to_string(), vec!["value1".to_string()]);
        map.insert("key2".to_string(), vec!["value2".to_string()]);
        let entry = SearchEntry {
            dn: "dn".to_string(),
            attrs: map,
            bin_attrs: HashMap::new(),
        };

        let json = LdapClient::create_json_signle_value(entry).unwrap();
        let test = LdapClient::map_to_struct::<TestSingleValued>(json);
        assert!(test.is_ok());
        let test = test.unwrap();
        assert_eq!(test.key1, "value1".to_string());
        assert_eq!(test.key2, "value2".to_string());
    }

    #[derive(Debug, Deserialize)]
    struct TestMultiValued {
        key1: Vec<String>,
        key2: Vec<String>,
    }

    #[derive(Debug, Deserialize)]
    struct TestSingleValued {
        key1: String,
        key2: String,
    }
}