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