]> BookStack Code Mirror - bookstack/blob - app/Auth/Permissions/PermissionApplicator.php
Merge pull request #3556 from GongMingCai/development
[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                     ->where(function (Builder $query) {
117                         $this->addJointHasPermissionCheck($query, $this->currentUser()->id);
118                     });
119             });
120         });
121     }
122
123     /**
124      * Extend the given page query to ensure draft items are not visible
125      * unless created by the given user.
126      */
127     public function restrictDraftsOnPageQuery(Builder $query): Builder
128     {
129         return $query->where(function (Builder $query) {
130             $query->where('draft', '=', false)
131                 ->orWhere(function (Builder $query) {
132                     $query->where('draft', '=', true)
133                         ->where('owned_by', '=', $this->currentUser()->id);
134                 });
135         });
136     }
137
138     /**
139      * Filter items that have entities set as a polymorphic relation.
140      * For simplicity, this will not return results attached to draft pages.
141      * Draft pages should never really have related items though.
142      *
143      * @param Builder|QueryBuilder $query
144      */
145     public function restrictEntityRelationQuery($query, string $tableName, string $entityIdColumn, string $entityTypeColumn)
146     {
147         $tableDetails = ['tableName' => $tableName, 'entityIdColumn' => $entityIdColumn, 'entityTypeColumn' => $entityTypeColumn];
148         $pageMorphClass = (new Page())->getMorphClass();
149
150         $q = $query->whereExists(function ($permissionQuery) use (&$tableDetails) {
151             /** @var Builder $permissionQuery */
152             $permissionQuery->select(['role_id'])->from('joint_permissions')
153                 ->whereColumn('joint_permissions.entity_id', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
154                 ->whereColumn('joint_permissions.entity_type', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityTypeColumn'])
155                 ->whereIn('joint_permissions.role_id', $this->getCurrentUserRoleIds())
156                 ->where(function (QueryBuilder $query) {
157                     $this->addJointHasPermissionCheck($query, $this->currentUser()->id);
158                 });
159         })->where(function ($query) use ($tableDetails, $pageMorphClass) {
160             /** @var Builder $query */
161             $query->where($tableDetails['entityTypeColumn'], '!=', $pageMorphClass)
162                 ->orWhereExists(function (QueryBuilder $query) use ($tableDetails, $pageMorphClass) {
163                     $query->select('id')->from('pages')
164                         ->whereColumn('pages.id', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
165                         ->where($tableDetails['tableName'] . '.' . $tableDetails['entityTypeColumn'], '=', $pageMorphClass)
166                         ->where('pages.draft', '=', false);
167                 });
168         });
169
170         return $q;
171     }
172
173     /**
174      * Add conditions to a query for a model that's a relation of a page, so only the model results
175      * on visible pages are returned by the query.
176      * Is effectively the same as "restrictEntityRelationQuery" but takes into account page drafts
177      * while not expecting a polymorphic relation, Just a simpler one-page-to-many-relations set-up.
178      */
179     public function restrictPageRelationQuery(Builder $query, string $tableName, string $pageIdColumn): Builder
180     {
181         $fullPageIdColumn = $tableName . '.' . $pageIdColumn;
182         $morphClass = (new Page())->getMorphClass();
183
184         $existsQuery = function ($permissionQuery) use ($fullPageIdColumn, $morphClass) {
185             /** @var Builder $permissionQuery */
186             $permissionQuery->select('joint_permissions.role_id')->from('joint_permissions')
187                 ->whereColumn('joint_permissions.entity_id', '=', $fullPageIdColumn)
188                 ->where('joint_permissions.entity_type', '=', $morphClass)
189                 ->whereIn('joint_permissions.role_id', $this->getCurrentUserRoleIds())
190                 ->where(function (QueryBuilder $query) {
191                     $this->addJointHasPermissionCheck($query, $this->currentUser()->id);
192                 });
193         };
194
195         $q = $query->where(function ($query) use ($existsQuery, $fullPageIdColumn) {
196             $query->whereExists($existsQuery)
197                 ->orWhere($fullPageIdColumn, '=', 0);
198         });
199
200         // Prevent visibility of non-owned draft pages
201         $q->whereExists(function (QueryBuilder $query) use ($fullPageIdColumn) {
202             $query->select('id')->from('pages')
203                 ->whereColumn('pages.id', '=', $fullPageIdColumn)
204                 ->where(function (QueryBuilder $query) {
205                     $query->where('pages.draft', '=', false)
206                         ->orWhere('pages.owned_by', '=', $this->currentUser()->id);
207                 });
208         });
209
210         return $q;
211     }
212
213     /**
214      * Add the query for checking the given user id has permission
215      * within the join_permissions table.
216      *
217      * @param QueryBuilder|Builder $query
218      */
219     protected function addJointHasPermissionCheck($query, int $userIdToCheck)
220     {
221         $query->where('joint_permissions.has_permission', '=', true)->orWhere(function ($query) use ($userIdToCheck) {
222             $query->where('joint_permissions.has_permission_own', '=', true)
223                 ->where('joint_permissions.owned_by', '=', $userIdToCheck);
224         });
225     }
226
227     /**
228      * Get the current user.
229      */
230     protected function currentUser(): User
231     {
232         return user();
233     }
234
235     /**
236      * Get the roles for the current logged-in user.
237      *
238      * @return int[]
239      */
240     protected function getCurrentUserRoleIds(): array
241     {
242         if (auth()->guest()) {
243             return [Role::getSystemRole('public')->id];
244         }
245
246         return $this->currentUser()->roles->pluck('id')->values()->all();
247     }
248 }