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 $relevantPermissions = $currentEntity->permissions()
82 ->where(function (Builder $query) use ($userRoleIds) {
83 $query->whereIn('role_id', $userRoleIds)
84 ->orWhere(function (Builder $query) {
85 $query->whereNull(['role_id', 'user_id']);
88 ->get(['role_id', 'user_id', $action])
91 // TODO - Update below for user permissions
93 // 1. Default fallback set and allows, no role permissions -> True
94 // 2. Default fallback set and prevents, no role permissions -> False
95 // 3. Role permission allows, fallback set and allows -> True
96 // 3. Role permission allows, fallback set and prevents -> True
97 // 3. Role permission allows, fallback not set -> True
98 // 3. Role permission prevents, fallback set and allows -> False
99 // 3. Role permission prevents, fallback set and prevents -> False
100 // 3. Role permission prevents, fallback not set -> False
101 // 4. Nothing exists -> Continue
103 // If the default is set, we have to return something here.
105 foreach ($relevantPermissions as $permission) {
106 $allowedById[$permission->role_id . ':' . $permission->user_id] = $permission->$action;
109 // Continue up the chain if no applicable entity permission overrides.
110 if (empty($allowedById)) {
114 // If we have user-role-specific permissions set, allow if any of those
115 // role permissions allow access.
116 $hasDefault = isset($allowedById[':']);
117 if (!$hasDefault || count($allowedById) > 1) {
118 foreach ($allowedById as $key => $allowed) {
119 if ($key !== ':' && $allowed) {
126 // Otherwise, return the default "Other roles" fallback value.
127 return $allowedById[':'];
134 * Checks if a user has the given permission for any items in the system.
135 * Can be passed an entity instance to filter on a specific type.
137 public function checkUserHasEntityPermissionOnAny(string $action, string $entityClass = ''): bool
139 $this->ensureValidEntityAction($action);
141 $permissionQuery = EntityPermission::query()
142 ->where($action, '=', true)
143 ->whereIn('role_id', $this->getCurrentUserRoleIds());
144 // TODO - Update for user permission
146 if (!empty($entityClass)) {
147 /** @var Entity $entityInstance */
148 $entityInstance = app()->make($entityClass);
149 $permissionQuery = $permissionQuery->where('entity_type', '=', $entityInstance->getMorphClass());
152 $hasPermission = $permissionQuery->count() > 0;
154 return $hasPermission;
158 * Limit the given entity query so that the query will only
159 * return items that the user has view permission for.
161 public function restrictEntityQuery(Builder $query): Builder
163 return $query->where(function (Builder $parentQuery) {
164 $parentQuery->whereHas('jointPermissions', function (Builder $permissionQuery) {
165 // TODO - Update for user permission
166 $permissionQuery->whereIn('role_id', $this->getCurrentUserRoleIds())
167 ->where(function (Builder $query) {
168 $this->addJointHasPermissionCheck($query, $this->currentUser()->id);
175 * Extend the given page query to ensure draft items are not visible
176 * unless created by the given user.
178 public function restrictDraftsOnPageQuery(Builder $query): Builder
180 return $query->where(function (Builder $query) {
181 $query->where('draft', '=', false)
182 ->orWhere(function (Builder $query) {
183 $query->where('draft', '=', true)
184 ->where('owned_by', '=', $this->currentUser()->id);
190 * Filter items that have entities set as a polymorphic relation.
191 * For simplicity, this will not return results attached to draft pages.
192 * Draft pages should never really have related items though.
194 * @param Builder|QueryBuilder $query
196 public function restrictEntityRelationQuery($query, string $tableName, string $entityIdColumn, string $entityTypeColumn)
198 $tableDetails = ['tableName' => $tableName, 'entityIdColumn' => $entityIdColumn, 'entityTypeColumn' => $entityTypeColumn];
199 $pageMorphClass = (new Page())->getMorphClass();
201 $q = $query->whereExists(function ($permissionQuery) use (&$tableDetails) {
202 // TODO - Update for user permission
203 /** @var Builder $permissionQuery */
204 $permissionQuery->select(['role_id'])->from('joint_permissions')
205 ->whereColumn('joint_permissions.entity_id', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
206 ->whereColumn('joint_permissions.entity_type', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityTypeColumn'])
207 ->whereIn('joint_permissions.role_id', $this->getCurrentUserRoleIds())
208 ->where(function (QueryBuilder $query) {
209 $this->addJointHasPermissionCheck($query, $this->currentUser()->id);
211 })->where(function ($query) use ($tableDetails, $pageMorphClass) {
212 /** @var Builder $query */
213 $query->where($tableDetails['entityTypeColumn'], '!=', $pageMorphClass)
214 ->orWhereExists(function (QueryBuilder $query) use ($tableDetails, $pageMorphClass) {
215 $query->select('id')->from('pages')
216 ->whereColumn('pages.id', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
217 ->where($tableDetails['tableName'] . '.' . $tableDetails['entityTypeColumn'], '=', $pageMorphClass)
218 ->where('pages.draft', '=', false);
226 * Add conditions to a query for a model that's a relation of a page, so only the model results
227 * on visible pages are returned by the query.
228 * Is effectively the same as "restrictEntityRelationQuery" but takes into account page drafts
229 * while not expecting a polymorphic relation, Just a simpler one-page-to-many-relations set-up.
231 public function restrictPageRelationQuery(Builder $query, string $tableName, string $pageIdColumn): Builder
233 $fullPageIdColumn = $tableName . '.' . $pageIdColumn;
234 $morphClass = (new Page())->getMorphClass();
236 // TODO - Update for user permission
237 $existsQuery = function ($permissionQuery) use ($fullPageIdColumn, $morphClass) {
238 /** @var Builder $permissionQuery */
239 $permissionQuery->select('joint_permissions.role_id')->from('joint_permissions')
240 ->whereColumn('joint_permissions.entity_id', '=', $fullPageIdColumn)
241 ->where('joint_permissions.entity_type', '=', $morphClass)
242 ->whereIn('joint_permissions.role_id', $this->getCurrentUserRoleIds())
243 ->where(function (QueryBuilder $query) {
244 $this->addJointHasPermissionCheck($query, $this->currentUser()->id);
248 $q = $query->where(function ($query) use ($existsQuery, $fullPageIdColumn) {
249 $query->whereExists($existsQuery)
250 ->orWhere($fullPageIdColumn, '=', 0);
253 // Prevent visibility of non-owned draft pages
254 $q->whereExists(function (QueryBuilder $query) use ($fullPageIdColumn) {
255 $query->select('id')->from('pages')
256 ->whereColumn('pages.id', '=', $fullPageIdColumn)
257 ->where(function (QueryBuilder $query) {
258 $query->where('pages.draft', '=', false)
259 ->orWhere('pages.owned_by', '=', $this->currentUser()->id);
267 * Add the query for checking the given user id has permission
268 * within the join_permissions table.
270 * @param QueryBuilder|Builder $query
272 protected function addJointHasPermissionCheck($query, int $userIdToCheck)
274 $query->where('joint_permissions.has_permission', '=', true)->orWhere(function ($query) use ($userIdToCheck) {
275 $query->where('joint_permissions.has_permission_own', '=', true)
276 ->where('joint_permissions.owned_by', '=', $userIdToCheck);
281 * Get the current user.
283 protected function currentUser(): User
289 * Get the roles for the current logged-in user.
293 protected function getCurrentUserRoleIds(): array
295 if (auth()->guest()) {
296 return [Role::getSystemRole('public')->id];
299 return $this->currentUser()->roles->pluck('id')->values()->all();
303 * Ensure the given action is a valid and expected entity action.
304 * Throws an exception if invalid otherwise does nothing.
305 * @throws InvalidArgumentException
307 protected function ensureValidEntityAction(string $action): void
309 if (!in_array($action, EntityPermission::PERMISSIONS)) {
310 throw new InvalidArgumentException('Action should be a simple entity permission action, not a role permission');