Backend: new migration adds users.email_verified_at (null = unverified); registration leaves it null, and the register/login/me payloads now expose email_verified and email_verified_at. Frontend (web/): Vite + Vue 3 + TypeScript PWA (vite-plugin-pwa). Pinia auth store keeps the token in localStorage and validates it via GET /api/me on load. vue-router guards redirect unauthenticated visitors to /login, preserving the intended path; /register creates an account and signs in immediately (with the email unverified). Placeholder home page, minimal styling, generated icons. Dev server proxies /api to the API. docker-compose.yml gains an optional "web" service (profile: frontend) so `docker compose --profile frontend up -d` runs the dev server alongside the API; `docker compose up -d` still starts the API alone. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
144 lines
4.5 KiB
PHP
144 lines
4.5 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Http\Controllers;
|
|
|
|
use App\Auth\JwtService;
|
|
use App\Exception\ApiException;
|
|
use App\Exception\ValidationException;
|
|
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 JwtService $jwt,
|
|
) {
|
|
}
|
|
|
|
/**
|
|
* 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));
|
|
|
|
return $this->json($response, $this->session($user), 201);
|
|
}
|
|
|
|
/**
|
|
* 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($user));
|
|
}
|
|
|
|
/**
|
|
* GET /api/me (requires AuthMiddleware)
|
|
*/
|
|
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)]);
|
|
}
|
|
|
|
/**
|
|
* 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];
|
|
}
|
|
|
|
/**
|
|
* 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,
|
|
];
|
|
}
|
|
}
|