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 $adminRoleId = Role::getSystemRole('admin')->id;
63 if (in_array($adminRoleId, $userRoleIds)) {
68 if ($entity instanceof Page && $entity->chapter_id) {
69 $chain[] = $entity->chapter;
72 if ($entity instanceof Page || $entity instanceof Chapter) {
73 $chain[] = $entity->book;
76 foreach ($chain as $currentEntity) {
77 if (is_null($currentEntity->restricted)) {
78 throw new InvalidArgumentException('Entity restricted field used but has not been loaded');
81 if ($currentEntity->restricted) {
82 return $currentEntity->permissions()
83 ->whereIn('role_id', $userRoleIds)
84 ->where('action', '=', $action)
93 * Checks if a user has the given permission for any items in the system.
94 * Can be passed an entity instance to filter on a specific type.
96 public function checkUserHasEntityPermissionOnAny(string $action, string $entityClass = ''): bool
98 if (strpos($action, '-') !== false) {
99 throw new InvalidArgumentException('Action should be a simple entity permission action, not a role permission');
102 $permissionQuery = EntityPermission::query()
103 ->where('action', '=', $action)
104 ->whereIn('role_id', $this->getCurrentUserRoleIds());
106 if (!empty($entityClass)) {
107 /** @var Entity $entityInstance */
108 $entityInstance = app()->make($entityClass);
109 $permissionQuery = $permissionQuery->where('restrictable_type', '=', $entityInstance->getMorphClass());
112 $hasPermission = $permissionQuery->count() > 0;
114 return $hasPermission;
118 * Limit the given entity query so that the query will only
119 * return items that the user has view permission for.
121 public function restrictEntityQuery(Builder $query): Builder
123 return $query->where(function (Builder $parentQuery) {
124 $parentQuery->whereHas('jointPermissions', function (Builder $permissionQuery) {
125 $permissionQuery->whereIn('role_id', $this->getCurrentUserRoleIds())
126 ->where(function (Builder $query) {
127 $this->addJointHasPermissionCheck($query, $this->currentUser()->id);
134 * Extend the given page query to ensure draft items are not visible
135 * unless created by the given user.
137 public function restrictDraftsOnPageQuery(Builder $query): Builder
139 return $query->where(function (Builder $query) {
140 $query->where('draft', '=', false)
141 ->orWhere(function (Builder $query) {
142 $query->where('draft', '=', true)
143 ->where('owned_by', '=', $this->currentUser()->id);
149 * Filter items that have entities set as a polymorphic relation.
150 * For simplicity, this will not return results attached to draft pages.
151 * Draft pages should never really have related items though.
153 * @param Builder|QueryBuilder $query
155 public function restrictEntityRelationQuery($query, string $tableName, string $entityIdColumn, string $entityTypeColumn)
157 $tableDetails = ['tableName' => $tableName, 'entityIdColumn' => $entityIdColumn, 'entityTypeColumn' => $entityTypeColumn];
158 $pageMorphClass = (new Page())->getMorphClass();
160 $q = $query->whereExists(function ($permissionQuery) use (&$tableDetails) {
161 /** @var Builder $permissionQuery */
162 $permissionQuery->select(['role_id'])->from('joint_permissions')
163 ->whereColumn('joint_permissions.entity_id', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
164 ->whereColumn('joint_permissions.entity_type', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityTypeColumn'])
165 ->whereIn('joint_permissions.role_id', $this->getCurrentUserRoleIds())
166 ->where(function (QueryBuilder $query) {
167 $this->addJointHasPermissionCheck($query, $this->currentUser()->id);
169 })->where(function ($query) use ($tableDetails, $pageMorphClass) {
170 /** @var Builder $query */
171 $query->where($tableDetails['entityTypeColumn'], '!=', $pageMorphClass)
172 ->orWhereExists(function (QueryBuilder $query) use ($tableDetails, $pageMorphClass) {
173 $query->select('id')->from('pages')
174 ->whereColumn('pages.id', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
175 ->where($tableDetails['tableName'] . '.' . $tableDetails['entityTypeColumn'], '=', $pageMorphClass)
176 ->where('pages.draft', '=', false);
184 * Add conditions to a query for a model that's a relation of a page, so only the model results
185 * on visible pages are returned by the query.
186 * Is effectively the same as "restrictEntityRelationQuery" but takes into account page drafts
187 * while not expecting a polymorphic relation, Just a simpler one-page-to-many-relations set-up.
189 public function restrictPageRelationQuery(Builder $query, string $tableName, string $pageIdColumn): Builder
191 $fullPageIdColumn = $tableName . '.' . $pageIdColumn;
192 $morphClass = (new Page())->getMorphClass();
194 $existsQuery = function ($permissionQuery) use ($fullPageIdColumn, $morphClass) {
195 /** @var Builder $permissionQuery */
196 $permissionQuery->select('joint_permissions.role_id')->from('joint_permissions')
197 ->whereColumn('joint_permissions.entity_id', '=', $fullPageIdColumn)
198 ->where('joint_permissions.entity_type', '=', $morphClass)
199 ->whereIn('joint_permissions.role_id', $this->getCurrentUserRoleIds())
200 ->where(function (QueryBuilder $query) {
201 $this->addJointHasPermissionCheck($query, $this->currentUser()->id);
205 $q = $query->where(function ($query) use ($existsQuery, $fullPageIdColumn) {
206 $query->whereExists($existsQuery)
207 ->orWhere($fullPageIdColumn, '=', 0);
210 // Prevent visibility of non-owned draft pages
211 $q->whereExists(function (QueryBuilder $query) use ($fullPageIdColumn) {
212 $query->select('id')->from('pages')
213 ->whereColumn('pages.id', '=', $fullPageIdColumn)
214 ->where(function (QueryBuilder $query) {
215 $query->where('pages.draft', '=', false)
216 ->orWhere('pages.owned_by', '=', $this->currentUser()->id);
224 * Add the query for checking the given user id has permission
225 * within the join_permissions table.
227 * @param QueryBuilder|Builder $query
229 protected function addJointHasPermissionCheck($query, int $userIdToCheck)
231 $query->where('joint_permissions.has_permission', '=', true)->orWhere(function ($query) use ($userIdToCheck) {
232 $query->where('joint_permissions.has_permission_own', '=', true)
233 ->where('joint_permissions.owned_by', '=', $userIdToCheck);
238 * Get the current user.
240 protected function currentUser(): User
246 * Get the roles for the current logged-in user.
250 protected function getCurrentUserRoleIds(): array
252 if (auth()->guest()) {
253 return [Role::getSystemRole('public')->id];
256 return $this->currentUser()->roles->pluck('id')->values()->all();