82 lines
2.4 KiB
PHP
82 lines
2.4 KiB
PHP
|
|
<?php
|
||
|
|
|
||
|
|
declare(strict_types=1);
|
||
|
|
|
||
|
|
namespace App\Domain\Auth;
|
||
|
|
|
||
|
|
use Doctrine\ORM\Mapping as ORM;
|
||
|
|
use Symfony\Component\Uid\Uuid;
|
||
|
|
|
||
|
|
#[ORM\Entity]
|
||
|
|
#[ORM\Table(name: 'api_keys', schema: 'app')]
|
||
|
|
class ApiKey
|
||
|
|
{
|
||
|
|
#[ORM\Id]
|
||
|
|
#[ORM\Column(type: 'uuid')]
|
||
|
|
private Uuid $id;
|
||
|
|
|
||
|
|
#[ORM\ManyToOne(targetEntity: User::class)]
|
||
|
|
#[ORM\JoinColumn(nullable: false)]
|
||
|
|
private User $user;
|
||
|
|
|
||
|
|
#[ORM\Column(type: 'string', length: 255)]
|
||
|
|
private string $label;
|
||
|
|
|
||
|
|
#[ORM\Column(type: 'string', length: 255, unique: true)]
|
||
|
|
private string $keyHash;
|
||
|
|
|
||
|
|
/** @var array<string, bool> */
|
||
|
|
#[ORM\Column(type: 'json')]
|
||
|
|
private array $permissions = [];
|
||
|
|
|
||
|
|
#[ORM\Column(type: 'boolean')]
|
||
|
|
private bool $isActive = true;
|
||
|
|
|
||
|
|
#[ORM\Column(type: 'datetime_immutable', nullable: true)]
|
||
|
|
private ?\DateTimeImmutable $lastUsedAt = null;
|
||
|
|
|
||
|
|
#[ORM\Column(type: 'datetime_immutable', nullable: true)]
|
||
|
|
private ?\DateTimeImmutable $expiresAt = null;
|
||
|
|
|
||
|
|
public function __construct(User $user, string $label, string $keyHash)
|
||
|
|
{
|
||
|
|
$this->id = Uuid::v7();
|
||
|
|
$this->user = $user;
|
||
|
|
$this->label = $label;
|
||
|
|
$this->keyHash = $keyHash;
|
||
|
|
}
|
||
|
|
|
||
|
|
public function getId(): Uuid { return $this->id; }
|
||
|
|
public function getUser(): User { return $this->user; }
|
||
|
|
public function getLabel(): string { return $this->label; }
|
||
|
|
public function getKeyHash(): string { return $this->keyHash; }
|
||
|
|
public function isActive(): bool { return $this->isActive; }
|
||
|
|
public function setIsActive(bool $active): void { $this->isActive = $active; }
|
||
|
|
public function getLastUsedAt(): ?\DateTimeImmutable { return $this->lastUsedAt; }
|
||
|
|
public function getExpiresAt(): ?\DateTimeImmutable { return $this->expiresAt; }
|
||
|
|
public function setExpiresAt(?\DateTimeImmutable $expiresAt): void { $this->expiresAt = $expiresAt; }
|
||
|
|
|
||
|
|
/** @return array<string, bool> */
|
||
|
|
public function getPermissions(): array { return $this->permissions; }
|
||
|
|
|
||
|
|
public function hasPermission(string $permission): bool
|
||
|
|
{
|
||
|
|
return $this->permissions[$permission] ?? false;
|
||
|
|
}
|
||
|
|
|
||
|
|
public function grantPermission(string $permission): void
|
||
|
|
{
|
||
|
|
$this->permissions[$permission] = true;
|
||
|
|
}
|
||
|
|
|
||
|
|
public function markUsed(): void
|
||
|
|
{
|
||
|
|
$this->lastUsedAt = new \DateTimeImmutable();
|
||
|
|
}
|
||
|
|
|
||
|
|
public function isExpired(): bool
|
||
|
|
{
|
||
|
|
return null !== $this->expiresAt && $this->expiresAt < new \DateTimeImmutable();
|
||
|
|
}
|
||
|
|
}
|