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