76 lines
2.0 KiB
PHP
76 lines
2.0 KiB
PHP
<?php
|
|
|
|
namespace App\Services\Access;
|
|
|
|
use App\Models\User;
|
|
use Illuminate\Support\Facades\DB;
|
|
|
|
class AccessService
|
|
{
|
|
public function tenantId(User $user, ?int $requestedTenantId = null): ?int
|
|
{
|
|
if ($requestedTenantId) {
|
|
if ($user->isMasterAdmin() || $user->userTenants()->where('tenant_id', $requestedTenantId)->exists()) {
|
|
return $requestedTenantId;
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
return $user->userTenants()
|
|
->orderByDesc('is_default')
|
|
->orderBy('id')
|
|
->value('tenant_id');
|
|
}
|
|
|
|
public function hasMenuPermission(
|
|
User $user,
|
|
string $menuSlug,
|
|
string $permission,
|
|
?int $tenantId
|
|
): bool {
|
|
if ($user->isMasterAdmin()) {
|
|
return true;
|
|
}
|
|
|
|
$column = 'can_'.$permission;
|
|
$allowed = [
|
|
'can_view',
|
|
'can_create',
|
|
'can_update',
|
|
'can_delete',
|
|
'can_approve',
|
|
'can_export',
|
|
];
|
|
|
|
if (! in_array($column, $allowed, true) || ! $tenantId) {
|
|
return false;
|
|
}
|
|
|
|
return DB::table('user_menu_groups as umg')
|
|
->join('menu_groups as mg', 'mg.id', '=', 'umg.menu_group_id')
|
|
->join('menu_group_menus as mgm', 'mgm.menu_group_id', '=', 'mg.id')
|
|
->join('menu_lists as ml', 'ml.id', '=', 'mgm.menu_id')
|
|
->where('umg.user_id', $user->id)
|
|
->where('umg.tenant_id', $tenantId)
|
|
->where('mg.is_active', true)
|
|
->where('ml.is_active', true)
|
|
->where('ml.slug', $menuSlug)
|
|
->where("mgm.$column", true)
|
|
->exists();
|
|
}
|
|
|
|
public function canManageUser(User $actor, User $target, ?int $tenantId): bool
|
|
{
|
|
if ($actor->isMasterAdmin()) {
|
|
return true;
|
|
}
|
|
|
|
if (! $actor->isTenantOwner() || ! $tenantId || $target->isMasterAdmin()) {
|
|
return false;
|
|
}
|
|
|
|
return $target->userTenants()->where('tenant_id', $tenantId)->exists();
|
|
}
|
|
}
|