Passwordless-only auth: drop registration and passwords entirely
There is now one way in: POST /api/auth/magic-link with an email address. It
creates the account (unverified) if the address is new -- that's the only
"sign up" -- and emails a sign-in link either way, subject to the existing
60s-per-user resend throttle. Opening the link (POST /api/auth/verify-email,
unchanged) is what actually creates the session, and marks the address
verified the first time. Since a session can now only ever come from an
opened link, "authenticated" implies "verified" -- there's no more
authenticated-but-unverified state, so the resend-verification endpoint and
all the "verify your email" nagging UI are gone too.
Backend
- migrations/008: ALTER TABLE users DROP COLUMN password_hash.
- UserRepository: create() takes only an email; new findOrCreateByEmail()
(race-safe) backs the magic-link endpoint.
- AuthController: register()/login() removed; requestLoginLink() now
find-or-creates before sending.
- EmailVerificationController: resend() removed (dead -- you can't be
authenticated and unverified); requestChange() drops the password check,
now just { email }.
- EmailVerifier: sendVerification() removed (unused once register() and
resend() are gone); sendLoginLink() is the one email people get.
- Routes: POST /auth/register, POST /auth/login, POST /email/verification
all gone.
Frontend
- LoginView: email field + "Send sign-in link" button, nothing else.
RegisterView and the /register route are gone.
- auth store: register()/login()/resendVerification() removed;
requestEmailChange() drops the password param.
- ProfileView: password field and the "verify your email" section removed,
leaving just the change-email form.
- App.vue: the "verify email" header badge is gone; DashboardView's
unverified-address notice is gone.
- Now-dead .badge/.badge--warn/a.badge CSS removed.
Tests: AuthTest and EmailVerificationTest rewritten for the new flow (52
tests total, down from 58 -- consolidated, not reduced coverage).
ApiTestCase::authHeader() signs in via the real magic-link -> verify flow.
Verified end-to-end against the rebuilt container and the dev server: a brand
new address gets an account + session from one link; /auth/register,
/auth/login and /email/verification all 404; the UI shows no password field
anywhere and no verification nagging. Also fixed the README's "Try it" curl
snippets, which had been silently broken since JSON_PRETTY_PRINT was added
(grep patterns didn't tolerate the space after ':').
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -7,9 +7,10 @@ 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.
|
||||
* Builds the JSON representation of a user and the session envelope returned
|
||||
* when a magic link is opened (sign-up, sign-in, and email-change confirmation
|
||||
* all go through the same verify-email endpoint). Shared so every entry point
|
||||
* agrees on the shape.
|
||||
*/
|
||||
final class SessionPayload
|
||||
{
|
||||
|
||||
@@ -5,7 +5,6 @@ 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;
|
||||
@@ -13,13 +12,13 @@ use App\Repository\UserRepository;
|
||||
use Psr\Http\Message\ResponseInterface as Response;
|
||||
use Psr\Http\Message\ServerRequestInterface as Request;
|
||||
|
||||
/**
|
||||
* Passwordless auth: there is no register/login pair. An email address is
|
||||
* turned into an account (if it isn't one already) and sent a magic link;
|
||||
* opening that link is what actually signs the caller in.
|
||||
*/
|
||||
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(
|
||||
@@ -29,54 +28,14 @@ final class AuthController extends Controller
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* 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);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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));
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* Emails a one-time sign-in link for the given address, creating the
|
||||
* account first if it doesn't exist yet. Always responds the same way; a
|
||||
* link is only actually (re-)sent when one hasn't gone out in the last
|
||||
* minute. Opening the link creates the session and, the first time, marks
|
||||
* the address verified.
|
||||
*/
|
||||
public function requestLoginLink(Request $request, Response $response): Response
|
||||
{
|
||||
@@ -87,8 +46,9 @@ final class AuthController extends Controller
|
||||
throw new ValidationException(['email' => ['Enter a valid email address.']]);
|
||||
}
|
||||
|
||||
$user = $this->users->findByEmail($email);
|
||||
if ($user !== null && !$this->recentlyEmailed($user)) {
|
||||
$user = $this->users->findOrCreateByEmail($email);
|
||||
|
||||
if (!$this->recentlyEmailed($user)) {
|
||||
try {
|
||||
$this->verifier->sendLoginLink($user);
|
||||
} catch (MailException $e) {
|
||||
@@ -97,7 +57,7 @@ final class AuthController extends Controller
|
||||
}
|
||||
|
||||
return $this->json($response, [
|
||||
'message' => 'If that address has an account, a login link is on its way.',
|
||||
'message' => 'Check your email for a link to sign in.',
|
||||
], 202);
|
||||
}
|
||||
|
||||
@@ -119,41 +79,4 @@ final class AuthController extends Controller
|
||||
return $lastSent !== null
|
||||
&& (time() - (int) strtotime($lastSent)) < EmailVerifier::RESEND_INTERVAL_SECONDS;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -43,11 +43,11 @@ abstract class Controller
|
||||
/**
|
||||
* The authenticated user row attached by AuthMiddleware.
|
||||
*
|
||||
* @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}
|
||||
* @return array{id: int, email: 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, password_hash: string, email_verified_at: string|null, verification_email_sent_at: string|null, created_at: string, updated_at: string} $user */
|
||||
/** @var array{id: int, email: 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;
|
||||
|
||||
@@ -18,7 +18,6 @@ final class EmailVerificationController extends Controller
|
||||
{
|
||||
private const RESEND_INTERVAL_SECONDS = EmailVerifier::RESEND_INTERVAL_SECONDS;
|
||||
private const EMAIL_MAX = 255;
|
||||
private const PASSWORD_MAX = 72;
|
||||
|
||||
public function __construct(
|
||||
private readonly UserRepository $users,
|
||||
@@ -78,31 +77,6 @@ final class EmailVerificationController extends Controller
|
||||
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) {
|
||||
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.
|
||||
@@ -113,7 +87,6 @@ final class EmailVerificationController extends Controller
|
||||
$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 === '') {
|
||||
@@ -123,18 +96,10 @@ final class EmailVerificationController extends Controller
|
||||
} 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);
|
||||
}
|
||||
|
||||
@@ -8,8 +8,9 @@ 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.
|
||||
* Issues a magic-link token and emails it: a sign-in link (which also creates
|
||||
* the account and verifies the address, the first time) or a "confirm your new
|
||||
* address" link for a pending email change.
|
||||
*/
|
||||
final class EmailVerifier
|
||||
{
|
||||
@@ -25,27 +26,9 @@ final class EmailVerifier
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 passwordless login link. Opening it signs the user in and, as a
|
||||
* side effect, verifies the address if it wasn't already.
|
||||
* Send a passwordless sign-in link. Opening it creates the session and, the
|
||||
* first time, verifies the address -- this is also how an account is
|
||||
* created, so it doubles as the "welcome" email for a new address.
|
||||
*
|
||||
* @param array{id: int, email: string} $user
|
||||
*/
|
||||
|
||||
@@ -5,11 +5,14 @@ declare(strict_types=1);
|
||||
namespace App\Repository;
|
||||
|
||||
use PDO;
|
||||
use PDOException;
|
||||
|
||||
/**
|
||||
* Data access for the `users` table. Rows are returned as associative arrays.
|
||||
* There is no password: an account is created (if needed) and authenticated
|
||||
* entirely by opening an emailed magic link.
|
||||
*
|
||||
* @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}
|
||||
* @phpstan-type UserRow array{id: int, email: string, email_verified_at: string|null, verification_email_sent_at: string|null, created_at: string, updated_at: string}
|
||||
*/
|
||||
final class UserRepository
|
||||
{
|
||||
@@ -46,15 +49,10 @@ final class UserRepository
|
||||
/**
|
||||
* @return UserRow
|
||||
*/
|
||||
public function create(string $email, string $passwordHash): array
|
||||
public function create(string $email): array
|
||||
{
|
||||
$stmt = $this->pdo->prepare(
|
||||
'INSERT INTO users (email, password_hash) VALUES (:email, :password_hash)'
|
||||
);
|
||||
$stmt->execute([
|
||||
'email' => $email,
|
||||
'password_hash' => $passwordHash,
|
||||
]);
|
||||
$stmt = $this->pdo->prepare('INSERT INTO users (email) VALUES (:email)');
|
||||
$stmt->execute(['email' => $email]);
|
||||
|
||||
/** @var UserRow $user */
|
||||
$user = $this->findById((int) $this->pdo->lastInsertId());
|
||||
@@ -62,6 +60,32 @@ final class UserRepository
|
||||
return $user;
|
||||
}
|
||||
|
||||
/**
|
||||
* The user for this address, creating one (unverified) if it doesn't exist
|
||||
* yet -- this is the only "sign up".
|
||||
*
|
||||
* @return UserRow
|
||||
*/
|
||||
public function findOrCreateByEmail(string $email): array
|
||||
{
|
||||
$existing = $this->findByEmail($email);
|
||||
if ($existing !== null) {
|
||||
return $existing;
|
||||
}
|
||||
|
||||
try {
|
||||
return $this->create($email);
|
||||
} catch (PDOException $e) {
|
||||
// Lost a race with a concurrent request for the same address.
|
||||
$row = $this->findByEmail($email);
|
||||
if ($row === null) {
|
||||
throw $e;
|
||||
}
|
||||
|
||||
return $row;
|
||||
}
|
||||
}
|
||||
|
||||
public function markEmailVerified(int $id): void
|
||||
{
|
||||
$this->pdo->prepare(
|
||||
|
||||
@@ -78,13 +78,10 @@ $app->group('/api', function (RouteCollectorProxy $group) use (
|
||||
return $response->withHeader('Content-Type', 'application/json');
|
||||
});
|
||||
|
||||
$group->post('/auth/register', [$authController, 'register']);
|
||||
$group->post('/auth/login', [$authController, 'login']);
|
||||
$group->post('/auth/magic-link', [$authController, 'requestLoginLink']);
|
||||
$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('/projects', function (RouteCollectorProxy $projects) use (
|
||||
|
||||
Reference in New Issue
Block a user