Add stage 7: email verification magic links and a profile page
Backend - New Mail namespace: a Mailer interface with SMTP (phpmailer), PHP mail() (the default fallback), and log-to-file transports, selected by MAIL_TRANSPORT. EmailVerifier issues a hashed, 15-minute magic-link token and sends the link (APP_URL/verify-email?token=...). - Migration 005: email_verifications table + users.verification_email_sent_at. - Registration now emails a verification link (best effort — a send failure doesn't fail registration). - POST /api/auth/verify-email consumes a token and returns a session, so opening the link verifies the address (or applies a pending email change) and logs the user in. Single-use; distinct 400s for invalid/used/expired. - POST /api/email/verification resends; POST /api/email/change requests a deferred change (current password required; link goes to the new address; users.email only updates when that link is opened). Both throttled to once per 60s, returning 429 + retry_after. - GET /api/me and every session payload now include pending_email. Shared SessionPayload builds the user/session JSON for all entry points. Frontend - /verify-email view: posts the token, adopts the returned session, redirects. - /profile view: shows address + status, a resend button with a live cooldown (driven by retry_after / 429), and a change-email form (new address + current password) that surfaces the pending change. - Header shows a "verify email" badge linking to the profile. Tests: 9 new (EmailVerificationTest) covering the link lifecycle, throttle, and deferred change; AuthTest folded into ApiTestCase, which now routes mail to a per-test log. Suite: 32 passing. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,54 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Auth;
|
||||
|
||||
use App\Repository\EmailVerificationRepository;
|
||||
|
||||
/**
|
||||
* Builds the JSON representation of a user and the session envelope returned by
|
||||
* register / login / email verification. Shared so every entry point agrees on
|
||||
* the shape.
|
||||
*/
|
||||
final class SessionPayload
|
||||
{
|
||||
public function __construct(
|
||||
private readonly JwtService $jwt,
|
||||
private readonly EmailVerificationRepository $tokens,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{id: int, email: string, email_verified_at: string|null, created_at: string} $user
|
||||
* @return array{user: array<string, mixed>, token: string, expires_at: string}
|
||||
*/
|
||||
public function forUser(array $user): array
|
||||
{
|
||||
$issued = $this->jwt->issue($user);
|
||||
|
||||
return [
|
||||
'user' => $this->present($user),
|
||||
'token' => $issued['token'],
|
||||
'expires_at' => $issued['expires_at'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{id: int, email: string, email_verified_at?: string|null, created_at?: string} $user
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function present(array $user): array
|
||||
{
|
||||
$verifiedAt = $user['email_verified_at'] ?? null;
|
||||
|
||||
return [
|
||||
'id' => (int) $user['id'],
|
||||
'email' => $user['email'],
|
||||
'email_verified' => $verifiedAt !== null,
|
||||
'email_verified_at' => $verifiedAt,
|
||||
'pending_email' => $this->tokens->pendingEmailFor((int) $user['id']),
|
||||
'created_at' => $user['created_at'] ?? null,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -4,9 +4,11 @@ declare(strict_types=1);
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Auth\JwtService;
|
||||
use App\Auth\SessionPayload;
|
||||
use App\Exception\ApiException;
|
||||
use App\Exception\ValidationException;
|
||||
use App\Mail\EmailVerifier;
|
||||
use App\Mail\MailException;
|
||||
use App\Repository\UserRepository;
|
||||
use Psr\Http\Message\ResponseInterface as Response;
|
||||
use Psr\Http\Message\ServerRequestInterface as Request;
|
||||
@@ -22,7 +24,8 @@ final class AuthController extends Controller
|
||||
|
||||
public function __construct(
|
||||
private readonly UserRepository $users,
|
||||
private readonly JwtService $jwt,
|
||||
private readonly SessionPayload $session,
|
||||
private readonly EmailVerifier $verifier,
|
||||
) {
|
||||
}
|
||||
|
||||
@@ -39,7 +42,15 @@ final class AuthController extends Controller
|
||||
|
||||
$user = $this->users->create($email, password_hash($password, PASSWORD_DEFAULT));
|
||||
|
||||
return $this->json($response, $this->session($user), 201);
|
||||
// Best effort: a failed send must not fail registration — the user can
|
||||
// resend from their profile.
|
||||
try {
|
||||
$this->verifier->sendVerification($user);
|
||||
} catch (MailException $e) {
|
||||
error_log('Verification email failed for user ' . $user['id'] . ': ' . $e->getMessage());
|
||||
}
|
||||
|
||||
return $this->json($response, $this->session->forUser($user), 201);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -56,7 +67,7 @@ final class AuthController extends Controller
|
||||
throw new ApiException('Invalid email or password.', 401);
|
||||
}
|
||||
|
||||
return $this->json($response, $this->session($user));
|
||||
return $this->json($response, $this->session->forUser($user));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -64,10 +75,7 @@ final class AuthController extends Controller
|
||||
*/
|
||||
public function me(Request $request, Response $response): Response
|
||||
{
|
||||
/** @var array{id: int, email: string, email_verified_at: string|null, created_at: string} $user */
|
||||
$user = $request->getAttribute('user');
|
||||
|
||||
return $this->json($response, ['user' => $this->presentUser($user)]);
|
||||
return $this->json($response, ['user' => $this->session->present($this->user($request))]);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -106,38 +114,4 @@ final class AuthController extends Controller
|
||||
|
||||
return [mb_strtolower($email), $password];
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the standard authentication payload returned by register and login.
|
||||
*
|
||||
* @param array{id: int, email: string, email_verified_at: string|null, created_at: string} $user
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function session(array $user): array
|
||||
{
|
||||
$token = $this->jwt->issue($user);
|
||||
|
||||
return [
|
||||
'user' => $this->presentUser($user),
|
||||
'token' => $token['token'],
|
||||
'expires_at' => $token['expires_at'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{id: int, email: string, email_verified_at?: string|null, created_at?: string} $user
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function presentUser(array $user): array
|
||||
{
|
||||
$verifiedAt = $user['email_verified_at'] ?? null;
|
||||
|
||||
return [
|
||||
'id' => (int) $user['id'],
|
||||
'email' => $user['email'],
|
||||
'email_verified' => $verifiedAt !== null,
|
||||
'email_verified_at' => $verifiedAt,
|
||||
'created_at' => $user['created_at'] ?? null,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -41,13 +41,13 @@ abstract class Controller
|
||||
}
|
||||
|
||||
/**
|
||||
* The authenticated user attached by AuthMiddleware.
|
||||
* The authenticated user row attached by AuthMiddleware.
|
||||
*
|
||||
* @return array{id: int, email: string, email_verified_at: string|null, created_at: string}
|
||||
* @return array{id: int, email: string, password_hash: string, email_verified_at: string|null, verification_email_sent_at: string|null, created_at: string, updated_at: string}
|
||||
*/
|
||||
protected function user(Request $request): array
|
||||
{
|
||||
/** @var array{id: int, email: string, email_verified_at: string|null, created_at: string} $user */
|
||||
/** @var array{id: int, email: string, password_hash: string, email_verified_at: string|null, verification_email_sent_at: string|null, created_at: string, updated_at: string} $user */
|
||||
$user = $request->getAttribute('user');
|
||||
|
||||
return $user;
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Auth\SessionPayload;
|
||||
use App\Exception\ApiException;
|
||||
use App\Exception\ValidationException;
|
||||
use App\Mail\EmailVerifier;
|
||||
use App\Mail\MailException;
|
||||
use App\Repository\EmailVerificationRepository;
|
||||
use App\Repository\UserRepository;
|
||||
use Psr\Http\Message\ResponseInterface as Response;
|
||||
use Psr\Http\Message\ServerRequestInterface as Request;
|
||||
|
||||
final class EmailVerificationController extends Controller
|
||||
{
|
||||
private const RESEND_INTERVAL_SECONDS = 60;
|
||||
private const EMAIL_MAX = 255;
|
||||
private const PASSWORD_MAX = 72;
|
||||
|
||||
public function __construct(
|
||||
private readonly UserRepository $users,
|
||||
private readonly EmailVerificationRepository $tokens,
|
||||
private readonly EmailVerifier $verifier,
|
||||
private readonly SessionPayload $session,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/auth/verify-email (public)
|
||||
*
|
||||
* Consumes a magic-link token: verifies the address (or applies a pending
|
||||
* email change), then returns a session so the caller is logged in.
|
||||
*/
|
||||
public function verify(Request $request, Response $response): Response
|
||||
{
|
||||
$token = trim((string) ($this->body($request)['token'] ?? ''));
|
||||
if ($token === '') {
|
||||
throw new ValidationException(['token' => ['A verification token is required.']]);
|
||||
}
|
||||
|
||||
$row = $this->tokens->findByHash(hash('sha256', $token));
|
||||
|
||||
if ($row === null) {
|
||||
throw new ApiException('This verification link is not valid.', 400);
|
||||
}
|
||||
if ($row['consumed_at'] !== null) {
|
||||
throw new ApiException('This verification link has already been used.', 400);
|
||||
}
|
||||
if (strtotime($row['expires_at']) < time()) {
|
||||
throw new ApiException('This verification link has expired. Request a new one.', 400);
|
||||
}
|
||||
|
||||
if ($row['new_email'] !== null) {
|
||||
$clash = $this->users->findByEmail($row['new_email']);
|
||||
if ($clash !== null && $clash['id'] !== $row['user_id']) {
|
||||
throw new ApiException('That email address is now in use by another account.', 409);
|
||||
}
|
||||
}
|
||||
|
||||
if (!$this->tokens->consume($row['id'])) {
|
||||
throw new ApiException('This verification link has already been used.', 400);
|
||||
}
|
||||
|
||||
if ($row['new_email'] !== null) {
|
||||
$this->users->updateEmail($row['user_id'], $row['new_email']);
|
||||
} else {
|
||||
$this->users->markEmailVerified($row['user_id']);
|
||||
}
|
||||
|
||||
$user = $this->users->findById($row['user_id']);
|
||||
if ($user === null) {
|
||||
throw new ApiException('The account for this link no longer exists.', 404);
|
||||
}
|
||||
|
||||
return $this->json($response, $this->session->forUser($user));
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/email/verification (auth) — resend the verification email.
|
||||
*/
|
||||
public function resend(Request $request, Response $response): Response
|
||||
{
|
||||
$user = $this->user($request);
|
||||
|
||||
if (($user['email_verified_at'] ?? null) !== null) {
|
||||
throw new ApiException('Your email address is already verified.', 409);
|
||||
}
|
||||
|
||||
$this->guardResendInterval($user);
|
||||
|
||||
try {
|
||||
$this->verifier->sendVerification($user);
|
||||
} catch (MailException $e) {
|
||||
throw new ApiException('Could not send the email right now. Please try again shortly.', 502);
|
||||
}
|
||||
|
||||
return $this->json($response, [
|
||||
'message' => 'Verification email sent.',
|
||||
'retry_after' => self::RESEND_INTERVAL_SECONDS,
|
||||
], 202);
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/email/change (auth) — request a deferred email change. The new
|
||||
* address only takes effect once its magic link is opened.
|
||||
*/
|
||||
public function requestChange(Request $request, Response $response): Response
|
||||
{
|
||||
$user = $this->user($request);
|
||||
$body = $this->body($request);
|
||||
|
||||
$newEmail = is_string($body['email'] ?? null) ? mb_strtolower(trim($body['email'])) : '';
|
||||
$password = is_string($body['password'] ?? null) ? $body['password'] : '';
|
||||
|
||||
$errors = [];
|
||||
if ($newEmail === '') {
|
||||
$errors['email'][] = 'Email is required.';
|
||||
} elseif (!filter_var($newEmail, FILTER_VALIDATE_EMAIL) || strlen($newEmail) > self::EMAIL_MAX) {
|
||||
$errors['email'][] = 'Enter a valid email address.';
|
||||
} elseif ($newEmail === mb_strtolower($user['email'])) {
|
||||
$errors['email'][] = 'That is already your email address.';
|
||||
}
|
||||
if ($password === '' || strlen($password) > self::PASSWORD_MAX) {
|
||||
$errors['password'][] = 'Your current password is required.';
|
||||
}
|
||||
if ($errors !== []) {
|
||||
throw new ValidationException($errors);
|
||||
}
|
||||
|
||||
$full = $this->users->findById($user['id']);
|
||||
if ($full === null || !password_verify($password, $full['password_hash'])) {
|
||||
throw new ValidationException(['password' => ['That password is incorrect.']]);
|
||||
}
|
||||
|
||||
if ($this->users->findByEmail($newEmail) !== null) {
|
||||
throw new ApiException('That email address is already in use.', 409);
|
||||
}
|
||||
|
||||
$this->guardResendInterval($user);
|
||||
|
||||
try {
|
||||
$this->verifier->sendEmailChange($user, $newEmail);
|
||||
} catch (MailException $e) {
|
||||
throw new ApiException('Could not send the email right now. Please try again shortly.', 502);
|
||||
}
|
||||
|
||||
return $this->json($response, [
|
||||
'message' => 'Confirmation email sent to the new address.',
|
||||
'pending_email' => $newEmail,
|
||||
'retry_after' => self::RESEND_INTERVAL_SECONDS,
|
||||
], 202);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{verification_email_sent_at?: string|null} $user
|
||||
*/
|
||||
private function guardResendInterval(array $user): void
|
||||
{
|
||||
$lastSent = $user['verification_email_sent_at'] ?? null;
|
||||
if ($lastSent === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
$elapsed = time() - (int) strtotime($lastSent);
|
||||
if ($elapsed < self::RESEND_INTERVAL_SECONDS) {
|
||||
throw new ApiException(
|
||||
'Please wait a moment before requesting another email.',
|
||||
429,
|
||||
['retry_after' => self::RESEND_INTERVAL_SECONDS - $elapsed],
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Mail;
|
||||
|
||||
use App\Repository\EmailVerificationRepository;
|
||||
use App\Repository\UserRepository;
|
||||
|
||||
/**
|
||||
* Issues a magic-link token and emails it, for both "verify your address" and
|
||||
* "confirm your new address" flows.
|
||||
*/
|
||||
final class EmailVerifier
|
||||
{
|
||||
public const TOKEN_TTL_SECONDS = 900; // 15 minutes
|
||||
|
||||
public function __construct(
|
||||
private readonly EmailVerificationRepository $tokens,
|
||||
private readonly UserRepository $users,
|
||||
private readonly Mailer $mailer,
|
||||
private readonly string $appUrl,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a link that verifies the user's current address.
|
||||
*
|
||||
* @param array{id: int, email: string} $user
|
||||
*/
|
||||
public function sendVerification(array $user): void
|
||||
{
|
||||
$link = $this->issue((int) $user['id'], null);
|
||||
|
||||
$this->mailer->send(
|
||||
$user['email'],
|
||||
'Verify your email address',
|
||||
"Welcome!\n\n"
|
||||
. "Confirm this email address by opening the link below. It expires in 15 minutes.\n\n"
|
||||
. $link . "\n\n"
|
||||
. "If you didn't create an account, you can ignore this message.\n",
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a link (to the new address) that, once opened, changes the user's
|
||||
* email to $newEmail.
|
||||
*
|
||||
* @param array{id: int, email: string} $user
|
||||
*/
|
||||
public function sendEmailChange(array $user, string $newEmail): void
|
||||
{
|
||||
$link = $this->issue((int) $user['id'], $newEmail);
|
||||
|
||||
$this->mailer->send(
|
||||
$newEmail,
|
||||
'Confirm your new email address',
|
||||
"A request was made to change the email address on an account to this one.\n\n"
|
||||
. "Confirm the change by opening the link below. It expires in 15 minutes.\n\n"
|
||||
. $link . "\n\n"
|
||||
. "If this wasn't you, you can ignore this message; nothing will change.\n",
|
||||
);
|
||||
}
|
||||
|
||||
private function issue(int $userId, ?string $newEmail): string
|
||||
{
|
||||
$token = bin2hex(random_bytes(32));
|
||||
|
||||
$this->tokens->issue($userId, hash('sha256', $token), $newEmail, self::TOKEN_TTL_SECONDS);
|
||||
$this->users->markVerificationEmailSent($userId);
|
||||
|
||||
return $this->appUrl . '/verify-email?token=' . $token;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Mail;
|
||||
|
||||
/**
|
||||
* Appends each message as a JSON line to a file instead of sending it. Handy for
|
||||
* local development and used by the test suite. Enable with MAIL_TRANSPORT=log.
|
||||
*/
|
||||
final class LogMailer implements Mailer
|
||||
{
|
||||
public function __construct(private readonly string $path)
|
||||
{
|
||||
}
|
||||
|
||||
public function send(string $to, string $subject, string $body): void
|
||||
{
|
||||
$dir = dirname($this->path);
|
||||
if (!is_dir($dir)) {
|
||||
mkdir($dir, 0775, true);
|
||||
}
|
||||
|
||||
$line = json_encode([
|
||||
'sent_at' => gmdate('c'),
|
||||
'to' => $to,
|
||||
'subject' => $subject,
|
||||
'body' => $body,
|
||||
], JSON_UNESCAPED_SLASHES) . "\n";
|
||||
|
||||
if (file_put_contents($this->path, $line, FILE_APPEND | LOCK_EX) === false) {
|
||||
throw new MailException("Could not write to the mail log at {$this->path}.");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Mail;
|
||||
|
||||
use RuntimeException;
|
||||
|
||||
final class MailException extends RuntimeException
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Mail;
|
||||
|
||||
interface Mailer
|
||||
{
|
||||
/**
|
||||
* Send a plain-text email.
|
||||
*
|
||||
* @throws MailException when delivery fails.
|
||||
*/
|
||||
public function send(string $to, string $subject, string $body): void;
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Mail;
|
||||
|
||||
use App\Support\MailConfig;
|
||||
use PHPMailer\PHPMailer\Exception as PhpMailerException;
|
||||
use PHPMailer\PHPMailer\PHPMailer;
|
||||
|
||||
/**
|
||||
* Sends via SMTP when MAIL_TRANSPORT=smtp, otherwise via PHP's mail() function.
|
||||
*/
|
||||
final class PhpMailerMailer implements Mailer
|
||||
{
|
||||
public function __construct(private readonly MailConfig $config)
|
||||
{
|
||||
}
|
||||
|
||||
public function send(string $to, string $subject, string $body): void
|
||||
{
|
||||
$mail = new PHPMailer(true);
|
||||
|
||||
try {
|
||||
if ($this->config->transport === 'smtp') {
|
||||
$this->configureSmtp($mail);
|
||||
} else {
|
||||
$mail->isMail();
|
||||
}
|
||||
|
||||
$mail->setFrom($this->config->fromAddress, $this->config->fromName);
|
||||
$mail->addAddress($to);
|
||||
$mail->Subject = $subject;
|
||||
$mail->isHTML(false);
|
||||
$mail->Body = $body;
|
||||
|
||||
$mail->send();
|
||||
} catch (PhpMailerException $e) {
|
||||
throw new MailException('Failed to send email: ' . $e->getMessage(), 0, $e);
|
||||
}
|
||||
}
|
||||
|
||||
private function configureSmtp(PHPMailer $mail): void
|
||||
{
|
||||
$mail->isSMTP();
|
||||
$mail->Host = (string) $this->config->smtpHost;
|
||||
$mail->Port = $this->config->smtpPort;
|
||||
|
||||
if ($this->config->smtpUsername !== null) {
|
||||
$mail->SMTPAuth = true;
|
||||
$mail->Username = $this->config->smtpUsername;
|
||||
$mail->Password = (string) $this->config->smtpPassword;
|
||||
}
|
||||
|
||||
switch ($this->config->smtpEncryption) {
|
||||
case 'ssl':
|
||||
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
|
||||
break;
|
||||
case 'none':
|
||||
$mail->SMTPSecure = '';
|
||||
$mail->SMTPAutoTLS = false;
|
||||
break;
|
||||
default:
|
||||
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Repository;
|
||||
|
||||
use PDO;
|
||||
|
||||
/**
|
||||
* Data access for `email_verifications` (magic-link tokens).
|
||||
*
|
||||
* @phpstan-type TokenRow array{
|
||||
* id: int, user_id: int, token_hash: string, new_email: string|null,
|
||||
* expires_at: string, consumed_at: string|null, created_at: string
|
||||
* }
|
||||
*/
|
||||
final class EmailVerificationRepository
|
||||
{
|
||||
public function __construct(private readonly PDO $pdo)
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace any outstanding (unconsumed) tokens of the same kind for the user,
|
||||
* then store a new one.
|
||||
*/
|
||||
public function issue(int $userId, string $tokenHash, ?string $newEmail, int $ttlSeconds): void
|
||||
{
|
||||
// Drop the user's outstanding tokens of the same kind (verify vs. change).
|
||||
$nullClause = $newEmail === null ? 'new_email IS NULL' : 'new_email IS NOT NULL';
|
||||
$this->pdo
|
||||
->prepare("DELETE FROM email_verifications WHERE user_id = :user AND consumed_at IS NULL AND {$nullClause}")
|
||||
->execute(['user' => $userId]);
|
||||
|
||||
$insert = $this->pdo->prepare(
|
||||
'INSERT INTO email_verifications (user_id, token_hash, new_email, expires_at)
|
||||
VALUES (:user, :hash, :new_email, :expires_at)'
|
||||
);
|
||||
$insert->execute([
|
||||
'user' => $userId,
|
||||
'hash' => $tokenHash,
|
||||
'new_email' => $newEmail,
|
||||
'expires_at' => gmdate('Y-m-d\TH:i:s\Z', time() + $ttlSeconds),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return TokenRow|null
|
||||
*/
|
||||
public function findByHash(string $tokenHash): ?array
|
||||
{
|
||||
$stmt = $this->pdo->prepare('SELECT * FROM email_verifications WHERE token_hash = :hash');
|
||||
$stmt->execute(['hash' => $tokenHash]);
|
||||
|
||||
$row = $stmt->fetch();
|
||||
if ($row === false) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$row['id'] = (int) $row['id'];
|
||||
$row['user_id'] = (int) $row['user_id'];
|
||||
|
||||
/** @var TokenRow $row */
|
||||
return $row;
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark the token consumed. Returns false if it was already consumed (race).
|
||||
*/
|
||||
public function consume(int $id): bool
|
||||
{
|
||||
$stmt = $this->pdo->prepare(
|
||||
"UPDATE email_verifications SET consumed_at = strftime('%Y-%m-%dT%H:%M:%SZ', 'now')
|
||||
WHERE id = :id AND consumed_at IS NULL"
|
||||
);
|
||||
$stmt->execute(['id' => $id]);
|
||||
|
||||
return $stmt->rowCount() === 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* The address a still-valid change request is waiting on, if any.
|
||||
*/
|
||||
public function pendingEmailFor(int $userId): ?string
|
||||
{
|
||||
$stmt = $this->pdo->prepare(
|
||||
"SELECT new_email FROM email_verifications
|
||||
WHERE user_id = :user AND new_email IS NOT NULL AND consumed_at IS NULL
|
||||
AND expires_at > strftime('%Y-%m-%dT%H:%M:%SZ', 'now')
|
||||
ORDER BY id DESC LIMIT 1"
|
||||
);
|
||||
$stmt->execute(['user' => $userId]);
|
||||
|
||||
$value = $stmt->fetchColumn();
|
||||
|
||||
return $value === false ? null : (string) $value;
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,7 @@ use PDO;
|
||||
/**
|
||||
* Data access for the `users` table. Rows are returned as associative arrays.
|
||||
*
|
||||
* @phpstan-type UserRow array{id: int, email: string, password_hash: string, email_verified_at: string|null, created_at: string, updated_at: string}
|
||||
* @phpstan-type UserRow array{id: int, email: string, password_hash: string, email_verified_at: string|null, verification_email_sent_at: string|null, created_at: string, updated_at: string}
|
||||
*/
|
||||
final class UserRepository
|
||||
{
|
||||
@@ -62,6 +62,35 @@ final class UserRepository
|
||||
return $user;
|
||||
}
|
||||
|
||||
public function markEmailVerified(int $id): void
|
||||
{
|
||||
$this->pdo->prepare(
|
||||
"UPDATE users SET email_verified_at = strftime('%Y-%m-%dT%H:%M:%SZ', 'now'),
|
||||
updated_at = strftime('%Y-%m-%dT%H:%M:%SZ', 'now')
|
||||
WHERE id = :id"
|
||||
)->execute(['id' => $id]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply a confirmed email change: set the address and mark it verified.
|
||||
*/
|
||||
public function updateEmail(int $id, string $email): void
|
||||
{
|
||||
$this->pdo->prepare(
|
||||
"UPDATE users SET email = :email,
|
||||
email_verified_at = strftime('%Y-%m-%dT%H:%M:%SZ', 'now'),
|
||||
updated_at = strftime('%Y-%m-%dT%H:%M:%SZ', 'now')
|
||||
WHERE id = :id"
|
||||
)->execute(['email' => $email, 'id' => $id]);
|
||||
}
|
||||
|
||||
public function markVerificationEmailSent(int $id): void
|
||||
{
|
||||
$this->pdo->prepare(
|
||||
"UPDATE users SET verification_email_sent_at = strftime('%Y-%m-%dT%H:%M:%SZ', 'now') WHERE id = :id"
|
||||
)->execute(['id' => $id]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $row
|
||||
* @return UserRow
|
||||
|
||||
+23
-1
@@ -15,6 +15,9 @@ final class Config
|
||||
public readonly string $jwtSecret,
|
||||
public readonly int $jwtTtl,
|
||||
public readonly bool $displayErrors,
|
||||
/** Base URL of the frontend, used to build magic links. */
|
||||
public readonly string $appUrl,
|
||||
public readonly MailConfig $mail,
|
||||
) {
|
||||
}
|
||||
|
||||
@@ -38,7 +41,26 @@ final class Config
|
||||
$jwtTtl = (int) (self::env('JWT_TTL') ?? '86400');
|
||||
$displayErrors = filter_var(self::env('APP_DEBUG', 'false'), FILTER_VALIDATE_BOOL);
|
||||
|
||||
return new self($databasePath, $jwtSecret, $jwtTtl, $displayErrors);
|
||||
$appUrl = rtrim(self::env('APP_URL', 'http://localhost:5173'), '/');
|
||||
|
||||
$mailLogPath = self::env('MAIL_LOG_PATH', $storagePath . '/mail.log');
|
||||
if (!self::isAbsolutePath($mailLogPath)) {
|
||||
$mailLogPath = $basePath . '/' . ltrim($mailLogPath, '/');
|
||||
}
|
||||
|
||||
$mail = new MailConfig(
|
||||
transport: strtolower(self::env('MAIL_TRANSPORT', 'mail')),
|
||||
fromAddress: self::env('MAIL_FROM', 'no-reply@localhost'),
|
||||
fromName: self::env('MAIL_FROM_NAME', 'Todo List'),
|
||||
logPath: $mailLogPath,
|
||||
smtpHost: self::env('MAIL_SMTP_HOST'),
|
||||
smtpPort: (int) (self::env('MAIL_SMTP_PORT') ?? '587'),
|
||||
smtpUsername: self::env('MAIL_SMTP_USERNAME'),
|
||||
smtpPassword: self::env('MAIL_SMTP_PASSWORD'),
|
||||
smtpEncryption: strtolower(self::env('MAIL_SMTP_ENCRYPTION', 'tls')),
|
||||
);
|
||||
|
||||
return new self($databasePath, $jwtSecret, $jwtTtl, $displayErrors, $appUrl, $mail);
|
||||
}
|
||||
|
||||
private static function env(string $key, ?string $default = null): ?string
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Support;
|
||||
|
||||
/**
|
||||
* Mail delivery settings.
|
||||
*
|
||||
* `transport`:
|
||||
* - "mail" (default) — PHP's built-in mail() function
|
||||
* - "smtp" — an SMTP server (host/port/credentials below)
|
||||
* - "log" — append messages to `logPath` instead of sending (dev/test)
|
||||
*/
|
||||
final class MailConfig
|
||||
{
|
||||
public function __construct(
|
||||
public readonly string $transport,
|
||||
public readonly string $fromAddress,
|
||||
public readonly string $fromName,
|
||||
public readonly string $logPath,
|
||||
public readonly ?string $smtpHost,
|
||||
public readonly int $smtpPort,
|
||||
public readonly ?string $smtpUsername,
|
||||
public readonly ?string $smtpPassword,
|
||||
public readonly string $smtpEncryption,
|
||||
) {
|
||||
}
|
||||
}
|
||||
+21
-1
@@ -4,10 +4,17 @@ declare(strict_types=1);
|
||||
|
||||
use App\Auth\AuthMiddleware;
|
||||
use App\Auth\JwtService;
|
||||
use App\Auth\SessionPayload;
|
||||
use App\Http\Controllers\AuthController;
|
||||
use App\Http\Controllers\EmailVerificationController;
|
||||
use App\Http\Controllers\TodoItemController;
|
||||
use App\Http\Controllers\TodoListController;
|
||||
use App\Http\JsonErrorHandler;
|
||||
use App\Mail\EmailVerifier;
|
||||
use App\Mail\LogMailer;
|
||||
use App\Mail\Mailer;
|
||||
use App\Mail\PhpMailerMailer;
|
||||
use App\Repository\EmailVerificationRepository;
|
||||
use App\Repository\TodoItemRepository;
|
||||
use App\Repository\TodoListRepository;
|
||||
use App\Repository\UserRepository;
|
||||
@@ -36,9 +43,18 @@ $errorMiddleware->setDefaultErrorHandler(
|
||||
$users = new UserRepository($database->pdo());
|
||||
$todoLists = new TodoListRepository($database->pdo());
|
||||
$todoItems = new TodoItemRepository($database->pdo());
|
||||
$verificationTokens = new EmailVerificationRepository($database->pdo());
|
||||
$jwt = new JwtService($config->jwtSecret, $config->jwtTtl);
|
||||
$session = new SessionPayload($jwt, $verificationTokens);
|
||||
|
||||
$authController = new AuthController($users, $jwt);
|
||||
/** @var Mailer $mailer */
|
||||
$mailer = $config->mail->transport === 'log'
|
||||
? new LogMailer($config->mail->logPath)
|
||||
: new PhpMailerMailer($config->mail);
|
||||
$verifier = new EmailVerifier($verificationTokens, $users, $mailer, $config->appUrl);
|
||||
|
||||
$authController = new AuthController($users, $session, $verifier);
|
||||
$emailController = new EmailVerificationController($users, $verificationTokens, $verifier, $session);
|
||||
$listController = new TodoListController($todoLists);
|
||||
$itemController = new TodoItemController($todoLists, $todoItems);
|
||||
$authMiddleware = new AuthMiddleware($jwt, $users);
|
||||
@@ -47,6 +63,7 @@ $authMiddleware = new AuthMiddleware($jwt, $users);
|
||||
|
||||
$app->group('/api', function (RouteCollectorProxy $group) use (
|
||||
$authController,
|
||||
$emailController,
|
||||
$listController,
|
||||
$itemController,
|
||||
$authMiddleware,
|
||||
@@ -58,8 +75,11 @@ $app->group('/api', function (RouteCollectorProxy $group) use (
|
||||
|
||||
$group->post('/auth/register', [$authController, 'register']);
|
||||
$group->post('/auth/login', [$authController, 'login']);
|
||||
$group->post('/auth/verify-email', [$emailController, 'verify']);
|
||||
|
||||
$group->get('/me', [$authController, 'me'])->add($authMiddleware);
|
||||
$group->post('/email/verification', [$emailController, 'resend'])->add($authMiddleware);
|
||||
$group->post('/email/change', [$emailController, 'requestChange'])->add($authMiddleware);
|
||||
|
||||
$group->group('/lists', function (RouteCollectorProxy $lists) use ($listController, $itemController) {
|
||||
$lists->get('', [$listController, 'index']);
|
||||
|
||||
Reference in New Issue
Block a user