]> BookStack Code Mirror - bookstack/blob - app/Permissions/PermissionApplicator.php
Played around with a new app structure
[bookstack] / app / Permissions / PermissionApplicator.php
1 <?php
2
3 namespace BookStack\Permissions;
4
5 use BookStack\App\Model;
6 use BookStack\Entities\Models\Entity;
7 use BookStack\Entities\Models\Page;
8 use BookStack\Permissions\Models\EntityPermission;
9 use BookStack\Users\Models\HasCreatorAndUpdater;
10 use BookStack\Users\Models\HasOwner;
11 use BookStack\Users\Models\Role;
12 use BookStack\Users\Models\User;
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         return (new EntityPermissionEvaluator($action))->evaluateEntityForUser($entity, $userRoleIds);
65     }
66
67     /**
68      * Checks if a user has the given permission for any items in the system.
69      * Can be passed an entity instance to filter on a specific type.
70      */
71     public function checkUserHasEntityPermissionOnAny(string $action, string $entityClass = ''): bool
72     {
73         $this->ensureValidEntityAction($action);
74
75         $permissionQuery = EntityPermission::query()
76             ->where($action, '=', true)
77             ->whereIn('role_id', $this->getCurrentUserRoleIds());
78
79         if (!empty($entityClass)) {
80             /** @var Entity $entityInstance */
81             $entityInstance = app()->make($entityClass);
82             $permissionQuery = $permissionQuery->where('entity_type', '=', $entityInstance->getMorphClass());
83         }
84
85         $hasPermission = $permissionQuery->count() > 0;
86
87         return $hasPermission;
88     }
89
90     /**
91      * Limit the given entity query so that the query will only
92      * return items that the user has view permission for.
93      */
94     public function restrictEntityQuery(Builder $query): Builder
95     {
96         return $query->where(function (Builder $parentQuery) {
97             $parentQuery->whereHas('jointPermissions', function (Builder $permissionQuery) {
98                 $permissionQuery->select(['entity_id', 'entity_type'])
99                     ->selectRaw('max(owner_id) as owner_id')
100                     ->selectRaw('max(status) as status')
101                     ->whereIn('role_id', $this->getCurrentUserRoleIds())
102                     ->groupBy(['entity_type', 'entity_id'])
103                     ->havingRaw('(status IN (1, 3) or (owner_id = ? and status != 2))', [$this->currentUser()->id]);
104             });
105         });
106     }
107
108     /**
109      * Extend the given page query to ensure draft items are not visible
110      * unless created by the given user.
111      */
112     public function restrictDraftsOnPageQuery(Builder $query): Builder
113     {
114         return $query->where(function (Builder $query) {
115             $query->where('draft', '=', false)
116                 ->orWhere(function (Builder $query) {
117                     $query->where('draft', '=', true)
118                         ->where('owned_by', '=', $this->currentUser()->id);
119                 });
120         });
121     }
122
123     /**
124      * Filter items that have entities set as a polymorphic relation.
125      * For simplicity, this will not return results attached to draft pages.
126      * Draft pages should never really have related items though.
127      */
128     public function restrictEntityRelationQuery(Builder $query, string $tableName, string $entityIdColumn, string $entityTypeColumn): Builder
129     {
130         $tableDetails = ['tableName' => $tableName, 'entityIdColumn' => $entityIdColumn, 'entityTypeColumn' => $entityTypeColumn];
131         $pageMorphClass = (new Page())->getMorphClass();
132
133         return $this->restrictEntityQuery($query)
134             ->where(function ($query) use ($tableDetails, $pageMorphClass) {
135                 /** @var Builder $query */
136                 $query->where($tableDetails['entityTypeColumn'], '!=', $pageMorphClass)
137                 ->orWhereExists(function (QueryBuilder $query) use ($tableDetails, $pageMorphClass) {
138                     $query->select('id')->from('pages')
139                         ->whereColumn('pages.id', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
140                         ->where($tableDetails['tableName'] . '.' . $tableDetails['entityTypeColumn'], '=', $pageMorphClass)
141                         ->where('pages.draft', '=', false);
142                 });
143             });
144     }
145
146     /**
147      * Add conditions to a query for a model that's a relation of a page, so only the model results
148      * on visible pages are returned by the query.
149      * Is effectively the same as "restrictEntityRelationQuery" but takes into account page drafts
150      * while not expecting a polymorphic relation, Just a simpler one-page-to-many-relations set-up.
151      */
152     public function restrictPageRelationQuery(Builder $query, string $tableName, string $pageIdColumn): Builder
153     {
154         $fullPageIdColumn = $tableName . '.' . $pageIdColumn;
155         return $this->restrictEntityQuery($query)
156             ->where(function ($query) use ($fullPageIdColumn) {
157                 /** @var Builder $query */
158                 $query->whereExists(function (QueryBuilder $query) use ($fullPageIdColumn) {
159                     $query->select('id')->from('pages')
160                         ->whereColumn('pages.id', '=', $fullPageIdColumn)
161                         ->where('pages.draft', '=', false);
162                 })->orWhereExists(function (QueryBuilder $query) use ($fullPageIdColumn) {
163                     $query->select('id')->from('pages')
164                         ->whereColumn('pages.id', '=', $fullPageIdColumn)
165                         ->where('pages.draft', '=', true)
166                         ->where('pages.created_by', '=', $this->currentUser()->id);
167                 });
168             });
169     }
170
171     /**
172      * Get the current user.
173      */
174     protected function currentUser(): User
175     {
176         return user();
177     }
178
179     /**
180      * Get the roles for the current logged-in user.
181      *
182      * @return int[]
183      */
184     protected function getCurrentUserRoleIds(): array
185     {
186         if (auth()->guest()) {
187             return [Role::getSystemRole('public')->id];
188         }
189
190         return $this->currentUser()->roles->pluck('id')->values()->all();
191     }
192
193     /**
194      * Ensure the given action is a valid and expected entity action.
195      * Throws an exception if invalid otherwise does nothing.
196      * @throws InvalidArgumentException
197      */
198     protected function ensureValidEntityAction(string $action): void
199     {
200         if (!in_array($action, EntityPermission::PERMISSIONS)) {
201             throw new InvalidArgumentException('Action should be a simple entity permission action, not a role permission');
202         }
203     }
204 }