1
0
Files
breadcrumb-the-shire/lib/Service/PasswordResetService.php
2026-02-04 23:31:53 +01:00

148 lines
5.1 KiB
PHP

<?php
namespace MintyPHP\Service;
use MintyPHP\Repository\PasswordResetRepository;
use MintyPHP\Repository\UserRepository;
use MintyPHP\I18n;
use MintyPHP\Http\Request;
use MintyPHP\Service\RememberMeService;
class PasswordResetService
{
private const CODE_LENGTH = 6;
private const EXPIRY_MINUTES = 15;
private const MAX_ATTEMPTS = 5;
public static function requestReset(string $email, ?string $locale = null): array
{
$email = trim($email);
if ($email === '') {
return ['ok' => false, 'error' => 'email_required'];
}
$user = UserRepository::findByEmail($email);
if (!$user || !isset($user['id'])) {
return ['ok' => true];
}
$userId = (int) $user['id'];
PasswordResetRepository::invalidateForUser($userId);
$code = self::generateCode();
$codeHash = password_hash($code, PASSWORD_DEFAULT);
$expiresAt = gmdate('Y-m-d H:i:s', time() + (self::EXPIRY_MINUTES * 60));
$resetId = PasswordResetRepository::create($userId, $codeHash, $expiresAt);
if (!$resetId) {
return ['ok' => false, 'error' => 'create_failed'];
}
$locale = $locale ?: ($user['locale'] ?? null) ?: (I18n::$locale ?? I18n::$defaultLocale);
$name = trim(($user['first_name'] ?? '') . ' ' . ($user['last_name'] ?? ''));
$isGerman = strpos((string) $locale, 'de') === 0;
$greeting = $isGerman ? 'Hallo' : 'Hello';
if ($name !== '') {
$greeting .= ' ' . $name;
}
$greeting .= ',';
$verifyPath = Request::withLocale('password/verify', $locale);
$verifyUrl = appUrl($verifyPath);
$previousLocale = I18n::$locale ?? null;
I18n::$locale = $locale;
$subject = t('Password reset code');
I18n::$locale = $previousLocale;
$vars = [
'app_name' => appTitle(),
'app_logo_url' => appLogoUrlAbsolute(128),
'imprint_url' => appUrl(Request::withLocale('imprint', $locale)),
'privacy_url' => appUrl(Request::withLocale('privacy', $locale)),
'code' => $code,
'expires_minutes' => self::EXPIRY_MINUTES,
'verify_url' => $verifyUrl,
'greeting' => $greeting,
];
MailService::sendTemplate('reset_code', $vars, $email, $subject, $locale);
return ['ok' => true];
}
public static function verifyCode(string $email, string $code): array
{
$email = trim($email);
$code = trim($code);
if ($email === '' || $code === '') {
return ['ok' => false, 'error' => 'invalid'];
}
$user = UserRepository::findByEmail($email);
if (!$user || !isset($user['id'])) {
return ['ok' => false, 'error' => 'invalid'];
}
$reset = PasswordResetRepository::findActiveByUserId((int) $user['id']);
if (!$reset || !isset($reset['id'])) {
return ['ok' => false, 'error' => 'invalid'];
}
$attempts = (int) ($reset['attempts'] ?? 0);
if ($attempts >= self::MAX_ATTEMPTS) {
return ['ok' => false, 'error' => 'too_many_attempts'];
}
$hash = (string) ($reset['code_hash'] ?? '');
if ($hash === '' || !password_verify($code, $hash)) {
PasswordResetRepository::incrementAttempts((int) $reset['id']);
return ['ok' => false, 'error' => 'invalid'];
}
return ['ok' => true, 'reset_id' => (int) $reset['id'], 'user_id' => (int) $user['id']];
}
public static function resetPassword(int $resetId, string $password, string $password2): array
{
$reset = PasswordResetRepository::findById($resetId);
if (!$reset || !isset($reset['id'])) {
return ['ok' => false, 'errors' => [t('Reset request not found')]];
}
if (!empty($reset['used_at'])) {
return ['ok' => false, 'errors' => [t('Reset request already used')]];
}
$expiresAt = (string) ($reset['expires_at'] ?? '');
if ($expiresAt !== '') {
try {
$expiry = new \DateTimeImmutable($expiresAt, new \DateTimeZone('UTC'));
if ($expiry->getTimestamp() <= time()) {
return ['ok' => false, 'errors' => [t('Reset request expired')]];
}
} catch (\Exception $e) {
return ['ok' => false, 'errors' => [t('Reset request expired')]];
}
}
$userId = (int) ($reset['user_id'] ?? 0);
if ($userId <= 0) {
return ['ok' => false, 'errors' => [t('Reset request not found')]];
}
$result = UserService::resetPassword($userId, $password, $password2);
if (!($result['ok'] ?? false)) {
return $result;
}
PasswordResetRepository::markUsed($resetId);
RememberMeService::forgetAllForUser($userId);
return ['ok' => true];
}
private static function generateCode(): string
{
$max = (10 ** self::CODE_LENGTH) - 1;
$code = (string) random_int(0, $max);
return str_pad($code, self::CODE_LENGTH, '0', STR_PAD_LEFT);
}
}