Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions ProcessMaker/Contracts/PermissionRepositoryInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,9 @@ public function getGroupPermissionsById(int $groupId): array;
* Get nested group permissions (recursive)
*/
public function getNestedGroupPermissions(int $groupId): array;

/**
* Get all users affected by permissions inherited from the given group subtree.
*/
public function getAffectedUserIdsForGroup(int $groupId): array;
}
13 changes: 9 additions & 4 deletions ProcessMaker/Http/Controllers/Auth/LoginController.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
use ProcessMaker\Models\Setting;
use ProcessMaker\Models\User;
use ProcessMaker\Package\Auth\Database\Seeds\AuthDefaultSeeder;
use ProcessMaker\Services\PermissionCacheService;
use ProcessMaker\Traits\HasControllerAddons;

class LoginController extends Controller
Expand Down Expand Up @@ -262,7 +263,7 @@ public function beforeLogout(Request $request)

//Clear the user permissions
$userId = Auth::user()->id;
Cache::forget("user_{$userId}_permissions");
app(PermissionCacheService::class)->forgetLegacyUserPermissions($userId);
Cache::forget("user_{$userId}_project_assets");

// Clear the user session
Expand Down Expand Up @@ -364,9 +365,13 @@ public function login(Request $request, User $user)
return redirect()->route('password.change');
}
// Cache user permissions for a day to improve performance
Cache::remember("user_{$user->id}_permissions", 86400, function () use ($user) {
return $user->permissions()->pluck('name')->toArray();
});
app(PermissionCacheService::class)->rememberLegacyUserPermissions(
$user->id,
86400,
function () use ($user) {
return $user->permissions()->pluck('name')->toArray();
}
);

$this->setupLanguage($request, $user);

Expand Down
12 changes: 8 additions & 4 deletions ProcessMaker/Http/Middleware/CustomAuthorize.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
use Illuminate\Auth\Middleware\Authorize as Middleware;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
Expand All @@ -16,6 +15,7 @@
use ProcessMaker\Models\Screen;
use ProcessMaker\Models\Script;
use ProcessMaker\Models\User;
use ProcessMaker\Services\PermissionCacheService;
use ProcessMaker\Traits\ProjectAssetTrait;
use Symfony\Component\HttpFoundation\Response;

Expand Down Expand Up @@ -94,9 +94,13 @@ private function userHasAccessToProject($request, $userId, $models)

private function getUserPermissions($user)
{
return Cache::remember("user_{$user->id}_permissions", 86400, function () use ($user) {
return $user->permissions()->pluck('name')->toArray();
});
return app(PermissionCacheService::class)->rememberLegacyUserPermissions(
$user->id,
86400,
function () use ($user) {
return $user->permissions()->pluck('name')->toArray();
}
);
}

private function hasPermission($userPermissions, $permission)
Expand Down
8 changes: 3 additions & 5 deletions ProcessMaker/Http/Middleware/IsManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use ProcessMaker\Services\PermissionCacheService;
use Symfony\Component\HttpFoundation\Response;

class IsManager
Expand Down Expand Up @@ -76,12 +77,11 @@ private function simulateRequiredPermissionsForRequest($user, array $requiredPer
}

// simulate the permissions by adding them temporarily to the cache of permissions
$cacheKey = "user_{$user->id}_permissions";
$simulatedPermissions = array_merge($currentPermissions, $permissionsToAdd);

