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