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