getConnection(); $stmt = $pdo->prepare(" SELECT email, expires_at FROM password_resets WHERE token = ? AND expires_at > NOW() "); $stmt->execute([$token]); $reset = $stmt->fetch(); if ($reset) { $email = $reset['email']; $isValidToken = true; } } catch (Exception $e) { logError('Error checking reset token', ['error' => $e->getMessage()]); } } // Handle password reset form submission if ($_SERVER['REQUEST_METHOD'] === 'POST' && $isValidToken) { $newPassword = isset($_POST['password']) ? $_POST['password'] : ''; $confirmPassword = isset($_POST['confirm_password']) ? $_POST['confirm_password'] : ''; // Validation $errors = []; if (empty($newPassword)) { $errors[] = 'Password is required.'; } if (empty($confirmPassword)) { $errors[] = 'Please confirm your password.'; } if (!validatePassword($newPassword)) { $errors[] = 'Password must be at least 8 characters long.'; } if ($newPassword !== $confirmPassword) { $errors[] = 'Passwords do not match.'; } if (empty($errors)) { try { // Start transaction $pdo->beginTransaction(); // Hash new password $hashedPassword = hashPassword($newPassword); // Update user password $stmt = $pdo->prepare("UPDATE users SET password = ?, updated_at = NOW() WHERE email = ?"); $stmt->execute([$hashedPassword, $email]); // Delete used reset token $stmt = $pdo->prepare("DELETE FROM password_resets WHERE token = ?"); $stmt->execute([$token]); // Delete all user sessions (force re-login) $stmt = $pdo->prepare("DELETE FROM user_sessions WHERE user_id = (SELECT id FROM users WHERE email = ?)"); $stmt->execute([$email]); // Commit transaction $pdo->commit(); logError('Password reset successful', ['email' => $email]); // Redirect to success page showResetResult(true, 'Password Reset Successful', 'Your password has been reset successfully. You can now log in with your new password.'); } catch (PDOException $e) { if ($pdo->inTransaction()) { $pdo->rollback(); } logError('Database error during password reset', [ 'error' => $e->getMessage(), 'email' => $email ]); $errors[] = 'Failed to reset password due to a system error. Please try again later.'; } catch (Exception $e) { if ($pdo->inTransaction()) { $pdo->rollback(); } logError('General error during password reset', [ 'error' => $e->getMessage(), 'email' => $email ]); $errors[] = 'An unexpected error occurred. Please try again later.'; } } } function showResetResult($success, $title, $message) { $statusClass = $success ? 'success' : 'error'; $statusColor = $success ? '#28a745' : '#dc3545'; $iconClass = $success ? 'fa-check-circle' : 'fa-exclamation-triangle'; ?>
Enter your new password below.