]> BookStack Code Mirror - bookstack/blob - app/Repos/LdapRepo.php
Added tests to cover ldap group mapping
[bookstack] / app / Repos / LdapRepo.php
1 <?php namespace BookStack\Repos;
2
3 use BookStack\Services\LdapService;
4 use BookStack\Role;
5
6 class LdapRepo
7 {
8
9     protected $ldap = null;
10     protected $ldapService = null;
11
12     protected $config;
13
14     /**
15      * LdapRepo constructor.
16      * @param \BookStack\Repos\UserRepo $userRepo
17      * @param LdapService $ldapService
18      */
19     public function __construct(UserRepo $userRepo, LdapService $ldapService)
20     {
21         $this->config = config('services.ldap');
22
23         if (config('auth.method') !== 'ldap') {
24             return false;
25         }
26
27         $this->ldapService = $ldapService;
28         $this->userRepo = $userRepo;
29     }
30
31     /**
32      * If there is no ldap connection, all methods calls to this library will return null
33      */
34     public function __call($method, $arguments)
35     {
36         if ($this->ldap === null) {
37             return null;
38         }
39
40         return call_user_func_array(array($this,$method), $arguments);
41     }
42
43     /**
44      * Sync the LDAP groups to the user roles for the current user
45      * @param \BookStack\User $user
46      * @param string $userName
47      * @throws \BookStack\Exceptions\NotFoundException
48      */
49     public function syncGroups($user, $userName)
50     {
51         $userLdapGroups = $this->ldapService->getUserGroups($userName);
52         $userLdapGroups = $this->groupNameFilter($userLdapGroups);
53         // get the ids for the roles from the names
54         $ldapGroupsAsRoles = Role::whereIn('name', $userLdapGroups)->pluck('id');
55         // sync groups
56         if ($this->config['remove_from_groups']) {
57             $user->roles()->sync($ldapGroupsAsRoles);
58             $this->userRepo->attachDefaultRole($user);
59         } else {
60             $user->roles()->syncWithoutDetaching($ldapGroupsAsRoles);
61         }
62
63         // make the user an admin?
64         if (in_array($this->config['admin'], $userLdapGroups)) {
65             $this->userRepo->attachSystemRole($user, 'admin');
66         }
67     }
68
69     /**
70      * Filter to convert the groups from ldap to the format of the roles name on BookStack
71      * Spaces replaced with -, all lowercase letters
72      * @param array $groups
73      * @return array
74      */
75     private function groupNameFilter($groups)
76     {
77         $return = [];
78         foreach ($groups as $groupName) {
79             $return[] = str_replace(' ', '-', strtolower($groupName));
80         }
81         return $return;
82     }
83 }