]> BookStack Code Mirror - bookstack/blob - app/Services/LdapService.php
a540ab58bb1e26c165376b2c22673fc1b3fcdf30
[bookstack] / app / Services / LdapService.php
1 <?php namespace BookStack\Services;
2
3
4 use BookStack\Exceptions\LdapException;
5
6 class LdapService
7 {
8
9     public function getUserDetails($userName)
10     {
11
12         if(!function_exists('ldap_connect')) {
13             throw new LdapException('LDAP PHP extension not installed');
14         }
15
16
17         $ldapServer = explode(':', config('services.ldap.server'));
18         $ldapConnection = ldap_connect($ldapServer[0], count($ldapServer) > 1 ? $ldapServer[1] : 389);
19
20         if ($ldapConnection === false) {
21             throw new LdapException('Cannot connect to ldap server, Initial connection failed');
22         }
23
24         // Options
25
26         ldap_set_option($ldapConnection, LDAP_OPT_PROTOCOL_VERSION, 3); // TODO - make configurable
27
28         $ldapDn = config('services.ldap.dn');
29         $ldapPass = config('services.ldap.pass');
30         $isAnonymous = ($ldapDn === false || $ldapPass === false);
31         if ($isAnonymous) {
32             $ldapBind = ldap_bind($ldapConnection);
33         } else {
34             $ldapBind = ldap_bind($ldapConnection, $ldapDn, $ldapPass);
35         }
36
37         if (!$ldapBind) throw new LdapException('LDAP access failed using ' . $isAnonymous ? ' anonymous bind.' : ' given dn & pass details');
38
39         // Find user
40         $userFilter = $this->buildFilter(config('services.ldap.user_filter'), ['user' => $userName]);
41         //dd($userFilter);
42         $baseDn = config('services.ldap.base_dn');
43         $ldapSearch = ldap_search($ldapConnection, $baseDn, $userFilter);
44         $users = ldap_get_entries($ldapConnection, $ldapSearch);
45
46         dd($users);
47     }
48
49
50     private function buildFilter($filterString, $attrs)
51     {
52         $newAttrs = [];
53         foreach ($attrs as $key => $attrText) {
54             $newKey = '${'.$key.'}';
55             $newAttrs[$newKey] = $attrText;
56         }
57         return strtr($filterString, $newAttrs);
58     }
59
60 }