]> BookStack Code Mirror - bookstack/blob - app/Permissions/PermissionApplicator.php
Notifications: Switched testing from string to reference levels
[bookstack] / app / Permissions / PermissionApplicator.php
1 <?php
2
3 namespace BookStack\Permissions;
4
5 use BookStack\App\Model;
6 use BookStack\Entities\Models\Entity;
7 use BookStack\Entities\Models\Page;
8 use BookStack\Permissions\Models\EntityPermission;
9 use BookStack\Users\Models\HasCreatorAndUpdater;
10 use BookStack\Users\Models\HasOwner;
11 use BookStack\Users\Models\User;
12 use Illuminate\Database\Eloquent\Builder;
13 use Illuminate\Database\Query\Builder as QueryBuilder;
14 use InvalidArgumentException;
15
16 class PermissionApplicator
17 {
18     public function __construct(
19         protected ?User $user = null
20     ) {
21     }
22
23     /**
24      * Checks if an entity has a restriction set upon it.
25      *
26      * @param HasCreatorAndUpdater|HasOwner $ownable
27      */
28     public function checkOwnableUserAccess(Model $ownable, string $permission): bool
29     {
30         $explodedPermission = explode('-', $permission);
31         $action = $explodedPermission[1] ?? $explodedPermission[0];
32         $fullPermission = count($explodedPermission) > 1 ? $permission : $ownable->getMorphClass() . '-' . $permission;
33
34         $user = $this->currentUser();
35         $userRoleIds = $this->getCurrentUserRoleIds();
36
37         $allRolePermission = $user->can($fullPermission . '-all');
38         $ownRolePermission = $user->can($fullPermission . '-own');
39         $nonJointPermissions = ['restrictions', 'image', 'attachment', 'comment'];
40         $ownerField = ($ownable instanceof Entity) ? 'owned_by' : 'created_by';
41         $ownableFieldVal = $ownable->getAttribute($ownerField);
42
43         if (is_null($ownableFieldVal)) {
44             throw new InvalidArgumentException("{$ownerField} field used but has not been loaded");
45         }
46
47         $isOwner = $user->id === $ownableFieldVal;
48         $hasRolePermission = $allRolePermission || ($isOwner && $ownRolePermission);
49
50         // Handle non entity specific jointPermissions
51         if (in_array($explodedPermission[0], $nonJointPermissions)) {
52             return $hasRolePermission;
53         }
54
55         $hasApplicableEntityPermissions = $this->hasEntityPermission($ownable, $userRoleIds, $action);
56
57         return is_null($hasApplicableEntityPermissions) ? $hasRolePermission : $hasApplicableEntityPermissions;
58     }
59
60     /**
61      * Check if there are permissions that are applicable for the given entity item, action and roles.
62      * Returns null when no entity permissions are in force.
63      */
64     protected function hasEntityPermission(Entity $entity, array $userRoleIds, string $action): ?bool
65     {
66         $this->ensureValidEntityAction($action);
67
68         return (new EntityPermissionEvaluator($action))->evaluateEntityForUser($entity, $userRoleIds);
69     }
70
71     /**
72      * Checks if a user has the given permission for any items in the system.
73      * Can be passed an entity instance to filter on a specific type.
74      */
75     public function checkUserHasEntityPermissionOnAny(string $action, string $entityClass = ''): bool
76     {
77         $this->ensureValidEntityAction($action);
78
79         $permissionQuery = EntityPermission::query()
80             ->where($action, '=', true)
81             ->whereIn('role_id', $this->getCurrentUserRoleIds());
82
83         if (!empty($entityClass)) {
84             /** @var Entity $entityInstance */
85             $entityInstance = app()->make($entityClass);
86             $permissionQuery = $permissionQuery->where('entity_type', '=', $entityInstance->getMorphClass());
87         }
88
89         $hasPermission = $permissionQuery->count() > 0;
90
91         return $hasPermission;
92     }
93
94     /**
95      * Limit the given entity query so that the query will only
96      * return items that the user has view permission for.
97      */
98     public function restrictEntityQuery(Builder $query): Builder
99     {
100         return $query->where(function (Builder $parentQuery) {
101             $parentQuery->whereHas('jointPermissions', function (Builder $permissionQuery) {
102                 $permissionQuery->select(['entity_id', 'entity_type'])
103                     ->selectRaw('max(owner_id) as owner_id')
104                     ->selectRaw('max(status) as status')
105                     ->whereIn('role_id', $this->getCurrentUserRoleIds())
106                     ->groupBy(['entity_type', 'entity_id'])
107                     ->havingRaw('(status IN (1, 3) or (owner_id = ? and status != 2))', [$this->currentUser()->id]);
108             });
109         });
110     }
111
112     /**
113      * Extend the given page query to ensure draft items are not visible
114      * unless created by the given user.
115      */
116     public function restrictDraftsOnPageQuery(Builder $query): Builder
117     {
118         return $query->where(function (Builder $query) {
119             $query->where('draft', '=', false)
120                 ->orWhere(function (Builder $query) {
121                     $query->where('draft', '=', true)
122                         ->where('owned_by', '=', $this->currentUser()->id);
123                 });
124         });
125     }
126
127     /**
128      * Filter items that have entities set as a polymorphic relation.
129      * For simplicity, this will not return results attached to draft pages.
130      * Draft pages should never really have related items though.
131      */
132     public function restrictEntityRelationQuery(Builder $query, string $tableName, string $entityIdColumn, string $entityTypeColumn): Builder
133     {
134         $tableDetails = ['tableName' => $tableName, 'entityIdColumn' => $entityIdColumn, 'entityTypeColumn' => $entityTypeColumn];
135         $pageMorphClass = (new Page())->getMorphClass();
136
137         return $this->restrictEntityQuery($query)
138             ->where(function ($query) use ($tableDetails, $pageMorphClass) {
139                 /** @var Builder $query */
140                 $query->where($tableDetails['entityTypeColumn'], '!=', $pageMorphClass)
141                 ->orWhereExists(function (QueryBuilder $query) use ($tableDetails, $pageMorphClass) {
142                     $query->select('id')->from('pages')
143                         ->whereColumn('pages.id', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
144                         ->where($tableDetails['tableName'] . '.' . $tableDetails['entityTypeColumn'], '=', $pageMorphClass)
145                         ->where('pages.draft', '=', false);
146                 });
147             });
148     }
149
150     /**
151      * Add conditions to a query for a model that's a relation of a page, so only the model results
152      * on visible pages are returned by the query.
153      * Is effectively the same as "restrictEntityRelationQuery" but takes into account page drafts
154      * while not expecting a polymorphic relation, Just a simpler one-page-to-many-relations set-up.
155      */
156     public function restrictPageRelationQuery(Builder $query, string $tableName, string $pageIdColumn): Builder
157     {
158         $fullPageIdColumn = $tableName . '.' . $pageIdColumn;
159         return $this->restrictEntityQuery($query)
160             ->where(function ($query) use ($fullPageIdColumn) {
161                 /** @var Builder $query */
162                 $query->whereExists(function (QueryBuilder $query) use ($fullPageIdColumn) {
163                     $query->select('id')->from('pages')
164                         ->whereColumn('pages.id', '=', $fullPageIdColumn)
165                         ->where('pages.draft', '=', false);
166                 })->orWhereExists(function (QueryBuilder $query) use ($fullPageIdColumn) {
167                     $query->select('id')->from('pages')
168                         ->whereColumn('pages.id', '=', $fullPageIdColumn)
169                         ->where('pages.draft', '=', true)
170                         ->where('pages.created_by', '=', $this->currentUser()->id);
171                 });
172             });
173     }
174
175     /**
176      * Get the current user.
177      */
178     protected function currentUser(): User
179     {
180         return $this->user ?? user();
181     }
182
183     /**
184      * Get the roles for the current logged-in user.
185      *
186      * @return int[]
187      */
188     protected function getCurrentUserRoleIds(): array
189     {
190         return $this->currentUser()->roles->pluck('id')->values()->all();
191     }
192
193     /**
194      * Ensure the given action is a valid and expected entity action.
195      * Throws an exception if invalid otherwise does nothing.
196      * @throws InvalidArgumentException
197      */
198     protected function ensureValidEntityAction(string $action): void
199     {
200         if (!in_array($action, EntityPermission::PERMISSIONS)) {
201             throw new InvalidArgumentException('Action should be a simple entity permission action, not a role permission');
202         }
203     }
204 }