Add a User policy to control authorization on User model

This commit is contained in:
Bubka 2024-01-26 18:22:51 +01:00
parent 3b156df8a2
commit db3a732b15
3 changed files with 102 additions and 0 deletions

View File

@ -0,0 +1,18 @@
<?php
namespace App\Policies;
use App\Models\User;
trait SelfTrait
{
/**
* Ownership of single item condition
*
* @return bool
*/
protected function isHimself(User $user, mixed $item)
{
return $user->id === $item->id;
}
}

View File

@ -0,0 +1,81 @@
<?php
namespace App\Policies;
use App\Models\User;
use Illuminate\Support\Facades\Log;
class UserPolicy
{
use SelfTrait;
/**
* Perform pre-authorization checks.
*/
public function before(User $user, string $ability): bool|null
{
if ($user->isAdministrator()) {
return true;
}
return null;
}
/**
* Determine whether the user can view any models.
*/
public function viewAny(User $user): bool
{
return false;
}
/**
* Determine whether the user can view the model.
*/
public function view(User $user, User $model): bool
{
$can = $this->isHimself($user, $model);
if (! $can) {
Log::notice(sprintf('User ID #%s cannot view users other than himself)', $user->id));
}
return $can;
}
/**
* Determine whether the user can create models.
*/
public function create(?User $user): bool
{
return true;
}
/**
* Determine whether the user can update the model.
*/
public function update(User $user, User $model): bool
{
$can = $this->isHimself($user, $model);
if (! $can) {
Log::notice(sprintf('User ID #%s cannot update users other than himself)', $user->id));
}
return $can;
}
/**
* Determine whether the user can delete the model.
*/
public function delete(User $user, User $model): bool
{
$can = $this->isHimself($user, $model);
if (! $can) {
Log::notice(sprintf('User ID #%s cannot delete users other than himself)', $user->id));
}
return $can;
}
}

View File

@ -6,8 +6,10 @@ use App\Extensions\RemoteUserProvider;
use App\Extensions\WebauthnCredentialBroker;
use App\Models\Group;
use App\Models\TwoFAccount;
use App\Models\User;
use App\Policies\GroupPolicy;
use App\Policies\TwoFAccountPolicy;
use App\Policies\UserPolicy;
use App\Services\Auth\ReverseProxyGuard;
use Illuminate\Auth\Passwords\DatabaseTokenRepository;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
@ -25,6 +27,7 @@ class AuthServiceProvider extends ServiceProvider
protected $policies = [
TwoFAccount::class => TwoFAccountPolicy::class,
Group::class => GroupPolicy::class,
User::class => UserPolicy::class,
];
/**