]> BookStack Code Mirror - bookstack/blob - app/Services/LdapService.php
Merge pull request #3 from OsmosysSoftware/revert-1-issue-181
[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         $this->bindSystemUser($ldapConnection);
40
41         // Find user
42         $userFilter = $this->buildFilter($this->config['user_filter'], ['user' => $userName]);
43         $baseDn = $this->config['base_dn'];
44         $emailAttr = $this->config['email_attribute'];
45         $users = $this->ldap->searchAndGetEntries($ldapConnection, $baseDn, $userFilter, ['cn', 'uid', 'dn', $emailAttr]);
46         if ($users['count'] === 0) return null;
47
48         $user = $users[0];
49         return [
50             'uid'   => (isset($user['uid'])) ? $user['uid'][0] : $user['dn'],
51             'name'  => $user['cn'][0],
52             'dn'    => $user['dn'],
53             'email' => (isset($user[$emailAttr])) ? (is_array($user[$emailAttr]) ? $user[$emailAttr][0] : $user[$emailAttr]) : null
54         ];
55     }
56
57     /**
58      * @param Authenticatable $user
59      * @param string          $username
60      * @param string          $password
61      * @return bool
62      * @throws LdapException
63      */
64     public function validateUserCredentials(Authenticatable $user, $username, $password)
65     {
66         $ldapUser = $this->getUserDetails($username);
67         if ($ldapUser === null) return false;
68         if ($ldapUser['uid'] !== $user->external_auth_id) return false;
69
70         $ldapConnection = $this->getConnection();
71         try {
72             $ldapBind = $this->ldap->bind($ldapConnection, $ldapUser['dn'], $password);
73         } catch (\ErrorException $e) {
74             $ldapBind = false;
75         }
76
77         return $ldapBind;
78     }
79
80     /**
81      * Bind the system user to the LDAP connection using the given credentials
82      * otherwise anonymous access is attempted.
83      * @param $connection
84      * @throws LdapException
85      */
86     protected function bindSystemUser($connection)
87     {
88         $ldapDn = $this->config['dn'];
89         $ldapPass = $this->config['pass'];
90
91         $isAnonymous = ($ldapDn === false || $ldapPass === false);
92         if ($isAnonymous) {
93             $ldapBind = $this->ldap->bind($connection);
94         } else {
95             $ldapBind = $this->ldap->bind($connection, $ldapDn, $ldapPass);
96         }
97
98         if (!$ldapBind) throw new LdapException(($isAnonymous ? trans('errors.ldap_fail_anonymous') : trans('errors.ldap_fail_authed')));
99     }
100
101     /**
102      * Get the connection to the LDAP server.
103      * Creates a new connection if one does not exist.
104      * @return resource
105      * @throws LdapException
106      */
107     protected function getConnection()
108     {
109         if ($this->ldapConnection !== null) return $this->ldapConnection;
110
111         // Check LDAP extension in installed
112         if (!function_exists('ldap_connect') && config('app.env') !== 'testing') {
113             throw new LdapException(trans('errors.ldap_extension_not_installed'));
114         }
115
116         // Get port from server string and protocol if specified.
117         $ldapServer = explode(':', $this->config['server']);
118         $hasProtocol = preg_match('/^ldaps{0,1}\:\/\//', $this->config['server']) === 1;
119         if (!$hasProtocol) array_unshift($ldapServer, '');
120         $hostName = $ldapServer[0] . ($hasProtocol?':':'') . $ldapServer[1];
121         $defaultPort = $ldapServer[0] === 'ldaps' ? 636 : 389;
122         $ldapConnection = $this->ldap->connect($hostName, count($ldapServer) > 2 ? intval($ldapServer[2]) : $defaultPort);
123
124         if ($ldapConnection === false) {
125             throw new LdapException(trans('errors.ldap_cannot_connect'));
126         }
127
128         // Set any required options
129         if ($this->config['version']) {
130             $this->ldap->setVersion($ldapConnection, $this->config['version']);
131         }
132
133         $this->ldapConnection = $ldapConnection;
134         return $this->ldapConnection;
135     }
136
137     /**
138      * Build a filter string by injecting common variables.
139      * @param string $filterString
140      * @param array $attrs
141      * @return string
142      */
143     protected function buildFilter($filterString, array $attrs)
144     {
145         $newAttrs = [];
146         foreach ($attrs as $key => $attrText) {
147             $newKey = '${' . $key . '}';
148             $newAttrs[$newKey] = $attrText;
149         }
150         return strtr($filterString, $newAttrs);
151     }
152
153 }
Morty Proxy This is a proxified and sanitized view of the page, visit original site.