]> BookStack Code Mirror - bookstack/blob - app/Auth/Permissions/PermissionApplicator.php
Only output hidden user filters when not set to 'me'
[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             if (is_null($currentEntity->restricted)) {
78                 throw new InvalidArgumentException('Entity restricted field used but has not been loaded');
79             }
80
81             if ($currentEntity->restricted) {
82                 return $currentEntity->permissions()
83                     ->whereIn('role_id', $userRoleIds)
84                     ->where('action', '=', $action)
85                     ->count() > 0;
86             }
87         }
88
89         return null;
90     }
91
92     /**
93      * Checks if a user has the given permission for any items in the system.
94      * Can be passed an entity instance to filter on a specific type.
95      */
96     public function checkUserHasEntityPermissionOnAny(string $action, string $entityClass = ''): bool
97     {
98         if (strpos($action, '-') !== false) {
99             throw new InvalidArgumentException('Action should be a simple entity permission action, not a role permission');
100         }
101
102         $permissionQuery = EntityPermission::query()
103             ->where('action', '=', $action)
104             ->whereIn('role_id', $this->getCurrentUserRoleIds());
105
106         if (!empty($entityClass)) {
107             /** @var Entity $entityInstance */
108             $entityInstance = app()->make($entityClass);
109             $permissionQuery = $permissionQuery->where('restrictable_type', '=', $entityInstance->getMorphClass());
110         }
111
112         $hasPermission = $permissionQuery->count() > 0;
113
114         return $hasPermission;
115     }
116
117     /**
118      * Limit the given entity query so that the query will only
119      * return items that the user has view permission for.
120      */
121     public function restrictEntityQuery(Builder $query): Builder
122     {
123         return $query->where(function (Builder $parentQuery) {
124             $parentQuery->whereHas('jointPermissions', function (Builder $permissionQuery) {
125                 $permissionQuery->whereIn('role_id', $this->getCurrentUserRoleIds())
126                     ->where(function (Builder $query) {
127                         $this->addJointHasPermissionCheck($query, $this->currentUser()->id);
128                     });
129             });
130         });
131     }
132
133     /**
134      * Extend the given page query to ensure draft items are not visible
135      * unless created by the given user.
136      */
137     public function restrictDraftsOnPageQuery(Builder $query): Builder
138     {
139         return $query->where(function (Builder $query) {
140             $query->where('draft', '=', false)
141                 ->orWhere(function (Builder $query) {
142                     $query->where('draft', '=', true)
143                         ->where('owned_by', '=', $this->currentUser()->id);
144                 });
145         });
146     }
147
148     /**
149      * Filter items that have entities set as a polymorphic relation.
150      * For simplicity, this will not return results attached to draft pages.
151      * Draft pages should never really have related items though.
152      *
153      * @param Builder|QueryBuilder $query
154      */
155     public function restrictEntityRelationQuery($query, string $tableName, string $entityIdColumn, string $entityTypeColumn)
156     {
157         $tableDetails = ['tableName' => $tableName, 'entityIdColumn' => $entityIdColumn, 'entityTypeColumn' => $entityTypeColumn];
158         $pageMorphClass = (new Page())->getMorphClass();
159
160         $q = $query->whereExists(function ($permissionQuery) use (&$tableDetails) {
161             /** @var Builder $permissionQuery */
162             $permissionQuery->select(['role_id'])->from('joint_permissions')
163                 ->whereColumn('joint_permissions.entity_id', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
164                 ->whereColumn('joint_permissions.entity_type', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityTypeColumn'])
165                 ->whereIn('joint_permissions.role_id', $this->getCurrentUserRoleIds())
166                 ->where(function (QueryBuilder $query) {
167                     $this->addJointHasPermissionCheck($query, $this->currentUser()->id);
168                 });
169         })->where(function ($query) use ($tableDetails, $pageMorphClass) {
170             /** @var Builder $query */
171             $query->where($tableDetails['entityTypeColumn'], '!=', $pageMorphClass)
172                 ->orWhereExists(function (QueryBuilder $query) use ($tableDetails, $pageMorphClass) {
173                     $query->select('id')->from('pages')
174                         ->whereColumn('pages.id', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
175                         ->where($tableDetails['tableName'] . '.' . $tableDetails['entityTypeColumn'], '=', $pageMorphClass)
176                         ->where('pages.draft', '=', false);
177                 });
178         });
179
180         return $q;
181     }
182
183     /**
184      * Add conditions to a query for a model that's a relation of a page, so only the model results
185      * on visible pages are returned by the query.
186      * Is effectively the same as "restrictEntityRelationQuery" but takes into account page drafts
187      * while not expecting a polymorphic relation, Just a simpler one-page-to-many-relations set-up.
188      */
189     public function restrictPageRelationQuery(Builder $query, string $tableName, string $pageIdColumn): Builder
190     {
191         $fullPageIdColumn = $tableName . '.' . $pageIdColumn;
192         $morphClass = (new Page())->getMorphClass();
193
194         $existsQuery = function ($permissionQuery) use ($fullPageIdColumn, $morphClass) {
195             /** @var Builder $permissionQuery */
196             $permissionQuery->select('joint_permissions.role_id')->from('joint_permissions')
197                 ->whereColumn('joint_permissions.entity_id', '=', $fullPageIdColumn)
198                 ->where('joint_permissions.entity_type', '=', $morphClass)
199                 ->whereIn('joint_permissions.role_id', $this->getCurrentUserRoleIds())
200                 ->where(function (QueryBuilder $query) {
201                     $this->addJointHasPermissionCheck($query, $this->currentUser()->id);
202                 });
203         };
204
205         $q = $query->where(function ($query) use ($existsQuery, $fullPageIdColumn) {
206             $query->whereExists($existsQuery)
207                 ->orWhere($fullPageIdColumn, '=', 0);
208         });
209
210         // Prevent visibility of non-owned draft pages
211         $q->whereExists(function (QueryBuilder $query) use ($fullPageIdColumn) {
212             $query->select('id')->from('pages')
213                 ->whereColumn('pages.id', '=', $fullPageIdColumn)
214                 ->where(function (QueryBuilder $query) {
215                     $query->where('pages.draft', '=', false)
216                         ->orWhere('pages.owned_by', '=', $this->currentUser()->id);
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 }