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