Debian Codegraph @

library/Toplevelview/Util/Auth.php

raw
1 <?php
2
3 namespace Icinga\Module\Toplevelview\Util;
4
5 use Icinga\Authentication\Auth as IcingaAuth;
6 use Icinga\Security\SecurityException;
7 use ipl\Stdlib\Filter;
8 use ipl\Stdlib\Str;
9
10 /**
11 * Auth adds methods for handling permissions/restrictions
12 */
13 trait Auth
14 {
15 public function getAuth()
16 {
17 return IcingaAuth::getInstance();
18 }
19
20 /**
21 * assertAccessToView asserts that the current user has permission
22 * for the given view. Throws a SecurityException if not.
23 *
24 * @throws SecurityException
25 */
26 public function assertAccessToView($restrictions, $name): bool
27 {
28 $user = $this->getAuth()->getUser();
29
30 // If the user is unrestricted no restrictions apply
31 if ($user->isUnrestricted()) {
32 return true;
33 }
34
35 if ($restrictions->isEmpty()) {
36 return true;
37 }
38
39 if (Filter::match($restrictions, ['name' => $name])) {
40 return true;
41 }
42
43 throw new SecurityException('No permission for %s', $name);
44 }
45
46 /**
47 * assertAccessToView asserts that the current user has permission
48 * for the given view. Returns false if not
49 */
50 public function hasAccessToView($restrictions, $name): bool
51 {
52 $user = $this->getAuth()->getUser();
53
54 // If the user is unrestricted no restrictions apply
55 if ($user->isUnrestricted()) {
56 return true;
57 }
58
59 if ($restrictions->isEmpty()) {
60 return true;
61 }
62
63 return Filter::match($restrictions, ['name' => $name]);
64 }
65
66 /**
67 * getRestrictions returns the current user's restrictions.
68 */
69 public function getRestrictions($name = 'toplevelview/filter/views')
70 {
71 $user = $this->getAuth()->getUser();
72
73 // The final filter that is applied to the query.
74 // Any means any filter has to match
75 $f = Filter::any();
76
77 // For each of the user's roles add the given restrictions
78 foreach ($user->getRoles() as $role) {
79 // All means ALL filters have to match
80 $roleFilter = Filter::any();
81 // Load the restrictions for the user's role and parse them into a filter
82 $restriction = $role->getRestrictions($name);
83
84 if ($restriction) {
85 // Parse the given restriction and return a Filter\Rule
86 $res = Str::trimSplit($restriction);
87 foreach ($res as $r) {
88 // Add the new Rule to the role filter
89 $roleFilter->add(Filter::equal('name', $r));
90 }
91 }
92 // Add the filter to the overall filter
93 if (! $roleFilter->isEmpty()) {
94 $f->add($roleFilter);
95 }
96 }
97
98 return $f;
99 }
100 }