openvk/Web/Models/Entities/PasswordReset.php

69 lines
1.6 KiB
PHP
Raw Normal View History

<?php
declare(strict_types=1);
2020-06-07 19:04:43 +03:00
namespace openvk\Web\Models\Entities;
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";
public function getUser(): User
2020-06-07 19:04:43 +03:00
{
return (new Users())->get($this->getRecord()->profile);
2020-06-07 19:04:43 +03:00
}
public function getKey(): string
2020-06-07 19:04:43 +03:00
{
return $this->getRecord()->key;
}
public function getToken(): string
2020-06-07 19:04:43 +03:00
{
return $this->getKey();
}
public function getCreationTime(): DateTime
2020-06-07 19:04:43 +03:00
{
return new DateTime($this->getRecord()->timestamp);
}
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.
*/
public function isNew(): bool
2020-06-07 19:04:43 +03:00
{
return $this->getRecord()->timestamp > (time() - (5 * MINUTE));
2020-06-07 19:04:43 +03:00
}
/**
* Token is valid only for 3 days.
*/
public function isStillValid(): bool
2020-06-07 19:04:43 +03:00
{
return $this->getRecord()->timestamp > (time() - (3 * DAY));
2020-06-07 19:04:43 +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;
} catch (\SodiumException $ex) {
2020-06-07 19:04:43 +03:00
return false;
}
}
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());
parent::save($log);
2020-06-07 19:04:43 +03:00
}
}