]> BookStack Code Mirror - bookstack/blob - app/Services/LdapService.php
d33f8c378fdb1fc87d2878d2dfda3fff40efcb4e
[bookstack] / app / Services / LdapService.php
1 <?php namespace BookStack\Services;
2
3
4 use BookStack\Exceptions\LdapException;
5 use Illuminate\Contracts\Auth\Authenticatable;
6
7 /**
8  * Class LdapService
9  * Handles any app-specific LDAP tasks.
10  * @package BookStack\Services
11  */
12 class LdapService
13 {
14
15     protected $ldap;
16     protected $ldapConnection;
17     protected $config;
18
19     /**
20      * LdapService constructor.
21      * @param Ldap $ldap
22      */
23     public function __construct(Ldap $ldap)
24     {
25         $this->ldap = $ldap;
26         $this->config = config('services.ldap');
27     }
28
29     /**
30      * Get the details of a user from LDAP using the given username.
31      * User found via configurable user filter.
32      * @param $userName
33      * @return array|null
34      * @throws LdapException
35      */
36     public function getUserDetails($userName)
37     {
38         $ldapConnection = $this->getConnection();
39
40         // Find user
41         $userFilter = $this->buildFilter($this->config['user_filter'], ['user' => $userName]);
42         $baseDn = $this->config['base_dn'];
43         $users = $this->ldap->searchAndGetEntries($ldapConnection, $baseDn, $userFilter, ['cn', 'uid', 'dn', 'mail']);
44         if ($users['count'] === 0) return null;
45
46         $user = $users[0];
47         return [
48             'uid'   => $user['uid'][0],
49             'name'  => $user['cn'][0],
50             'dn'    => $user['dn'],
51             'email' => (isset($user['mail'])) ? $user['mail'][0] : null
52         ];
53     }
54
55     /**
56      * @param Authenticatable $user
57      * @param string          $username
58      * @param string          $password
59      * @return bool
60      * @throws LdapException
61      */
62     public function validateUserCredentials(Authenticatable $user, $username, $password)
63     {
64         $ldapUser = $this->getUserDetails($username);
65         if ($ldapUser === null) return false;
66         if ($ldapUser['uid'] !== $user->external_auth_id) return false;
67
68         $ldapConnection = $this->getConnection();
69         try {
70             $ldapBind = $this->ldap->bind($ldapConnection, $ldapUser['dn'], $password);
71         } catch (\ErrorException $e) {
72             $ldapBind = false;
73         }
74
75         return $ldapBind;
76     }
77
78     /**
79      * Bind the system user to the LDAP connection using the given credentials
80      * otherwise anonymous access is attempted.
81      * @param $connection
82      * @throws LdapException
83      */
84     protected function bindSystemUser($connection)
85     {
86         $ldapDn = $this->config['dn'];
87         $ldapPass = $this->config['pass'];
88
89         $isAnonymous = ($ldapDn === false || $ldapPass === false);
90         if ($isAnonymous) {
91             $ldapBind = $this->ldap->bind($connection);
92         } else {
93             $ldapBind = $this->ldap->bind($connection, $ldapDn, $ldapPass);
94         }
95
96         if (!$ldapBind) throw new LdapException('LDAP access failed using ' . $isAnonymous ? ' anonymous bind.' : ' given dn & pass details');
97     }
98
99     /**
100      * Get the connection to the LDAP server.
101      * Creates a new connection if one does not exist.
102      * @return resource
103      * @throws LdapException
104      */
105     protected function getConnection()
106     {
107         if ($this->ldapConnection !== null) return $this->ldapConnection;
108
109         // Check LDAP extension in installed
110         if (!function_exists('ldap_connect') && config('app.env') !== 'testing') {
111             throw new LdapException('LDAP PHP extension not installed');
112         }
113
114         // Get port from server string if specified.
115         $ldapServer = explode(':', $this->config['server']);
116         $ldapConnection = $this->ldap->connect($ldapServer[0], count($ldapServer) > 1 ? $ldapServer[1] : 389);
117
118         if ($ldapConnection === false) {
119             throw new LdapException('Cannot connect to ldap server, Initial connection failed');
120         }
121
122         // Set any required options
123         if ($this->config['version']) {
124             $this->ldap->setOption($ldapConnection, LDAP_OPT_PROTOCOL_VERSION, $this->config['version']);
125         }
126
127         $this->ldapConnection = $ldapConnection;
128         return $this->ldapConnection;
129     }
130
131     /**
132      * Build a filter string by injecting common variables.
133      * @param string $filterString
134      * @param array $attrs
135      * @return string
136      */
137     protected function buildFilter($filterString, array $attrs)
138     {
139         $newAttrs = [];
140         foreach ($attrs as $key => $attrText) {
141             $newKey = '${' . $key . '}';
142             $newAttrs[$newKey] = $attrText;
143         }
144         return strtr($filterString, $newAttrs);
145     }
146
147 }