2025-01-31 18:20:13 +03:00
|
|
|
<?php
|
|
|
|
|
|
|
|
declare(strict_types=1);
|
|
|
|
|
2020-06-07 19:04:43 +03:00
|
|
|
namespace openvk\Web\Models\Entities;
|
2025-01-31 18:20:13 +03:00
|
|
|
|
2020-06-07 19:04:43 +03:00
|
|
|
use openvk\Web\Models\Repositories\Users;
|
|
|
|
use openvk\Web\Models\RowModel;
|
|
|
|
use openvk\Web\Util\DateTime;
|
|
|
|
|
|
|
|
class PasswordReset extends RowModel
|
|
|
|
{
|
|
|
|
protected $tableName = "password_resets";
|
2025-01-31 18:20:13 +03:00
|
|
|
|
|
|
|
public function getUser(): User
|
2020-06-07 19:04:43 +03:00
|
|
|
{
|
2025-01-31 18:20:13 +03:00
|
|
|
return (new Users())->get($this->getRecord()->profile);
|
2020-06-07 19:04:43 +03:00
|
|
|
}
|
2025-01-31 18:20:13 +03:00
|
|
|
|
|
|
|
public function getKey(): string
|
2020-06-07 19:04:43 +03:00
|
|
|
{
|
|
|
|
return $this->getRecord()->key;
|
|
|
|
}
|
2025-01-31 18:20:13 +03:00
|
|
|
|
|
|
|
public function getToken(): string
|
2020-06-07 19:04:43 +03:00
|
|
|
{
|
|
|
|
return $this->getKey();
|
|
|
|
}
|
2025-01-31 18:20:13 +03:00
|
|
|
|
|
|
|
public function getCreationTime(): DateTime
|
2020-06-07 19:04:43 +03:00
|
|
|
{
|
|
|
|
return new DateTime($this->getRecord()->timestamp);
|
|
|
|
}
|
2025-01-31 18:20:13 +03:00
|
|
|
|
2020-06-07 19:04:43 +03:00
|
|
|
/**
|
|
|
|
* User can request password reset only if he does not have any "new" password resets.
|
|
|
|
* Password reset becomes "old" after 5 minutes and one second.
|
|
|
|
*/
|
2025-01-31 18:20:13 +03:00
|
|
|
public function isNew(): bool
|
2020-06-07 19:04:43 +03:00
|
|
|
{
|
2022-01-31 14:45:53 +03:00
|
|
|
return $this->getRecord()->timestamp > (time() - (5 * MINUTE));
|
2020-06-07 19:04:43 +03:00
|
|
|
}
|
2025-01-31 18:20:13 +03:00
|
|
|
|
2022-01-31 14:45:53 +03:00
|
|
|
/**
|
|
|
|
* Token is valid only for 3 days.
|
|
|
|
*/
|
2025-01-31 18:20:13 +03:00
|
|
|
public function isStillValid(): bool
|
2020-06-07 19:04:43 +03:00
|
|
|
{
|
2022-01-31 14:45:53 +03:00
|
|
|
return $this->getRecord()->timestamp > (time() - (3 * DAY));
|
2020-06-07 19:04:43 +03:00
|
|
|
}
|
2025-01-31 18:20:13 +03:00
|
|
|
|
|
|
|
public function verify(string $token): bool
|
2020-06-07 19:04:43 +03:00
|
|
|
{
|
|
|
|
try {
|
|
|
|
return $this->isStillValid() ? sodium_memcmp($this->getKey(), $token) : false;
|
2025-01-31 18:20:13 +03:00
|
|
|
} catch (\SodiumException $ex) {
|
2020-06-07 19:04:43 +03:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
2025-01-31 18:20:13 +03:00
|
|
|
|
|
|
|
public function save(?bool $log = false): void
|
2020-06-07 19:04:43 +03:00
|
|
|
{
|
|
|
|
$this->stateChanges("key", base64_encode(openssl_random_pseudo_bytes(46)));
|
|
|
|
$this->stateChanges("timestamp", time());
|
2025-01-31 18:20:13 +03:00
|
|
|
|
2023-10-31 00:13:36 +03:00
|
|
|
parent::save($log);
|
2020-06-07 19:04:43 +03:00
|
|
|
}
|
|
|
|
}
|