]> BookStack Code Mirror - bookstack/blob - app/Auth/Permissions/PermissionApplicator.php
Addressed additional unsupported array spread operation
[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         $this->ensureValidEntityAction($action);
63
64         $adminRoleId = Role::getSystemRole('admin')->id;
65         if (in_array($adminRoleId, $userRoleIds)) {
66             return true;
67         }
68
69         // The chain order here is very important due to the fact we walk up the chain
70         // in the loop below. Earlier items in the chain have higher priority.
71         $chain = [$entity];
72         if ($entity instanceof Page && $entity->chapter_id) {
73             $chain[] = $entity->chapter;
74         }
75
76         if ($entity instanceof Page || $entity instanceof Chapter) {
77             $chain[] = $entity->book;
78         }
79
80         foreach ($chain as $currentEntity) {
81             $allowedByRoleId = $currentEntity->permissions()
82                 ->whereIn('role_id', [0, ...$userRoleIds])
83                 ->pluck($action, 'role_id');
84
85             // Continue up the chain if no applicable entity permission overrides.
86             if ($allowedByRoleId->isEmpty()) {
87                 continue;
88             }
89
90             // If we have user-role-specific permissions set, allow if any of those
91             // role permissions allow access.
92             $hasDefault = $allowedByRoleId->has(0);
93             if (!$hasDefault || $allowedByRoleId->count() > 1) {
94                 return $allowedByRoleId->search(function (bool $allowed, int $roleId) {
95                         return $roleId !== 0 && $allowed;
96                 }) !== false;
97             }
98
99             // Otherwise, return the default "Other roles" fallback value.
100             return $allowedByRoleId->get(0);
101         }
102
103         return null;
104     }
105
106     /**
107      * Checks if a user has the given permission for any items in the system.
108      * Can be passed an entity instance to filter on a specific type.
109      */
110     public function checkUserHasEntityPermissionOnAny(string $action, string $entityClass = ''): bool
111     {
112         $this->ensureValidEntityAction($action);
113
114         $permissionQuery = EntityPermission::query()
115             ->where($action, '=', true)
116             ->whereIn('role_id', $this->getCurrentUserRoleIds());
117
118         if (!empty($entityClass)) {
119             /** @var Entity $entityInstance */
120             $entityInstance = app()->make($entityClass);
121             $permissionQuery = $permissionQuery->where('entity_type', '=', $entityInstance->getMorphClass());
122         }
123
124         $hasPermission = $permissionQuery->count() > 0;
125
126         return $hasPermission;
127     }
128
129     /**
130      * Limit the given entity query so that the query will only
131      * return items that the user has view permission for.
132      */
133     public function restrictEntityQuery(Builder $query): Builder
134     {
135         return $query->where(function (Builder $parentQuery) {
136             $parentQuery->whereHas('jointPermissions', function (Builder $permissionQuery) {
137                 $permissionQuery->whereIn('role_id', $this->getCurrentUserRoleIds())
138                     ->where(function (Builder $query) {
139                         $this->addJointHasPermissionCheck($query, $this->currentUser()->id);
140                     });
141             });
142         });
143     }
144
145     /**
146      * Extend the given page query to ensure draft items are not visible
147      * unless created by the given user.
148      */
149     public function restrictDraftsOnPageQuery(Builder $query): Builder
150     {
151         return $query->where(function (Builder $query) {
152             $query->where('draft', '=', false)
153                 ->orWhere(function (Builder $query) {
154                     $query->where('draft', '=', true)
155                         ->where('owned_by', '=', $this->currentUser()->id);
156                 });
157         });
158     }
159
160     /**
161      * Filter items that have entities set as a polymorphic relation.
162      * For simplicity, this will not return results attached to draft pages.
163      * Draft pages should never really have related items though.
164      *
165      * @param Builder|QueryBuilder $query
166      */
167     public function restrictEntityRelationQuery($query, string $tableName, string $entityIdColumn, string $entityTypeColumn)
168     {
169         $tableDetails = ['tableName' => $tableName, 'entityIdColumn' => $entityIdColumn, 'entityTypeColumn' => $entityTypeColumn];
170         $pageMorphClass = (new Page())->getMorphClass();
171
172         $q = $query->whereExists(function ($permissionQuery) use (&$tableDetails) {
173             /** @var Builder $permissionQuery */
174             $permissionQuery->select(['role_id'])->from('joint_permissions')
175                 ->whereColumn('joint_permissions.entity_id', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
176                 ->whereColumn('joint_permissions.entity_type', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityTypeColumn'])
177                 ->whereIn('joint_permissions.role_id', $this->getCurrentUserRoleIds())
178                 ->where(function (QueryBuilder $query) {
179                     $this->addJointHasPermissionCheck($query, $this->currentUser()->id);
180                 });
181         })->where(function ($query) use ($tableDetails, $pageMorphClass) {
182             /** @var Builder $query */
183             $query->where($tableDetails['entityTypeColumn'], '!=', $pageMorphClass)
184                 ->orWhereExists(function (QueryBuilder $query) use ($tableDetails, $pageMorphClass) {
185                     $query->select('id')->from('pages')
186                         ->whereColumn('pages.id', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
187                         ->where($tableDetails['tableName'] . '.' . $tableDetails['entityTypeColumn'], '=', $pageMorphClass)
188                         ->where('pages.draft', '=', false);
189                 });
190         });
191
192         return $q;
193     }
194
195     /**
196      * Add conditions to a query for a model that's a relation of a page, so only the model results
197      * on visible pages are returned by the query.
198      * Is effectively the same as "restrictEntityRelationQuery" but takes into account page drafts
199      * while not expecting a polymorphic relation, Just a simpler one-page-to-many-relations set-up.
200      */
201     public function restrictPageRelationQuery(Builder $query, string $tableName, string $pageIdColumn): Builder
202     {
203         $fullPageIdColumn = $tableName . '.' . $pageIdColumn;
204         $morphClass = (new Page())->getMorphClass();
205
206         $existsQuery = function ($permissionQuery) use ($fullPageIdColumn, $morphClass) {
207             /** @var Builder $permissionQuery */
208             $permissionQuery->select('joint_permissions.role_id')->from('joint_permissions')
209                 ->whereColumn('joint_permissions.entity_id', '=', $fullPageIdColumn)
210                 ->where('joint_permissions.entity_type', '=', $morphClass)
211                 ->whereIn('joint_permissions.role_id', $this->getCurrentUserRoleIds())
212                 ->where(function (QueryBuilder $query) {
213                     $this->addJointHasPermissionCheck($query, $this->currentUser()->id);
214                 });
215         };
216
217         $q = $query->where(function ($query) use ($existsQuery, $fullPageIdColumn) {
218             $query->whereExists($existsQuery)
219                 ->orWhere($fullPageIdColumn, '=', 0);
220         });
221
222         // Prevent visibility of non-owned draft pages
223         $q->whereExists(function (QueryBuilder $query) use ($fullPageIdColumn) {
224             $query->select('id')->from('pages')
225                 ->whereColumn('pages.id', '=', $fullPageIdColumn)
226                 ->where(function (QueryBuilder $query) {
227                     $query->where('pages.draft', '=', false)
228                         ->orWhere('pages.owned_by', '=', $this->currentUser()->id);
229                 });
230         });
231
232         return $q;
233     }
234
235     /**
236      * Add the query for checking the given user id has permission
237      * within the join_permissions table.
238      *
239      * @param QueryBuilder|Builder $query
240      */
241     protected function addJointHasPermissionCheck($query, int $userIdToCheck)
242     {
243         $query->where('joint_permissions.has_permission', '=', true)->orWhere(function ($query) use ($userIdToCheck) {
244             $query->where('joint_permissions.has_permission_own', '=', true)
245                 ->where('joint_permissions.owned_by', '=', $userIdToCheck);
246         });
247     }
248
249     /**
250      * Get the current user.
251      */
252     protected function currentUser(): User
253     {
254         return user();
255     }
256
257     /**
258      * Get the roles for the current logged-in user.
259      *
260      * @return int[]
261      */
262     protected function getCurrentUserRoleIds(): array
263     {
264         if (auth()->guest()) {
265             return [Role::getSystemRole('public')->id];
266         }
267
268         return $this->currentUser()->roles->pluck('id')->values()->all();
269     }
270
271     /**
272      * Ensure the given action is a valid and expected entity action.
273      * Throws an exception if invalid otherwise does nothing.
274      * @throws InvalidArgumentException
275      */
276     protected function ensureValidEntityAction(string $action): void
277     {
278         if (!in_array($action, EntityPermission::PERMISSIONS)) {
279             throw new InvalidArgumentException('Action should be a simple entity permission action, not a role permission');
280         }
281     }
282 }