1 <?php namespace BookStack\Services;
3 use BookStack\Exceptions\LdapException;
4 use BookStack\Repos\UserRepo;
7 use Illuminate\Contracts\Auth\Authenticatable;
8 use Illuminate\Database\Eloquent\Builder;
12 * Handles any app-specific LDAP tasks.
13 * @package BookStack\Services
19 protected $ldapConnection;
25 * LdapService constructor.
27 * @param UserRepo $userRepo
29 public function __construct(Ldap $ldap, UserRepo $userRepo)
32 $this->config = config('services.ldap');
33 $this->userRepo = $userRepo;
34 $this->enabled = config('auth.method') === 'ldap';
38 * Check if groups should be synced.
41 public function shouldSyncGroups()
43 return $this->enabled && $this->config['user_to_groups'] !== false;
47 * Search for attributes for a specific user on the ldap
48 * @param string $userName
49 * @param array $attributes
51 * @throws LdapException
53 private function getUserWithAttributes($userName, $attributes)
55 $ldapConnection = $this->getConnection();
56 $this->bindSystemUser($ldapConnection);
59 $userFilter = $this->buildFilter($this->config['user_filter'], ['user' => $userName]);
60 $baseDn = $this->config['base_dn'];
62 $followReferrals = $this->config['follow_referrals'] ? 1 : 0;
63 $this->ldap->setOption($ldapConnection, LDAP_OPT_REFERRALS, $followReferrals);
64 $users = $this->ldap->searchAndGetEntries($ldapConnection, $baseDn, $userFilter, $attributes);
65 if ($users['count'] === 0) {
73 * Get the details of a user from LDAP using the given username.
74 * User found via configurable user filter.
77 * @throws LdapException
79 public function getUserDetails($userName)
81 $emailAttr = $this->config['email_attribute'];
82 $user = $this->getUserWithAttributes($userName, ['cn', 'uid', 'dn', $emailAttr]);
89 'uid' => (isset($user['uid'])) ? $user['uid'][0] : $user['dn'],
90 'name' => $user['cn'][0],
92 'email' => (isset($user[$emailAttr])) ? (is_array($user[$emailAttr]) ? $user[$emailAttr][0] : $user[$emailAttr]) : null
97 * @param Authenticatable $user
98 * @param string $username
99 * @param string $password
101 * @throws LdapException
103 public function validateUserCredentials(Authenticatable $user, $username, $password)
105 $ldapUser = $this->getUserDetails($username);
106 if ($ldapUser === null) {
109 if ($ldapUser['uid'] !== $user->external_auth_id) {
113 $ldapConnection = $this->getConnection();
115 $ldapBind = $this->ldap->bind($ldapConnection, $ldapUser['dn'], $password);
116 } catch (\ErrorException $e) {
124 * Bind the system user to the LDAP connection using the given credentials
125 * otherwise anonymous access is attempted.
127 * @throws LdapException
129 protected function bindSystemUser($connection)
131 $ldapDn = $this->config['dn'];
132 $ldapPass = $this->config['pass'];
134 $isAnonymous = ($ldapDn === false || $ldapPass === false);
136 $ldapBind = $this->ldap->bind($connection);
138 $ldapBind = $this->ldap->bind($connection, $ldapDn, $ldapPass);
142 throw new LdapException(($isAnonymous ? trans('errors.ldap_fail_anonymous') : trans('errors.ldap_fail_authed')));
147 * Get the connection to the LDAP server.
148 * Creates a new connection if one does not exist.
150 * @throws LdapException
152 protected function getConnection()
154 if ($this->ldapConnection !== null) {
155 return $this->ldapConnection;
158 // Check LDAP extension in installed
159 if (!function_exists('ldap_connect') && config('app.env') !== 'testing') {
160 throw new LdapException(trans('errors.ldap_extension_not_installed'));
163 // Get port from server string and protocol if specified.
164 $ldapServer = explode(':', $this->config['server']);
165 $hasProtocol = preg_match('/^ldaps{0,1}\:\/\//', $this->config['server']) === 1;
167 array_unshift($ldapServer, '');
169 $hostName = $ldapServer[0] . ($hasProtocol?':':'') . $ldapServer[1];
170 $defaultPort = $ldapServer[0] === 'ldaps' ? 636 : 389;
171 $ldapConnection = $this->ldap->connect($hostName, count($ldapServer) > 2 ? intval($ldapServer[2]) : $defaultPort);
173 if ($ldapConnection === false) {
174 throw new LdapException(trans('errors.ldap_cannot_connect'));
177 // Set any required options
178 if ($this->config['version']) {
179 $this->ldap->setVersion($ldapConnection, $this->config['version']);
182 $this->ldapConnection = $ldapConnection;
183 return $this->ldapConnection;
187 * Build a filter string by injecting common variables.
188 * @param string $filterString
189 * @param array $attrs
192 protected function buildFilter($filterString, array $attrs)
195 foreach ($attrs as $key => $attrText) {
196 $newKey = '${' . $key . '}';
197 $newAttrs[$newKey] = $attrText;
199 return strtr($filterString, $newAttrs);
203 * Get the groups a user is a part of on ldap
204 * @param string $userName
206 * @throws LdapException
208 public function getUserGroups($userName)
210 $groupsAttr = $this->config['group_attribute'];
211 $user = $this->getUserWithAttributes($userName, [$groupsAttr]);
213 if ($user === null) {
217 $userGroups = $this->groupFilter($user);
218 $userGroups = $this->getGroupsRecursive($userGroups, []);
223 * Get the parent groups of an array of groups
224 * @param array $groupsArray
225 * @param array $checked
227 * @throws LdapException
229 private function getGroupsRecursive($groupsArray, $checked)
232 foreach ($groupsArray as $groupName) {
233 if (in_array($groupName, $checked)) {
237 $groupsToAdd = $this->getGroupGroups($groupName);
238 $groups_to_add = array_merge($groups_to_add, $groupsToAdd);
239 $checked[] = $groupName;
241 $groupsArray = array_unique(array_merge($groupsArray, $groups_to_add), SORT_REGULAR);
243 if (!empty($groups_to_add)) {
244 return $this->getGroupsRecursive($groupsArray, $checked);
251 * Get the parent groups of a single group
252 * @param string $groupName
254 * @throws LdapException
256 private function getGroupGroups($groupName)
258 $ldapConnection = $this->getConnection();
259 $this->bindSystemUser($ldapConnection);
261 $followReferrals = $this->config['follow_referrals'] ? 1 : 0;
262 $this->ldap->setOption($ldapConnection, LDAP_OPT_REFERRALS, $followReferrals);
264 $baseDn = $this->config['base_dn'];
265 $groupsAttr = strtolower($this->config['group_attribute']);
267 $groups = $this->ldap->searchAndGetEntries($ldapConnection, $baseDn, 'CN='.$groupName, [$groupsAttr]);
268 if ($groups['count'] === 0) {
272 $groupGroups = $this->groupFilter($groups[0]);
277 * Filter out LDAP CN and DN language in a ldap search return
278 * Gets the base CN (common name) of the string
279 * @param string $ldapSearchReturn
282 protected function groupFilter($ldapSearchReturn)
284 $groupsAttr = strtolower($this->config['group_attribute']);
287 if (isset($ldapSearchReturn[$groupsAttr]['count'])) {
288 $count = (int) $ldapSearchReturn[$groupsAttr]['count'];
290 for ($i=0; $i<$count; $i++) {
291 $dnComponents = ldap_explode_dn($ldapSearchReturn[$groupsAttr][$i], 1);
292 if (!in_array($dnComponents[0], $ldapGroups)) {
293 $ldapGroups[] = $dnComponents[0];
300 * Sync the LDAP groups to the user roles for the current user
301 * @param \BookStack\User $user
302 * @throws LdapException
304 public function syncGroups(User $user)
306 $userLdapGroups = $this->getUserGroups($user->external_auth_id);
308 // Get the ids for the roles from the names
309 $ldapGroupsAsRoles = $this->matchLdapGroupsToSystemsRoles($userLdapGroups);
312 if ($this->config['remove_from_groups']) {
313 $user->roles()->sync($ldapGroupsAsRoles);
314 $this->userRepo->attachDefaultRole($user);
316 $user->roles()->syncWithoutDetaching($ldapGroupsAsRoles);
321 * Match an array of group names from LDAP to BookStack system roles.
322 * Formats LDAP group names to be lower-case and hyphenated.
323 * @param array $groupNames
324 * @return \Illuminate\Support\Collection
326 protected function matchLdapGroupsToSystemsRoles(array $groupNames)
328 foreach ($groupNames as $i => $groupName) {
329 $groupNames[$i] = str_replace(' ', '-', trim(strtolower($groupName)));
332 $roles = Role::query()->where(function(Builder $query) use ($groupNames) {
333 $query->whereIn('name', $groupNames);
334 foreach ($groupNames as $groupName) {
335 $query->orWhere('external_auth_id', 'LIKE', '%' . $groupName . '%');
339 $matchedRoles = $roles->filter(function(Role $role) use ($groupNames) {
340 return $this->roleMatchesGroupNames($role, $groupNames);
343 return $matchedRoles->pluck('id');
347 * Check a role against an array of group names to see if it matches.
348 * Checked against role 'external_auth_id' if set otherwise the name of the role.
350 * @param array $groupNames
353 protected function roleMatchesGroupNames(Role $role, array $groupNames)
355 if ($role->external_auth_id) {
356 $externalAuthIds = explode(',', strtolower($role->external_auth_id));
357 foreach ($externalAuthIds as $externalAuthId) {
358 if (in_array(trim($externalAuthId), $groupNames)) {
365 $roleName = str_replace(' ', '-', trim(strtolower($role->display_name)));
366 return in_array($roleName, $groupNames);