3 namespace BookStack\Auth\Permissions;
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;
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;
17 class PermissionApplicator
20 * Checks if an entity has a restriction set upon it.
22 * @param HasCreatorAndUpdater|HasOwner $ownable
24 public function checkOwnableUserAccess(Model $ownable, string $permission): bool
26 $explodedPermission = explode('-', $permission);
27 $action = $explodedPermission[1] ?? $explodedPermission[0];
28 $fullPermission = count($explodedPermission) > 1 ? $permission : $ownable->getMorphClass() . '-' . $permission;
30 $user = $this->currentUser();
31 $userRoleIds = $this->getCurrentUserRoleIds();
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);
39 if (is_null($ownableFieldVal)) {
40 throw new InvalidArgumentException("{$ownerField} field used but has not been loaded");
43 $isOwner = $user->id === $ownableFieldVal;
44 $hasRolePermission = $allRolePermission || ($isOwner && $ownRolePermission);
46 // Handle non entity specific jointPermissions
47 if (in_array($explodedPermission[0], $nonJointPermissions)) {
48 return $hasRolePermission;
51 $hasApplicableEntityPermissions = $this->hasEntityPermission($ownable, $userRoleIds, $action);
53 return is_null($hasApplicableEntityPermissions) ? $hasRolePermission : $hasApplicableEntityPermissions;
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.
60 protected function hasEntityPermission(Entity $entity, array $userRoleIds, string $action): ?bool
62 $this->ensureValidEntityAction($action);
64 $adminRoleId = Role::getSystemRole('admin')->id;
65 if (in_array($adminRoleId, $userRoleIds)) {
69 // The chain order here is very important due to the fact we walk up the chain
70 // in the loop below. Earlier items in the chain have higher priority.
72 if ($entity instanceof Page && $entity->chapter_id) {
73 $chain[] = $entity->chapter;
76 if ($entity instanceof Page || $entity instanceof Chapter) {
77 $chain[] = $entity->book;
80 foreach ($chain as $currentEntity) {
81 $allowedByRoleId = $currentEntity->permissions()
82 ->whereIn('role_id', [0, ...$userRoleIds])
83 ->pluck($action, 'role_id');
85 // Continue up the chain if no applicable entity permission overrides.
86 if ($allowedByRoleId->isEmpty()) {
90 // If we have user-role-specific permissions set, allow if any of those
91 // role permissions allow access.
92 $hasDefault = $allowedByRoleId->has(0);
93 if (!$hasDefault || $allowedByRoleId->count() > 1) {
94 return $allowedByRoleId->search(function (bool $allowed, int $roleId) {
95 return $roleId !== 0 && $allowed;
99 // Otherwise, return the default "Other roles" fallback value.
100 return $allowedByRoleId->get(0);
107 * Checks if a user has the given permission for any items in the system.
108 * Can be passed an entity instance to filter on a specific type.
110 public function checkUserHasEntityPermissionOnAny(string $action, string $entityClass = ''): bool
112 $this->ensureValidEntityAction($action);
114 $permissionQuery = EntityPermission::query()
115 ->where($action, '=', true)
116 ->whereIn('role_id', $this->getCurrentUserRoleIds());
118 if (!empty($entityClass)) {
119 /** @var Entity $entityInstance */
120 $entityInstance = app()->make($entityClass);
121 $permissionQuery = $permissionQuery->where('entity_type', '=', $entityInstance->getMorphClass());
124 $hasPermission = $permissionQuery->count() > 0;
126 return $hasPermission;
130 * Limit the given entity query so that the query will only
131 * return items that the user has view permission for.
133 public function restrictEntityQuery(Builder $query): Builder
135 return $query->where(function (Builder $parentQuery) {
136 $parentQuery->whereHas('jointPermissions', function (Builder $permissionQuery) {
137 $permissionQuery->whereIn('role_id', $this->getCurrentUserRoleIds())
138 ->where(function (Builder $query) {
139 $this->addJointHasPermissionCheck($query, $this->currentUser()->id);
146 * Extend the given page query to ensure draft items are not visible
147 * unless created by the given user.
149 public function restrictDraftsOnPageQuery(Builder $query): Builder
151 return $query->where(function (Builder $query) {
152 $query->where('draft', '=', false)
153 ->orWhere(function (Builder $query) {
154 $query->where('draft', '=', true)
155 ->where('owned_by', '=', $this->currentUser()->id);
161 * Filter items that have entities set as a polymorphic relation.
162 * For simplicity, this will not return results attached to draft pages.
163 * Draft pages should never really have related items though.
165 * @param Builder|QueryBuilder $query
167 public function restrictEntityRelationQuery($query, string $tableName, string $entityIdColumn, string $entityTypeColumn)
169 $tableDetails = ['tableName' => $tableName, 'entityIdColumn' => $entityIdColumn, 'entityTypeColumn' => $entityTypeColumn];
170 $pageMorphClass = (new Page())->getMorphClass();
172 $q = $query->whereExists(function ($permissionQuery) use (&$tableDetails) {
173 /** @var Builder $permissionQuery */
174 $permissionQuery->select(['role_id'])->from('joint_permissions')
175 ->whereColumn('joint_permissions.entity_id', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
176 ->whereColumn('joint_permissions.entity_type', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityTypeColumn'])
177 ->whereIn('joint_permissions.role_id', $this->getCurrentUserRoleIds())
178 ->where(function (QueryBuilder $query) {
179 $this->addJointHasPermissionCheck($query, $this->currentUser()->id);
181 })->where(function ($query) use ($tableDetails, $pageMorphClass) {
182 /** @var Builder $query */
183 $query->where($tableDetails['entityTypeColumn'], '!=', $pageMorphClass)
184 ->orWhereExists(function (QueryBuilder $query) use ($tableDetails, $pageMorphClass) {
185 $query->select('id')->from('pages')
186 ->whereColumn('pages.id', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
187 ->where($tableDetails['tableName'] . '.' . $tableDetails['entityTypeColumn'], '=', $pageMorphClass)
188 ->where('pages.draft', '=', false);
196 * Add conditions to a query for a model that's a relation of a page, so only the model results
197 * on visible pages are returned by the query.
198 * Is effectively the same as "restrictEntityRelationQuery" but takes into account page drafts
199 * while not expecting a polymorphic relation, Just a simpler one-page-to-many-relations set-up.
201 public function restrictPageRelationQuery(Builder $query, string $tableName, string $pageIdColumn): Builder
203 $fullPageIdColumn = $tableName . '.' . $pageIdColumn;
204 $morphClass = (new Page())->getMorphClass();
206 $existsQuery = function ($permissionQuery) use ($fullPageIdColumn, $morphClass) {
207 /** @var Builder $permissionQuery */
208 $permissionQuery->select('joint_permissions.role_id')->from('joint_permissions')
209 ->whereColumn('joint_permissions.entity_id', '=', $fullPageIdColumn)
210 ->where('joint_permissions.entity_type', '=', $morphClass)
211 ->whereIn('joint_permissions.role_id', $this->getCurrentUserRoleIds())
212 ->where(function (QueryBuilder $query) {
213 $this->addJointHasPermissionCheck($query, $this->currentUser()->id);
217 $q = $query->where(function ($query) use ($existsQuery, $fullPageIdColumn) {
218 $query->whereExists($existsQuery)
219 ->orWhere($fullPageIdColumn, '=', 0);
222 // Prevent visibility of non-owned draft pages
223 $q->whereExists(function (QueryBuilder $query) use ($fullPageIdColumn) {
224 $query->select('id')->from('pages')
225 ->whereColumn('pages.id', '=', $fullPageIdColumn)
226 ->where(function (QueryBuilder $query) {
227 $query->where('pages.draft', '=', false)
228 ->orWhere('pages.owned_by', '=', $this->currentUser()->id);
236 * Add the query for checking the given user id has permission
237 * within the join_permissions table.
239 * @param QueryBuilder|Builder $query
241 protected function addJointHasPermissionCheck($query, int $userIdToCheck)
243 $query->where('joint_permissions.has_permission', '=', true)->orWhere(function ($query) use ($userIdToCheck) {
244 $query->where('joint_permissions.has_permission_own', '=', true)
245 ->where('joint_permissions.owned_by', '=', $userIdToCheck);
250 * Get the current user.
252 protected function currentUser(): User
258 * Get the roles for the current logged-in user.
262 protected function getCurrentUserRoleIds(): array
264 if (auth()->guest()) {
265 return [Role::getSystemRole('public')->id];
268 return $this->currentUser()->roles->pluck('id')->values()->all();
272 * Ensure the given action is a valid and expected entity action.
273 * Throws an exception if invalid otherwise does nothing.
274 * @throws InvalidArgumentException
276 protected function ensureValidEntityAction(string $action): void
278 if (!in_array($action, EntityPermission::PERMISSIONS)) {
279 throw new InvalidArgumentException('Action should be a simple entity permission action, not a role permission');