]> BookStack Code Mirror - bookstack/blob - app/Auth/Permissions/PermissionApplicator.php
Fixed failed permission checks due to non-loaded fields
[bookstack] / app / Auth / Permissions / PermissionApplicator.php
1 <?php
2
3 namespace BookStack\Auth\Permissions;
4
5 use BookStack\Auth\Role;
6 use BookStack\Auth\User;
7 use BookStack\Entities\Models\Chapter;
8 use BookStack\Entities\Models\Entity;
9 use BookStack\Entities\Models\Page;
10 use BookStack\Model;
11 use BookStack\Traits\HasCreatorAndUpdater;
12 use BookStack\Traits\HasOwner;
13 use Illuminate\Database\Eloquent\Builder;
14 use Illuminate\Database\Query\Builder as QueryBuilder;
15 use InvalidArgumentException;
16
17 class PermissionApplicator
18 {
19     /**
20      * Checks if an entity has a restriction set upon it.
21      *
22      * @param HasCreatorAndUpdater|HasOwner $ownable
23      */
24     public function checkOwnableUserAccess(Model $ownable, string $permission): bool
25     {
26         $explodedPermission = explode('-', $permission);
27         $action = $explodedPermission[1] ?? $explodedPermission[0];
28         $fullPermission = count($explodedPermission) > 1 ? $permission : $ownable->getMorphClass() . '-' . $permission;
29
30         $user = $this->currentUser();
31         $userRoleIds = $this->getCurrentUserRoleIds();
32
33         $allRolePermission = $user->can($fullPermission . '-all');
34         $ownRolePermission = $user->can($fullPermission . '-own');
35         $nonJointPermissions = ['restrictions', 'image', 'attachment', 'comment'];
36         $ownerField = ($ownable instanceof Entity) ? 'owned_by' : 'created_by';
37         $ownableFieldVal = $ownable->getAttribute($ownerField);
38
39         if (is_null($ownableFieldVal)) {
40             throw new InvalidArgumentException("{$ownerField} field used but has not been loaded");
41         }
42
43         $isOwner = $user->id === $ownableFieldVal;
44         $hasRolePermission = $allRolePermission || ($isOwner && $ownRolePermission);
45
46         // Handle non entity specific jointPermissions
47         if (in_array($explodedPermission[0], $nonJointPermissions)) {
48             return $hasRolePermission;
49         }
50
51         $hasApplicableEntityPermissions = $this->hasEntityPermission($ownable, $userRoleIds, $action);
52
53         return is_null($hasApplicableEntityPermissions) ? $hasRolePermission : $hasApplicableEntityPermissions;
54     }
55
56     /**
57      * Check if there are permissions that are applicable for the given entity item, action and roles.
58      * Returns null when no entity permissions are in force.
59      */
60     protected function hasEntityPermission(Entity $entity, array $userRoleIds, string $action): ?bool
61     {
62         $adminRoleId = Role::getSystemRole('admin')->id;
63         if (in_array($adminRoleId, $userRoleIds)) {
64             return true;
65         }
66
67         $chain = [$entity];
68         if ($entity instanceof Page && $entity->chapter_id) {
69             $chain[] = $entity->chapter;
70         }
71
72         if ($entity instanceof Page || $entity instanceof Chapter) {
73             $chain[] = $entity->book;
74         }
75
76         foreach ($chain as $currentEntity) {
77
78             if (is_null($currentEntity->restricted)) {
79                 throw new InvalidArgumentException("Entity restricted field used but has not been loaded");
80             }
81
82             if ($currentEntity->restricted) {
83                 return $currentEntity->permissions()
84                     ->whereIn('role_id', $userRoleIds)
85                     ->where('action', '=', $action)
86                     ->count() > 0;
87             }
88         }
89
90         return null;
91     }
92
93     /**
94      * Checks if a user has the given permission for any items in the system.
95      * Can be passed an entity instance to filter on a specific type.
96      */
97     public function checkUserHasEntityPermissionOnAny(string $action, string $entityClass = ''): bool
98     {
99         if (strpos($action, '-') !== false) {
100             throw new InvalidArgumentException('Action should be a simple entity permission action, not a role permission');
101         }
102
103         $permissionQuery = EntityPermission::query()
104             ->where('action', '=', $action)
105             ->whereIn('role_id', $this->getCurrentUserRoleIds());
106
107         if (!empty($entityClass)) {
108             /** @var Entity $entityInstance */
109             $entityInstance = app()->make($entityClass);
110             $permissionQuery = $permissionQuery->where('restrictable_type', '=', $entityInstance->getMorphClass());
111         }
112
113         $hasPermission = $permissionQuery->count() > 0;
114
115         return $hasPermission;
116     }
117
118     /**
119      * Limit the given entity query so that the query will only
120      * return items that the user has view permission for.
121      */
122     public function restrictEntityQuery(Builder $query): Builder
123     {
124         return $query->where(function (Builder $parentQuery) {
125             $parentQuery->whereHas('jointPermissions', function (Builder $permissionQuery) {
126                 $permissionQuery->whereIn('role_id', $this->getCurrentUserRoleIds())
127                     ->where(function (Builder $query) {
128                         $this->addJointHasPermissionCheck($query, $this->currentUser()->id);
129                     });
130             });
131         });
132     }
133
134     /**
135      * Extend the given page query to ensure draft items are not visible
136      * unless created by the given user.
137      */
138     public function restrictDraftsOnPageQuery(Builder $query): Builder
139     {
140         return $query->where(function (Builder $query) {
141             $query->where('draft', '=', false)
142                 ->orWhere(function (Builder $query) {
143                     $query->where('draft', '=', true)
144                         ->where('owned_by', '=', $this->currentUser()->id);
145                 });
146         });
147     }
148
149     /**
150      * Filter items that have entities set as a polymorphic relation.
151      * For simplicity, this will not return results attached to draft pages.
152      * Draft pages should never really have related items though.
153      *
154      * @param Builder|QueryBuilder $query
155      */
156     public function restrictEntityRelationQuery($query, string $tableName, string $entityIdColumn, string $entityTypeColumn)
157     {
158         $tableDetails = ['tableName' => $tableName, 'entityIdColumn' => $entityIdColumn, 'entityTypeColumn' => $entityTypeColumn];
159         $pageMorphClass = (new Page())->getMorphClass();
160
161         $q = $query->whereExists(function ($permissionQuery) use (&$tableDetails) {
162             /** @var Builder $permissionQuery */
163             $permissionQuery->select(['role_id'])->from('joint_permissions')
164                 ->whereColumn('joint_permissions.entity_id', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
165                 ->whereColumn('joint_permissions.entity_type', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityTypeColumn'])
166                 ->whereIn('joint_permissions.role_id', $this->getCurrentUserRoleIds())
167                 ->where(function (QueryBuilder $query) {
168                     $this->addJointHasPermissionCheck($query, $this->currentUser()->id);
169                 });
170         })->where(function ($query) use ($tableDetails, $pageMorphClass) {
171             /** @var Builder $query */
172             $query->where($tableDetails['entityTypeColumn'], '!=', $pageMorphClass)
173                 ->orWhereExists(function (QueryBuilder $query) use ($tableDetails, $pageMorphClass) {
174                     $query->select('id')->from('pages')
175                         ->whereColumn('pages.id', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
176                         ->where($tableDetails['tableName'] . '.' . $tableDetails['entityTypeColumn'], '=', $pageMorphClass)
177                         ->where('pages.draft', '=', false);
178                 });
179         });
180
181         return $q;
182     }
183
184     /**
185      * Add conditions to a query for a model that's a relation of a page, so only the model results
186      * on visible pages are returned by the query.
187      * Is effectively the same as "restrictEntityRelationQuery" but takes into account page drafts
188      * while not expecting a polymorphic relation, Just a simpler one-page-to-many-relations set-up.
189      */
190     public function restrictPageRelationQuery(Builder $query, string $tableName, string $pageIdColumn): Builder
191     {
192         $fullPageIdColumn = $tableName . '.' . $pageIdColumn;
193         $morphClass = (new Page())->getMorphClass();
194
195         $existsQuery = function ($permissionQuery) use ($fullPageIdColumn, $morphClass) {
196             /** @var Builder $permissionQuery */
197             $permissionQuery->select('joint_permissions.role_id')->from('joint_permissions')
198                 ->whereColumn('joint_permissions.entity_id', '=', $fullPageIdColumn)
199                 ->where('joint_permissions.entity_type', '=', $morphClass)
200                 ->whereIn('joint_permissions.role_id', $this->getCurrentUserRoleIds())
201                 ->where(function (QueryBuilder $query) {
202                     $this->addJointHasPermissionCheck($query, $this->currentUser()->id);
203                 });
204         };
205
206         $q = $query->where(function ($query) use ($existsQuery, $fullPageIdColumn) {
207             $query->whereExists($existsQuery)
208                 ->orWhere($fullPageIdColumn, '=', 0);
209         });
210
211         // Prevent visibility of non-owned draft pages
212         $q->whereExists(function (QueryBuilder $query) use ($fullPageIdColumn) {
213             $query->select('id')->from('pages')
214                 ->whereColumn('pages.id', '=', $fullPageIdColumn)
215                 ->where(function (QueryBuilder $query) {
216                     $query->where('pages.draft', '=', false)
217                         ->orWhere('pages.owned_by', '=', $this->currentUser()->id);
218                 });
219         });
220
221         return $q;
222     }
223
224     /**
225      * Add the query for checking the given user id has permission
226      * within the join_permissions table.
227      *
228      * @param QueryBuilder|Builder $query
229      */
230     protected function addJointHasPermissionCheck($query, int $userIdToCheck)
231     {
232         $query->where('joint_permissions.has_permission', '=', true)->orWhere(function ($query) use ($userIdToCheck) {
233             $query->where('joint_permissions.has_permission_own', '=', true)
234                 ->where('joint_permissions.owned_by', '=', $userIdToCheck);
235         });
236     }
237
238     /**
239      * Get the current user.
240      */
241     protected function currentUser(): User
242     {
243         return user();
244     }
245
246     /**
247      * Get the roles for the current logged-in user.
248      *
249      * @return int[]
250      */
251     protected function getCurrentUserRoleIds(): array
252     {
253         if (auth()->guest()) {
254             return [Role::getSystemRole('public')->id];
255         }
256
257         return $this->currentUser()->roles->pluck('id')->values()->all();
258     }
259 }