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 $isOwner = $user->id === $ownable->getAttribute($ownerField);
38 $hasRolePermission = $allRolePermission || ($isOwner && $ownRolePermission);
40 // Handle non entity specific jointPermissions
41 if (in_array($explodedPermission[0], $nonJointPermissions)) {
42 return $hasRolePermission;
45 $hasApplicableEntityPermissions = $this->hasEntityPermission($ownable, $userRoleIds, $action);
47 return is_null($hasApplicableEntityPermissions) ? $hasRolePermission : $hasApplicableEntityPermissions;
51 * Check if there are permissions that are applicable for the given entity item, action and roles.
52 * Returns null when no entity permissions are in force.
54 protected function hasEntityPermission(Entity $entity, array $userRoleIds, string $action): ?bool
56 $adminRoleId = Role::getSystemRole('admin')->id;
57 if (in_array($adminRoleId, $userRoleIds)) {
62 if ($entity instanceof Page && $entity->chapter_id) {
63 $chain[] = $entity->chapter;
66 if ($entity instanceof Page || $entity instanceof Chapter) {
67 $chain[] = $entity->book;
70 foreach ($chain as $currentEntity) {
71 if ($currentEntity->restricted) {
72 return $currentEntity->permissions()
73 ->whereIn('role_id', $userRoleIds)
74 ->where('action', '=', $action)
83 * Checks if a user has the given permission for any items in the system.
84 * Can be passed an entity instance to filter on a specific type.
86 public function checkUserHasEntityPermissionOnAny(string $action, string $entityClass = ''): bool
88 if (strpos($action, '-') !== false) {
89 throw new InvalidArgumentException('Action should be a simple entity permission action, not a role permission');
92 $permissionQuery = EntityPermission::query()
93 ->where('action', '=', $action)
94 ->whereIn('role_id', $this->getCurrentUserRoleIds());
96 if (!empty($entityClass)) {
97 /** @var Entity $entityInstance */
98 $entityInstance = app()->make($entityClass);
99 $permissionQuery = $permissionQuery->where('restrictable_type', '=', $entityInstance->getMorphClass());
102 $hasPermission = $permissionQuery->count() > 0;
104 return $hasPermission;
108 * Limit the given entity query so that the query will only
109 * return items that the user has view permission for.
111 public function restrictEntityQuery(Builder $query): Builder
113 return $query->where(function (Builder $parentQuery) {
114 $parentQuery->whereHas('jointPermissions', function (Builder $permissionQuery) {
115 $permissionQuery->whereIn('role_id', $this->getCurrentUserRoleIds())
116 ->where(function (Builder $query) {
117 $this->addJointHasPermissionCheck($query, $this->currentUser()->id);
124 * Extend the given page query to ensure draft items are not visible
125 * unless created by the given user.
127 public function restrictDraftsOnPageQuery(Builder $query): Builder
129 return $query->where(function (Builder $query) {
130 $query->where('draft', '=', false)
131 ->orWhere(function (Builder $query) {
132 $query->where('draft', '=', true)
133 ->where('owned_by', '=', $this->currentUser()->id);
139 * Filter items that have entities set as a polymorphic relation.
140 * For simplicity, this will not return results attached to draft pages.
141 * Draft pages should never really have related items though.
143 * @param Builder|QueryBuilder $query
145 public function restrictEntityRelationQuery($query, string $tableName, string $entityIdColumn, string $entityTypeColumn)
147 $tableDetails = ['tableName' => $tableName, 'entityIdColumn' => $entityIdColumn, 'entityTypeColumn' => $entityTypeColumn];
148 $pageMorphClass = (new Page())->getMorphClass();
150 $q = $query->whereExists(function ($permissionQuery) use (&$tableDetails) {
151 /** @var Builder $permissionQuery */
152 $permissionQuery->select(['role_id'])->from('joint_permissions')
153 ->whereColumn('joint_permissions.entity_id', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
154 ->whereColumn('joint_permissions.entity_type', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityTypeColumn'])
155 ->whereIn('joint_permissions.role_id', $this->getCurrentUserRoleIds())
156 ->where(function (QueryBuilder $query) {
157 $this->addJointHasPermissionCheck($query, $this->currentUser()->id);
159 })->where(function ($query) use ($tableDetails, $pageMorphClass) {
160 /** @var Builder $query */
161 $query->where($tableDetails['entityTypeColumn'], '!=', $pageMorphClass)
162 ->orWhereExists(function (QueryBuilder $query) use ($tableDetails, $pageMorphClass) {
163 $query->select('id')->from('pages')
164 ->whereColumn('pages.id', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
165 ->where($tableDetails['tableName'] . '.' . $tableDetails['entityTypeColumn'], '=', $pageMorphClass)
166 ->where('pages.draft', '=', false);
174 * Add conditions to a query for a model that's a relation of a page, so only the model results
175 * on visible pages are returned by the query.
176 * Is effectively the same as "restrictEntityRelationQuery" but takes into account page drafts
177 * while not expecting a polymorphic relation, Just a simpler one-page-to-many-relations set-up.
179 public function restrictPageRelationQuery(Builder $query, string $tableName, string $pageIdColumn): Builder
181 $fullPageIdColumn = $tableName . '.' . $pageIdColumn;
182 $morphClass = (new Page())->getMorphClass();
184 $existsQuery = function ($permissionQuery) use ($fullPageIdColumn, $morphClass) {
185 /** @var Builder $permissionQuery */
186 $permissionQuery->select('joint_permissions.role_id')->from('joint_permissions')
187 ->whereColumn('joint_permissions.entity_id', '=', $fullPageIdColumn)
188 ->where('joint_permissions.entity_type', '=', $morphClass)
189 ->whereIn('joint_permissions.role_id', $this->getCurrentUserRoleIds())
190 ->where(function (QueryBuilder $query) {
191 $this->addJointHasPermissionCheck($query, $this->currentUser()->id);
195 $q = $query->where(function ($query) use ($existsQuery, $fullPageIdColumn) {
196 $query->whereExists($existsQuery)
197 ->orWhere($fullPageIdColumn, '=', 0);
200 // Prevent visibility of non-owned draft pages
201 $q->whereExists(function (QueryBuilder $query) use ($fullPageIdColumn) {
202 $query->select('id')->from('pages')
203 ->whereColumn('pages.id', '=', $fullPageIdColumn)
204 ->where(function (QueryBuilder $query) {
205 $query->where('pages.draft', '=', false)
206 ->orWhere('pages.owned_by', '=', $this->currentUser()->id);
214 * Add the query for checking the given user id has permission
215 * within the join_permissions table.
217 * @param QueryBuilder|Builder $query
219 protected function addJointHasPermissionCheck($query, int $userIdToCheck)
221 $query->where('joint_permissions.has_permission', '=', true)->orWhere(function ($query) use ($userIdToCheck) {
222 $query->where('joint_permissions.has_permission_own', '=', true)
223 ->where('joint_permissions.owned_by', '=', $userIdToCheck);
228 * Get the current user.
230 protected function currentUser(): User
236 * Get the roles for the current logged-in user.
240 protected function getCurrentUserRoleIds(): array
242 if (auth()->guest()) {
243 return [Role::getSystemRole('public')->id];
246 return $this->currentUser()->roles->pluck('id')->values()->all();