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