// save in cache temporarily (only for this request)
// use a very short time to expire quickly if not cleaned manually
Cache::put($cacheKey, $simulatedPermissions, 5); // 5 segundos como fallback
app(PermissionCacheService::class)->putLegacyUserPermissions($user->id, $simulatedPermissions, 5);
} catch (\Exception $e) {
Log::error('IsManager middleware - Error simulating permissions: ' . $e->getMessage());
}
Expand All @@ -93,10 +93,8 @@ private function simulateRequiredPermissionsForRequest($user, array $requiredPer
private function cleanupSimulatedPermission($user)
{
try {
$cacheKey = "user_{$user->id}_permissions";

// delete the cache to force the reload of real permissions
Cache::forget($cacheKey);
app(PermissionCacheService::class)->forgetLegacyUserPermissions($user->id);
} catch (\Exception $e) {
Log::error('IsManager middleware - Error cleaning up simulated permissions: ' . $e->getMessage());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@

use Illuminate\Support\Facades\Log;
use ProcessMaker\Events\GroupMembershipChanged;
use ProcessMaker\Models\Group;
use ProcessMaker\Models\User;
use ProcessMaker\Services\PermissionServiceManager;

class InvalidatePermissionCacheOnGroupHierarchyChange
Expand All @@ -28,9 +26,13 @@ public function handle(GroupMembershipChanged $event): void

// All actions (added, removed, updated) require the same cache invalidation logic
// because they all affect the permission hierarchy for the group and its descendants
$this->permissionService->invalidateAll();
if ($group) {
$this->permissionService->invalidateAffectedCachesForGroup((int) $group->id);
}

Log::info("Successfully invalidated permission cache for group hierarchy change: {$action} for group {$group->id}");
Log::info(
"Successfully invalidated permission cache for group hierarchy change: {$action} for group " . ($group?->id ?? 'unknown')
);
} catch (\Exception $e) {
Log::error('Failed to invalidate permission cache on group hierarchy change', [
'error' => $e->getMessage(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ public function handle(PermissionUpdated $event): void

// Invalidate cache for group if group permissions were updated
if ($event->getGroupId()) {
$this->permissionService->invalidateAll();
$this->permissionService->invalidateAffectedCachesForGroup((int) $event->getGroupId());
}
} catch (\Exception $e) {
Log::error('Failed to invalidate permission cache', [
Expand Down
2 changes: 1 addition & 1 deletion ProcessMaker/Models/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -591,7 +591,7 @@ public function refresh()

// Clear permissions and user_permissions
Cache::forget('permissions');
Cache::forget("user_{$this->id}_permissions");
app(\ProcessMaker\Services\PermissionCacheService::class)->forgetLegacyUserPermissions($this->id);

// return the refreshed user instance
return $this;
Expand Down
46 changes: 46 additions & 0 deletions ProcessMaker/Repositories/PermissionRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,19 @@ public function getNestedGroupPermissions(int $groupId): array
return array_unique($permissions);
}

/**
* Get all user ids affected by permissions inherited from the given group subtree.
*/
public function getAffectedUserIdsForGroup(int $groupId): array
{
$group = Group::find($groupId);
if (!$group) {
return [];
}

return $this->collectAffectedUserIds($group);
}

/**
* Get nested group permissions recursively with protection against infinite loops
*/
Expand Down Expand Up @@ -261,4 +274,37 @@ private function hasNestedGroupPermission(Group $group, string $permission, arra

return false;
}

/**
* Collect all users inside a group subtree with protection against cycles.
*/
private function collectAffectedUserIds(Group $group, array $visitedGroups = [], int $maxDepth = 25): array
{
if (in_array($group->id, $visitedGroups, true) || count($visitedGroups) >= $maxDepth) {
return [];
}

if (!$group->relationLoaded('groupMembers')) {
$group->load('groupMembers.member');
}

$visitedGroups[] = $group->id;
$userIds = [];

foreach ($group->groupMembers as $groupMember) {
if ($groupMember->member_type === User::class) {
$userIds[] = (int) $groupMember->member_id;
continue;
}

if ($groupMember->member_type === Group::class && $groupMember->member instanceof Group) {
$userIds = array_merge(
$userIds,
$this->collectAffectedUserIds($groupMember->member, $visitedGroups, $maxDepth)
);
}
}

return array_values(array_unique($userIds));
}
}
124 changes: 120 additions & 4 deletions ProcessMaker/Services/PermissionCacheService.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ class PermissionCacheService implements PermissionCacheInterface

private const GROUP_PERMISSIONS_KEY = 'group_permissions';

private const LEGACY_USER_PERMISSIONS_KEY = 'user';

private const TRACKED_PERMISSION_KEYS = 'permission_cache_keys';

/**
* Get cached permissions for a user
*/
Expand All @@ -41,6 +45,7 @@ public function cacheUserPermissions(int $userId, array $permissions): void

try {
Cache::put($key, $permissions, self::USER_PERMISSIONS_TTL);
$this->trackPermissionKey($key);
} catch (\Exception $e) {
Log::warning("Failed to cache user permissions for user {$userId}: " . $e->getMessage());
}
Expand Down Expand Up @@ -71,6 +76,7 @@ public function cacheGroupPermissions(int $groupId, array $permissions): void

try {
Cache::put($key, $permissions, self::GROUP_PERMISSIONS_TTL);
$this->trackPermissionKey($key);
} catch (\Exception $e) {
Log::warning("Failed to cache group permissions for group {$groupId}: " . $e->getMessage());
}
Expand All @@ -81,15 +87,72 @@ public function cacheGroupPermissions(int $groupId, array $permissions): void
*/
public function invalidateUserPermissions(int $userId): void
{
$key = $this->getUserPermissionsKey($userId);
$keys = [
$this->getUserPermissionsKey($userId),
$this->getLegacyUserPermissionsKey($userId),
];

try {
Cache::forget($key);
foreach ($keys as $key) {
Cache::forget($key);
$this->untrackPermissionKey($key);
}
} catch (\Exception $e) {
Log::warning("Failed to invalidate user permissions cache for user {$userId}: " . $e->getMessage());
}
}

/**
* Remember legacy user permissions and track the key for scoped clearAll().
*/
public function rememberLegacyUserPermissions(int $userId, int $ttl, callable $callback): array
{
$key = $this->getLegacyUserPermissionsKey($userId);

try {
$permissions = Cache::remember($key, $ttl, $callback);
$this->trackPermissionKey($key);

return is_array($permissions) ? $permissions : [];
} catch (\Exception $e) {
Log::warning("Failed to remember legacy user permissions for user {$userId}: " . $e->getMessage());

$permissions = $callback();

return is_array($permissions) ? $permissions : [];
}
}

/**
* Cache legacy user permissions and track the key for scoped clearAll().
*/
public function putLegacyUserPermissions(int $userId, array $permissions, int $ttl): void
{
$key = $this->getLegacyUserPermissionsKey($userId);

try {
Cache::put($key, $permissions, $ttl);
$this->trackPermissionKey($key);
} catch (\Exception $e) {
Log::warning("Failed to cache legacy user permissions for user {$userId}: " . $e->getMessage());
}
}

/**
* Forget the legacy user permission cache and remove it from the tracked index.
*/
public function forgetLegacyUserPermissions(int $userId): void
{
$key = $this->getLegacyUserPermissionsKey($userId);

try {
Cache::forget($key);
$this->untrackPermissionKey($key);
} catch (\Exception $e) {
Log::warning("Failed to forget legacy user permissions for user {$userId}: " . $e->getMessage());
}
}

/**
* Invalidate group permissions cache
*/
Expand All @@ -99,6 +162,7 @@ public function invalidateGroupPermissions(int $groupId): void

try {
Cache::forget($key);
$this->untrackPermissionKey($key);
} catch (\Exception $e) {
Log::warning("Failed to invalidate group permissions cache for group {$groupId}: " . $e->getMessage());
}
Expand All @@ -110,8 +174,11 @@ public function invalidateGroupPermissions(int $groupId): void
public function clearAll(): void
{
try {
// Clear all permission-related caches
Cache::flush();
foreach ($this->getTrackedPermissionKeys() as $key) {
Cache::forget($key);
}

Cache::forget(self::TRACKED_PERMISSION_KEYS);
} catch (\Exception $e) {
Log::warning('Failed to clear all permission caches: ' . $e->getMessage());
}
Expand All @@ -133,6 +200,14 @@ private function getGroupPermissionsKey(int $groupId): string
return self::GROUP_PERMISSIONS_KEY . ":{$groupId}";
}

/**
* Get cache key for legacy user permissions.
*/
private function getLegacyUserPermissionsKey(int $userId): string
{
return self::LEGACY_USER_PERMISSIONS_KEY . "_{$userId}_permissions";
}

/**
* Warm up cache for a user
*/
Expand Down Expand Up @@ -160,4 +235,45 @@ public function getCacheStats(): array
'cache_driver' => config('cache.default'),
];
}

/**
* Track service-managed permission keys so clearAll() can stay scoped.
*/
private function trackPermissionKey(string $key): void
{
$keys = $this->getTrackedPermissionKeys();
if (!in_array($key, $keys, true)) {
$keys[] = $key;
Cache::forever(self::TRACKED_PERMISSION_KEYS, $keys);
}
}

/**
* Stop tracking a permission key after explicit invalidation.
*/
private function untrackPermissionKey(string $key): void
{
$keys = array_values(array_filter(
$this->getTrackedPermissionKeys(),
fn ($trackedKey) => $trackedKey !== $key
));

if (empty($keys)) {
Cache::forget(self::TRACKED_PERMISSION_KEYS);

return;
}

Cache::forever(self::TRACKED_PERMISSION_KEYS, $keys);
}

/**
* Read the tracked permission keys index.
*/
private function getTrackedPermissionKeys(): array
{
$keys = Cache::get(self::TRACKED_PERMISSION_KEYS, []);

return is_array($keys) ? $keys : [];
}
}
Loading
Loading