85 lines
2.8 KiB
PHP
85 lines
2.8 KiB
PHP
@php
|
|
use App\Models\DocumentManagerPermission;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Illuminate\Support\Facades\Auth;
|
|
use Illuminate\Support\Facades\Cache;
|
|
|
|
$userLevel = $request->get('user_level');
|
|
$permissionsJson = $request->get('permissions', '{}');
|
|
$permissions = json_decode($permissionsJson, true) ?: [];
|
|
|
|
if (!$userLevel) {
|
|
header('Content-Type: application/json');
|
|
echo json_encode(['success' => false, 'message' => 'User level is required']);
|
|
exit;
|
|
}
|
|
|
|
try {
|
|
DB::beginTransaction();
|
|
|
|
// 1. Delete ALL existing permissions for this user level
|
|
// This is the most reliable way to ensure "unchecked" permissions are removed
|
|
DocumentManagerPermission::where('user_level', $userLevel)->delete();
|
|
\Log::info("Deleted all existing permissions for user level", ['user_level' => $userLevel]);
|
|
|
|
// 2. Insert ONLY the permissions sent in the request
|
|
// We only store "Allow" permissions. Absence of a record means "No Explicit Permission"
|
|
// (which falls back to inheritance or default deny)
|
|
$insertCount = 0;
|
|
|
|
foreach ($permissions as $folderPath => $types) {
|
|
// Skip if types is not an array or empty
|
|
if (!is_array($types) || empty($types)) {
|
|
continue;
|
|
}
|
|
|
|
foreach ($types as $permissionType) {
|
|
// Only allow valid permission types
|
|
if (!in_array($permissionType, ['read', 'write'])) {
|
|
continue;
|
|
}
|
|
|
|
DocumentManagerPermission::create([
|
|
'user_level' => $userLevel,
|
|
'folder_path' => $folderPath,
|
|
'permission_type' => $permissionType,
|
|
'is_allowed' => true // We only save TRUE permissions
|
|
]);
|
|
|
|
$insertCount++;
|
|
}
|
|
}
|
|
|
|
DB::commit();
|
|
|
|
// Clear cache for this user level
|
|
DocumentManagerPermission::clearPermissionCache($userLevel);
|
|
|
|
// Log permission changes
|
|
\Log::info('Document Manager Permissions Updated', [
|
|
'user_level' => $userLevel,
|
|
'updated_by' => Auth::user()->id ?? 'Unknown',
|
|
'inserted_records' => $insertCount,
|
|
'folders_count' => count($permissions)
|
|
]);
|
|
|
|
// Clear cache after saving permissions
|
|
Cache::flush();
|
|
\App\Models\DocumentManagerPermission::clearAllCaches();
|
|
|
|
header('Content-Type: application/json');
|
|
echo json_encode(['success' => true, 'message' => 'Permissions saved successfully']);
|
|
|
|
} catch (Exception $e) {
|
|
DB::rollback();
|
|
|
|
\Log::error("Error saving permissions", [
|
|
'error' => $e->getMessage(),
|
|
'trace' => $e->getTraceAsString()
|
|
]);
|
|
|
|
header('Content-Type: application/json');
|
|
echo json_encode(['success' => false, 'message' => 'Error saving permissions: ' . $e->getMessage()]);
|
|
}
|
|
@endphp
|