<?php
namespace App\Entity;
use AdScore\Common\StrUtils;
use App\Component\Serializer\Normalizer\ProxyAwareObjectNormalizer;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Annotation as SA;
/**
* UserApi
*
* @ORM\Table(name="users_api")
* @ORM\Entity
*/
class UserApi extends User
{
public const KEY_TYPE = [
'static' => 'static',
];
public const SERIALIZATION_GROUP = [
UserApi::class,
User::class,
UserAllowedClient::class,
Role::class,
];
public const SERIALIZATION_CONTEXT = [
'read' => ['groups' => ['user_general', 'user_details', 'user_api'], ProxyAwareObjectNormalizer::RESOLVE_PROXY_CLASSES => self::SERIALIZATION_GROUP ],
'create' => ['groups' => ['user_general', 'user_details', 'user_api', 'user_api_create'], ProxyAwareObjectNormalizer::RESOLVE_PROXY_CLASSES => self::SERIALIZATION_GROUP ],
];
/**
* @var string|null
*
* @ORM\Column(name="description", type="string", length=255, nullable=true)
* @SA\Groups({"user_api"})
*/
private $description;
/**
* @var string
*
* @SA\Ignore
* @ORM\Column(name="`key`", type="text", length=65535, nullable=false)
*/
private $key;
/**
* @var string
*
* @ORM\Column(name="key_type", type="string", length=0, nullable=false)
* @SA\Groups({"user_api"})
*/
private $keyType;
/**
* @var string|null
* @SA\Groups({"user_api_create"})
* @SA\SerializedName("password")
*/
private $plainKey = null;
/**
* @var string|null
* @SA\Groups({"user_api_create"})
* @SA\SerializedName("auth_header")
*/
private $authHeader = null;
public function __construct(
Account $account,
?string $description = null,
?array $ipAddress = null,
?string $key = null,
string $keyType = self::KEY_TYPE['static'],
string $roleName = Role::ROLES['owner']
) {
$password = $key ?? StrUtils::generateRandomPassword(
StrUtils::PASSWORD_DEFAULT_LENGTH
);
parent::__construct($account, $roleName, User::SENTRY_LOGGING['off']);
$this->setDescription($description)
->setPlainKey($password)
->setKeyType($keyType);
if (!empty($ipAddress)) {
foreach ($ipAddress as $ip) {
$allowed = new UserAllowedClient();
$allowed->setIpAddress($ip)
->setUser($this);
}
}
}
public function getDescription(): ?string
{
return $this->description;
}
public function setDescription(?string $description): self
{
$this->description = $description;
return $this;
}
public function getKey(): ?string
{
return $this->key;
}
public function setKey(string $key): self
{
$this->key = $key;
return $this;
}
public function getKeyType(): ?string
{
return $this->keyType;
}
public function setKeyType(string $keyType): self
{
$this->keyType = $keyType;
return $this;
}
/**
* @return mixed
*/
public function getPlainKey()
{
return $this->plainKey;
}
/**
* @param mixed $plainKey
*/
public function setPlainKey($plainKey): self
{
$this->plainKey = $plainKey;
$this->setKey(StrUtils::hashPassword($plainKey));
return $this;
}
/**
* @return string|null
*/
public function getAuthHeader(): ?string
{
return "Authorization: Basic " . \base64_encode($this->getId(). ':' . $this->plainKey);
}
}