AzuraCast/src/Entity/ApiKey.php

150 lines
3.2 KiB
PHP
Raw Normal View History

<?php
namespace App\Entity;
use App\Annotations\AuditLog;
use Doctrine\ORM\Mapping as ORM;
2019-09-04 18:00:51 +00:00
use Exception;
use JsonSerializable;
/**
* @ORM\Table(name="api_keys")
* @ORM\Entity()
*
* @AuditLog\Auditable
*/
2019-09-04 18:00:51 +00:00
class ApiKey implements JsonSerializable
{
public const SEPARATOR = ':';
use Traits\TruncateStrings;
/**
* @ORM\Column(name="id", type="string", length=16)
* @ORM\Id
* @var string
*/
protected $id;
/**
* @ORM\Column(name="verifier", type="string", length=128, nullable=false)
*
* @AuditLog\AuditIgnore()
*
* @var string
*/
protected $verifier;
/**
* @ORM\Column(name="user_id", type="integer")
*
* @AuditLog\AuditIgnore()
*
* @var int
*/
protected $user_id;
/**
* @ORM\ManyToOne(targetEntity="User", inversedBy="api_keys", fetch="EAGER")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="user_id", referencedColumnName="uid", onDelete="CASCADE")
* })
* @var User
*/
protected $user;
/**
* @ORM\Column(name="comment", type="string", length=255, nullable=true)
* @var string|null
*/
protected $comment;
2019-07-10 23:44:23 +00:00
/**
* @param User $user
* @param string|null $key An existing API key to import (if one exists).
*/
public function __construct(User $user, ?string $key = null)
{
$this->user = $user;
if (null !== $key) {
[$identifier, $verifier] = explode(self::SEPARATOR, $key);
$this->id = $identifier;
$this->verifier = $this->hashVerifier($verifier);
}
}
2019-09-04 18:00:51 +00:00
/**
* @param string $original
*
2019-09-04 18:00:51 +00:00
* @return string The hashed verifier.
*/
protected function hashVerifier(string $original): string
{
return hash('sha512', $original);
}
/**
* Generate a unique identifier and return both the identifier and verifier.
*
* @return array [identifier, verifier]
2019-09-04 18:00:51 +00:00
* @throws Exception
*/
public function generate(): array
{
$random_str = hash('sha256', random_bytes(32));
$identifier = substr($random_str, 0, 16);
$verifier = substr($random_str, 16, 32);
$this->id = $identifier;
$this->verifier = $this->hashVerifier($verifier);
return [$identifier, $verifier];
}
public function getId(): string
{
return $this->id;
}
/**
* Verify an incoming API key against the verifier on this record.
*
2019-12-07 00:57:50 +00:00
* @param string $verifier
*
* @return bool
*/
public function verify(string $verifier): bool
{
return hash_equals($this->verifier, $this->hashVerifier($verifier));
}
public function getUser(): User
{
return $this->user;
}
/**
* @AuditLog\AuditIdentifier
* @return string
*/
public function getComment(): ?string
{
return $this->comment;
}
public function setComment(?string $comment): void
{
2020-03-29 07:16:41 +00:00
$this->comment = $this->truncateString($comment);
}
public function jsonSerialize()
{
return [
'id' => $this->id,
'comment' => $this->comment,
];
}
}