3 namespace BookStack\Auth\Permissions;
5 use BookStack\Auth\Role;
6 use BookStack\Auth\User;
7 use BookStack\Entities\Models\Entity;
8 use BookStack\Entities\Models\Page;
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;
16 class PermissionApplicator
19 * Checks if an entity has a restriction set upon it.
21 * @param HasCreatorAndUpdater|HasOwner $ownable
23 public function checkOwnableUserAccess(Model $ownable, string $permission): bool
25 $explodedPermission = explode('-', $permission);
26 $action = $explodedPermission[1] ?? $explodedPermission[0];
27 $fullPermission = count($explodedPermission) > 1 ? $permission : $ownable->getMorphClass() . '-' . $permission;
29 $user = $this->currentUser();
30 $userRoleIds = $this->getCurrentUserRoleIds();
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);
38 if (is_null($ownableFieldVal)) {
39 throw new InvalidArgumentException("{$ownerField} field used but has not been loaded");
42 $isOwner = $user->id === $ownableFieldVal;
43 $hasRolePermission = $allRolePermission || ($isOwner && $ownRolePermission);
45 // Handle non entity specific jointPermissions
46 if (in_array($explodedPermission[0], $nonJointPermissions)) {
47 return $hasRolePermission;
50 $hasApplicableEntityPermissions = $this->hasEntityPermission($ownable, $user->id, $userRoleIds, $action);
52 return is_null($hasApplicableEntityPermissions) ? $hasRolePermission : $hasApplicableEntityPermissions;
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.
59 protected function hasEntityPermission(Entity $entity, int $userId, array $userRoleIds, string $action): ?bool
61 $this->ensureValidEntityAction($action);
63 return (new EntityPermissionEvaluator($entity, $userId, $userRoleIds, $action))->evaluate();
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.
70 public function checkUserHasEntityPermissionOnAny(string $action, string $entityClass = ''): bool
72 $this->ensureValidEntityAction($action);
74 $permissionQuery = EntityPermission::query()
75 ->where($action, '=', true)
76 ->whereIn('role_id', $this->getCurrentUserRoleIds());
78 if (!empty($entityClass)) {
79 /** @var Entity $entityInstance */
80 $entityInstance = app()->make($entityClass);
81 $permissionQuery = $permissionQuery->where('entity_type', '=', $entityInstance->getMorphClass());
84 $hasPermission = $permissionQuery->count() > 0;
86 return $hasPermission;
90 * Limit the given entity query so that the query will only
91 * return items that the user has view permission for.
93 public function restrictEntityQuery(Builder $query): Builder
95 return $query->where(function (Builder $parentQuery) {
96 $parentQuery->whereHas('jointPermissions', function (Builder $permissionQuery) {
97 $permissionQuery->whereIn('role_id', $this->getCurrentUserRoleIds())
98 ->where(function (Builder $query) {
99 $this->addJointHasPermissionCheck($query, $this->currentUser()->id);
106 * Extend the given page query to ensure draft items are not visible
107 * unless created by the given user.
109 public function restrictDraftsOnPageQuery(Builder $query): Builder
111 return $query->where(function (Builder $query) {
112 $query->where('draft', '=', false)
113 ->orWhere(function (Builder $query) {
114 $query->where('draft', '=', true)
115 ->where('owned_by', '=', $this->currentUser()->id);
121 * Filter items that have entities set as a polymorphic relation.
122 * For simplicity, this will not return results attached to draft pages.
123 * Draft pages should never really have related items though.
125 * @param Builder|QueryBuilder $query
127 public function restrictEntityRelationQuery($query, string $tableName, string $entityIdColumn, string $entityTypeColumn)
129 $tableDetails = ['tableName' => $tableName, 'entityIdColumn' => $entityIdColumn, 'entityTypeColumn' => $entityTypeColumn];
130 $pageMorphClass = (new Page())->getMorphClass();
132 $q = $query->whereExists(function ($permissionQuery) use (&$tableDetails) {
133 /** @var Builder $permissionQuery */
134 $permissionQuery->select(['role_id'])->from('joint_permissions')
135 ->whereColumn('joint_permissions.entity_id', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
136 ->whereColumn('joint_permissions.entity_type', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityTypeColumn'])
137 ->whereIn('joint_permissions.role_id', $this->getCurrentUserRoleIds())
138 ->where(function (QueryBuilder $query) {
139 $this->addJointHasPermissionCheck($query, $this->currentUser()->id);
141 })->where(function ($query) use ($tableDetails, $pageMorphClass) {
142 /** @var Builder $query */
143 $query->where($tableDetails['entityTypeColumn'], '!=', $pageMorphClass)
144 ->orWhereExists(function (QueryBuilder $query) use ($tableDetails, $pageMorphClass) {
145 $query->select('id')->from('pages')
146 ->whereColumn('pages.id', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
147 ->where($tableDetails['tableName'] . '.' . $tableDetails['entityTypeColumn'], '=', $pageMorphClass)
148 ->where('pages.draft', '=', false);
156 * Add conditions to a query for a model that's a relation of a page, so only the model results
157 * on visible pages are returned by the query.
158 * Is effectively the same as "restrictEntityRelationQuery" but takes into account page drafts
159 * while not expecting a polymorphic relation, Just a simpler one-page-to-many-relations set-up.
161 public function restrictPageRelationQuery(Builder $query, string $tableName, string $pageIdColumn): Builder
163 $fullPageIdColumn = $tableName . '.' . $pageIdColumn;
164 $morphClass = (new Page())->getMorphClass();
166 $existsQuery = function ($permissionQuery) use ($fullPageIdColumn, $morphClass) {
167 /** @var Builder $permissionQuery */
168 $permissionQuery->select('joint_permissions.role_id')->from('joint_permissions')
169 ->whereColumn('joint_permissions.entity_id', '=', $fullPageIdColumn)
170 ->where('joint_permissions.entity_type', '=', $morphClass)
171 ->whereIn('joint_permissions.role_id', $this->getCurrentUserRoleIds())
172 ->where(function (QueryBuilder $query) {
173 $this->addJointHasPermissionCheck($query, $this->currentUser()->id);
177 $q = $query->where(function ($query) use ($existsQuery, $fullPageIdColumn) {
178 $query->whereExists($existsQuery)
179 ->orWhere($fullPageIdColumn, '=', 0);
182 // Prevent visibility of non-owned draft pages
183 $q->whereExists(function (QueryBuilder $query) use ($fullPageIdColumn) {
184 $query->select('id')->from('pages')
185 ->whereColumn('pages.id', '=', $fullPageIdColumn)
186 ->where(function (QueryBuilder $query) {
187 $query->where('pages.draft', '=', false)
188 ->orWhere('pages.owned_by', '=', $this->currentUser()->id);
196 * Add the query for checking the given user id has permission
197 * within the join_permissions table.
199 * @param QueryBuilder|Builder $query
201 protected function addJointHasPermissionCheck($query, int $userIdToCheck)
203 $query->where('joint_permissions.has_permission', '=', true)->orWhere(function ($query) use ($userIdToCheck) {
204 $query->where('joint_permissions.has_permission_own', '=', true)
205 ->where('joint_permissions.owned_by', '=', $userIdToCheck);
210 * Get the current user.
212 protected function currentUser(): User
218 * Get the roles for the current logged-in user.
222 protected function getCurrentUserRoleIds(): array
224 if (auth()->guest()) {
225 return [Role::getSystemRole('public')->id];
228 return $this->currentUser()->roles->pluck('id')->values()->all();
232 * Ensure the given action is a valid and expected entity action.
233 * Throws an exception if invalid otherwise does nothing.
234 * @throws InvalidArgumentException
236 protected function ensureValidEntityAction(string $action): void
238 if (!in_array($action, EntityPermission::PERMISSIONS)) {
239 throw new InvalidArgumentException('Action should be a simple entity permission action, not a role permission');