59 lines
1.3 KiB
PHP
59 lines
1.3 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Services;
|
|
|
|
use App\Exceptions\AuthServiceException;
|
|
use Illuminate\Contracts\Auth\StatefulGuard;
|
|
use Uwil\LaravelBackend\Models\User;
|
|
|
|
class AdminAuthService
|
|
{
|
|
public function __construct(
|
|
private readonly StatefulGuard $guard
|
|
) {
|
|
}
|
|
|
|
public function canWithUser(\UnitEnum | string $abilities, mixed $arguments = []): bool
|
|
{
|
|
return $this->getUser()?->can($abilities, $arguments) ?? false;
|
|
}
|
|
|
|
public function check(): bool
|
|
{
|
|
return $this->guard->check();
|
|
}
|
|
|
|
public function guest(): bool
|
|
{
|
|
return ! $this->check();
|
|
}
|
|
|
|
public function getUser(): ?User
|
|
{
|
|
$user = $this->guard->user();
|
|
|
|
if ($user && ! ($user instanceof User)) {
|
|
throw new \InvalidArgumentException('Auth service needs a backend guard');
|
|
}
|
|
|
|
return $user ? clone $user : null;
|
|
}
|
|
|
|
public function getUserAsMandatory(): User
|
|
{
|
|
$user = $this->getUser();
|
|
|
|
if ($user === null) {
|
|
throw new AuthServiceException('Authenticated user is required from here');
|
|
}
|
|
|
|
return clone $user;
|
|
}
|
|
|
|
public function getMandatoryUserId(): string
|
|
{
|
|
return (string) $this->getUserAsMandatory()->id;
|
|
}
|
|
}
|