Files
project-manager/src/Http/Controllers/AuthController.php
T

160 lines
5.5 KiB
PHP
Raw Normal View History

2026-09-03 17:35:10 +01:00
<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use App\Auth\SessionPayload;
2026-09-03 17:35:10 +01:00
use App\Exception\ApiException;
use App\Exception\ValidationException;
use App\Mail\EmailVerifier;
use App\Mail\MailException;
2026-09-03 17:35:10 +01:00
use App\Repository\UserRepository;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
final class AuthController extends Controller
{
private const PASSWORD_MIN = 8;
// bcrypt (password_hash's current default) only considers the first 72 bytes.
private const PASSWORD_MAX = 72;
private const EMAIL_MAX = 255;
public function __construct(
private readonly UserRepository $users,
private readonly SessionPayload $session,
private readonly EmailVerifier $verifier,
2026-09-03 17:35:10 +01:00
) {
}
/**
* POST /api/auth/register
*/
public function register(Request $request, Response $response): Response
{
[$email, $password] = $this->credentials($request);
if ($this->users->findByEmail($email) !== null) {
throw new ApiException('That email address is already registered.', 409);
}
$user = $this->users->create($email, password_hash($password, PASSWORD_DEFAULT));
// 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);
2026-09-03 17:35:10 +01:00
}
/**
* POST /api/auth/login
*/
public function login(Request $request, Response $response): Response
{
[$email, $password] = $this->credentials($request);
$user = $this->users->findByEmail($email);
if ($user === null || !password_verify($password, $user['password_hash'])) {
// Same message either way so we don't reveal which emails are registered.
throw new ApiException('Invalid email or password.', 401);
}
return $this->json($response, $this->session->forUser($user));
2026-09-03 17:35:10 +01:00
}
2026-09-04 10:29:13 +01:00
/**
* POST /api/auth/magic-link (public)
*
* Emails a one-time login link for the given address. Always responds the
* same way so registered addresses can't be enumerated; a link is only sent
* when the account exists and hasn't been sent one in the last minute.
* Opening the link signs the user in and verifies the address.
*/
public function requestLoginLink(Request $request, Response $response): Response
{
$body = (array) ($request->getParsedBody() ?? []);
$email = is_string($body['email'] ?? null) ? mb_strtolower(trim($body['email'])) : '';
if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL) || strlen($email) > self::EMAIL_MAX) {
throw new ValidationException(['email' => ['Enter a valid email address.']]);
}
$user = $this->users->findByEmail($email);
if ($user !== null && !$this->recentlyEmailed($user)) {
try {
$this->verifier->sendLoginLink($user);
} catch (MailException $e) {
error_log('Login link failed for user ' . $user['id'] . ': ' . $e->getMessage());
}
}
return $this->json($response, [
'message' => 'If that address has an account, a login link is on its way.',
], 202);
}
2026-09-03 17:35:10 +01:00
/**
* GET /api/me (requires AuthMiddleware)
*/
public function me(Request $request, Response $response): Response
{
return $this->json($response, ['user' => $this->session->present($this->user($request))]);
2026-09-03 17:35:10 +01:00
}
2026-09-04 10:29:13 +01:00
/**
* @param array{verification_email_sent_at?: string|null} $user
*/
private function recentlyEmailed(array $user): bool
{
$lastSent = $user['verification_email_sent_at'] ?? null;
return $lastSent !== null
&& (time() - (int) strtotime($lastSent)) < EmailVerifier::RESEND_INTERVAL_SECONDS;
}
2026-09-03 17:35:10 +01:00
/**
* Extract and validate the email/password pair from the request body.
*
* @return array{0: string, 1: string} Normalised email and raw password.
*/
private function credentials(Request $request): array
{
$body = (array) ($request->getParsedBody() ?? []);
$email = is_string($body['email'] ?? null) ? trim($body['email']) : '';
$password = is_string($body['password'] ?? null) ? $body['password'] : '';
$errors = [];
if ($email === '') {
$errors['email'][] = 'Email is required.';
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors['email'][] = 'Email must be a valid address.';
} elseif (strlen($email) > self::EMAIL_MAX) {
$errors['email'][] = sprintf('Email must be at most %d characters.', self::EMAIL_MAX);
}
if ($password === '') {
$errors['password'][] = 'Password is required.';
} elseif (strlen($password) < self::PASSWORD_MIN) {
$errors['password'][] = sprintf('Password must be at least %d characters.', self::PASSWORD_MIN);
} elseif (strlen($password) > self::PASSWORD_MAX) {
$errors['password'][] = sprintf('Password must be at most %d characters.', self::PASSWORD_MAX);
}
if ($errors !== []) {
throw new ValidationException($errors);
}
return [mb_strtolower($email), $password];
}
}