forked from fa/breadcrumb-the-shire
72 lines
2.1 KiB
PHP
72 lines
2.1 KiB
PHP
|
|
<?php
|
||
|
|
|
||
|
|
namespace MintyPHP\Repository;
|
||
|
|
|
||
|
|
use MintyPHP\DB;
|
||
|
|
|
||
|
|
class PasswordResetRepository
|
||
|
|
{
|
||
|
|
public static function create(int $userId, string $codeHash, string $expiresAt): ?int
|
||
|
|
{
|
||
|
|
$id = DB::insert(
|
||
|
|
'insert into password_resets (user_id, code_hash, expires_at, attempts, used_at, created) values (?,?,?,?,NULL,NOW())',
|
||
|
|
(string) $userId,
|
||
|
|
$codeHash,
|
||
|
|
$expiresAt,
|
||
|
|
0
|
||
|
|
);
|
||
|
|
return $id ? (int) $id : null;
|
||
|
|
}
|
||
|
|
|
||
|
|
public static function invalidateForUser(int $userId): bool
|
||
|
|
{
|
||
|
|
$result = DB::update(
|
||
|
|
'update password_resets set used_at = NOW() where user_id = ? and used_at is null',
|
||
|
|
(string) $userId
|
||
|
|
);
|
||
|
|
return $result !== false;
|
||
|
|
}
|
||
|
|
|
||
|
|
public static function findActiveByUserId(int $userId): ?array
|
||
|
|
{
|
||
|
|
$row = DB::selectOne(
|
||
|
|
'select id, user_id, code_hash, expires_at, attempts, used_at from password_resets where user_id = ? and used_at is null and expires_at > UTC_TIMESTAMP() order by id desc limit 1',
|
||
|
|
(string) $userId
|
||
|
|
);
|
||
|
|
if (!$row || !isset($row['password_resets'])) {
|
||
|
|
return null;
|
||
|
|
}
|
||
|
|
return $row['password_resets'];
|
||
|
|
}
|
||
|
|
|
||
|
|
public static function findById(int $id): ?array
|
||
|
|
{
|
||
|
|
$row = DB::selectOne(
|
||
|
|
'select id, user_id, code_hash, expires_at, attempts, used_at from password_resets where id = ? limit 1',
|
||
|
|
(string) $id
|
||
|
|
);
|
||
|
|
if (!$row || !isset($row['password_resets'])) {
|
||
|
|
return null;
|
||
|
|
}
|
||
|
|
return $row['password_resets'];
|
||
|
|
}
|
||
|
|
|
||
|
|
public static function incrementAttempts(int $id): bool
|
||
|
|
{
|
||
|
|
$result = DB::update(
|
||
|
|
'update password_resets set attempts = attempts + 1 where id = ?',
|
||
|
|
(string) $id
|
||
|
|
);
|
||
|
|
return $result !== false;
|
||
|
|
}
|
||
|
|
|
||
|
|
public static function markUsed(int $id): bool
|
||
|
|
{
|
||
|
|
$result = DB::update(
|
||
|
|
'update password_resets set used_at = NOW() where id = ?',
|
||
|
|
(string) $id
|
||
|
|
);
|
||
|
|
return $result !== false;
|
||
|
|
}
|
||
|
|
}
|