]> BookStack Code Mirror - bookstack/blob - app/Services/LdapService.php
set uploaded files public visibliity (relevant for S3 storage)
[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('LDAP access failed using ' . ($isAnonymous ? ' anonymous bind.' : ' given dn & pass details'));
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('LDAP PHP extension not installed');
113         }
114
115         // Get port from server string if specified.
116         $ldapServer = explode(':', $this->config['server']);
117         $ldapConnection = $this->ldap->connect($ldapServer[0], count($ldapServer) > 1 ? $ldapServer[1] : 389);
118
119         if ($ldapConnection === false) {
120             throw new LdapException('Cannot connect to ldap server, Initial connection failed');
121         }
122
123         // Set any required options
124         if ($this->config['version']) {
125             $this->ldap->setVersion($ldapConnection, $this->config['version']);
126         }
127
128         $this->ldapConnection = $ldapConnection;
129         return $this->ldapConnection;
130     }
131
132     /**
133      * Build a filter string by injecting common variables.
134      * @param string $filterString
135      * @param array $attrs
136      * @return string
137      */
138     protected function buildFilter($filterString, array $attrs)
139     {
140         $newAttrs = [];
141         foreach ($attrs as $key => $attrText) {
142             $newKey = '${' . $key . '}';
143             $newAttrs[$newKey] = $attrText;
144         }
145         return strtr($filterString, $newAttrs);
146     }
147
148 }