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