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) {
78 if (is_null($currentEntity->restricted)) {
79 throw new InvalidArgumentException("Entity restricted field used but has not been loaded");
82 if ($currentEntity->restricted) {
83 return $currentEntity->permissions()
84 ->whereIn('role_id', $userRoleIds)
85 ->where('action', '=', $action)
94 * Checks if a user has the given permission for any items in the system.
95 * Can be passed an entity instance to filter on a specific type.
97 public function checkUserHasEntityPermissionOnAny(string $action, string $entityClass = ''): bool
99 if (strpos($action, '-') !== false) {
100 throw new InvalidArgumentException('Action should be a simple entity permission action, not a role permission');
103 $permissionQuery = EntityPermission::query()
104 ->where('action', '=', $action)
105 ->whereIn('role_id', $this->getCurrentUserRoleIds());
107 if (!empty($entityClass)) {
108 /** @var Entity $entityInstance */
109 $entityInstance = app()->make($entityClass);
110 $permissionQuery = $permissionQuery->where('restrictable_type', '=', $entityInstance->getMorphClass());
113 $hasPermission = $permissionQuery->count() > 0;
115 return $hasPermission;
119 * Limit the given entity query so that the query will only
120 * return items that the user has view permission for.
122 public function restrictEntityQuery(Builder $query): Builder
124 return $query->where(function (Builder $parentQuery) {
125 $parentQuery->whereHas('jointPermissions', function (Builder $permissionQuery) {
126 $permissionQuery->whereIn('role_id', $this->getCurrentUserRoleIds())
127 ->where(function (Builder $query) {
128 $this->addJointHasPermissionCheck($query, $this->currentUser()->id);
135 * Extend the given page query to ensure draft items are not visible
136 * unless created by the given user.
138 public function restrictDraftsOnPageQuery(Builder $query): Builder
140 return $query->where(function (Builder $query) {
141 $query->where('draft', '=', false)
142 ->orWhere(function (Builder $query) {
143 $query->where('draft', '=', true)
144 ->where('owned_by', '=', $this->currentUser()->id);
150 * Filter items that have entities set as a polymorphic relation.
151 * For simplicity, this will not return results attached to draft pages.
152 * Draft pages should never really have related items though.
154 * @param Builder|QueryBuilder $query
156 public function restrictEntityRelationQuery($query, string $tableName, string $entityIdColumn, string $entityTypeColumn)
158 $tableDetails = ['tableName' => $tableName, 'entityIdColumn' => $entityIdColumn, 'entityTypeColumn' => $entityTypeColumn];
159 $pageMorphClass = (new Page())->getMorphClass();
161 $q = $query->whereExists(function ($permissionQuery) use (&$tableDetails) {
162 /** @var Builder $permissionQuery */
163 $permissionQuery->select(['role_id'])->from('joint_permissions')
164 ->whereColumn('joint_permissions.entity_id', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
165 ->whereColumn('joint_permissions.entity_type', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityTypeColumn'])
166 ->whereIn('joint_permissions.role_id', $this->getCurrentUserRoleIds())
167 ->where(function (QueryBuilder $query) {
168 $this->addJointHasPermissionCheck($query, $this->currentUser()->id);
170 })->where(function ($query) use ($tableDetails, $pageMorphClass) {
171 /** @var Builder $query */
172 $query->where($tableDetails['entityTypeColumn'], '!=', $pageMorphClass)
173 ->orWhereExists(function (QueryBuilder $query) use ($tableDetails, $pageMorphClass) {
174 $query->select('id')->from('pages')
175 ->whereColumn('pages.id', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
176 ->where($tableDetails['tableName'] . '.' . $tableDetails['entityTypeColumn'], '=', $pageMorphClass)
177 ->where('pages.draft', '=', false);
185 * Add conditions to a query for a model that's a relation of a page, so only the model results
186 * on visible pages are returned by the query.
187 * Is effectively the same as "restrictEntityRelationQuery" but takes into account page drafts
188 * while not expecting a polymorphic relation, Just a simpler one-page-to-many-relations set-up.
190 public function restrictPageRelationQuery(Builder $query, string $tableName, string $pageIdColumn): Builder
192 $fullPageIdColumn = $tableName . '.' . $pageIdColumn;
193 $morphClass = (new Page())->getMorphClass();
195 $existsQuery = function ($permissionQuery) use ($fullPageIdColumn, $morphClass) {
196 /** @var Builder $permissionQuery */
197 $permissionQuery->select('joint_permissions.role_id')->from('joint_permissions')
198 ->whereColumn('joint_permissions.entity_id', '=', $fullPageIdColumn)
199 ->where('joint_permissions.entity_type', '=', $morphClass)
200 ->whereIn('joint_permissions.role_id', $this->getCurrentUserRoleIds())
201 ->where(function (QueryBuilder $query) {
202 $this->addJointHasPermissionCheck($query, $this->currentUser()->id);
206 $q = $query->where(function ($query) use ($existsQuery, $fullPageIdColumn) {
207 $query->whereExists($existsQuery)
208 ->orWhere($fullPageIdColumn, '=', 0);
211 // Prevent visibility of non-owned draft pages
212 $q->whereExists(function (QueryBuilder $query) use ($fullPageIdColumn) {
213 $query->select('id')->from('pages')
214 ->whereColumn('pages.id', '=', $fullPageIdColumn)
215 ->where(function (QueryBuilder $query) {
216 $query->where('pages.draft', '=', false)
217 ->orWhere('pages.owned_by', '=', $this->currentUser()->id);
225 * Add the query for checking the given user id has permission
226 * within the join_permissions table.
228 * @param QueryBuilder|Builder $query
230 protected function addJointHasPermissionCheck($query, int $userIdToCheck)
232 $query->where('joint_permissions.has_permission', '=', true)->orWhere(function ($query) use ($userIdToCheck) {
233 $query->where('joint_permissions.has_permission_own', '=', true)
234 ->where('joint_permissions.owned_by', '=', $userIdToCheck);
239 * Get the current user.
241 protected function currentUser(): User
247 * Get the roles for the current logged-in user.
251 protected function getCurrentUserRoleIds(): array
253 if (auth()->guest()) {
254 return [Role::getSystemRole('public')->id];
257 return $this->currentUser()->roles->pluck('id')->values()->all();