test email signup flow

This commit is contained in:
Yisroel Baum 2026-08-03 20:22:50 +03:00
parent a95903ed05
commit 9945163a2f
Signed by: yisroelbaum
GPG key ID: 0FA60884F75520A9
12 changed files with 631 additions and 0 deletions

View file

@ -0,0 +1,69 @@
<?php
namespace Tests\Fakes;
use App\Email\EmailConfirmationToken\CreateEmailConfirmationTokenDto;
use App\Email\EmailConfirmationToken\EmailConfirmationToken;
use App\Email\EmailConfirmationToken\EmailConfirmationTokenRepository;
use App\User\User;
class FakeEmailConfirmationTokenRepository implements EmailConfirmationTokenRepository
{
/**
* @var array<int, EmailConfirmationToken>
*/
private array $tokens = [];
public function create(
CreateEmailConfirmationTokenDto $dto,
): EmailConfirmationToken {
$id = count($this->tokens) + 1;
$token = new EmailConfirmationToken(
id: $id,
user: $dto->user,
availableTo: $dto->availableTo,
token: $dto->token,
);
$this->tokens[$id] = $token;
return $this->copy($token);
}
public function findByToken(string $token): ?EmailConfirmationToken
{
foreach ($this->tokens as $candidate) {
if ($candidate->getToken() === $token) {
return $this->copy($candidate);
}
}
return null;
}
public function findByUser(User $user): ?EmailConfirmationToken
{
foreach ($this->tokens as $candidate) {
if ($candidate->getUser()->getId() === $user->getId()) {
return $this->copy($candidate);
}
}
return null;
}
public function delete(int $id): void
{
unset($this->tokens[$id]);
}
private function copy(
EmailConfirmationToken $token,
): EmailConfirmationToken {
return new EmailConfirmationToken(
id: $token->getId(),
user: $token->getUser(),
availableTo: $token->getAvailableTo(),
token: $token->getToken(),
);
}
}

View file

@ -0,0 +1,22 @@
<?php
namespace Tests\Fakes;
use App\Email\EmailFactory;
class FakeEmailFactory implements EmailFactory
{
private ?string $lastToken = null;
public function makeConfirmationEmail(string $token): string
{
$this->lastToken = $token;
return "confirm with {$token}";
}
public function getLastToken(): ?string
{
return $this->lastToken;
}
}

View file

@ -0,0 +1,48 @@
<?php
namespace Tests\Fakes;
use App\Email\Emailer;
use App\Shared\ValueObject\EmailAddress;
class FakeEmailer implements Emailer
{
private int $sendCount = 0;
private ?EmailAddress $lastRecipient = null;
private ?string $lastSubject = null;
private ?string $lastBody = null;
public function send(
EmailAddress $recipient,
string $subject,
string $body,
): void {
$this->sendCount++;
$this->lastRecipient = $recipient;
$this->lastSubject = $subject;
$this->lastBody = $body;
}
public function getSendCount(): int
{
return $this->sendCount;
}
public function getLastRecipient(): ?EmailAddress
{
return $this->lastRecipient;
}
public function getLastSubject(): ?string
{
return $this->lastSubject;
}
public function getLastBody(): ?string
{
return $this->lastBody;
}
}

View file

@ -45,6 +45,13 @@ class FakeUserRepository implements UserRepository
return null;
}
public function update(User $user): User
{
$this->users[$user->getId()] = $this->copy($user);
return $this->copy($user);
}
private function copy(User $user): User
{
return new User(

View file

@ -0,0 +1,70 @@
<?php
namespace Tests\Feature\Auth;
use App\Auth\PasswordHasher;
use App\Auth\SessionRepository;
use App\Email\EmailConfirmationToken\EmailConfirmationTokenRepository;
use App\Email\EmailConfirmationToken\UseCases\CreateEmailConfirmationToken;
use App\Email\EmailConfirmationToken\UseCases\CreateEmailConfirmationTokenRequest;
use App\Http\Middleware\AuthMiddleware;
use App\Shared\ValueObject\EmailAddress;
use App\User\CreateUserDto;
use App\User\UserRepository;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class ConfirmEmailEndpointTest extends TestCase
{
use RefreshDatabase;
public function test_confirmation_sets_password_and_starts_session(): void
{
$userRepository = app(UserRepository::class);
$user = $userRepository->create(new CreateUserDto(
email: new EmailAddress('user@example.com'),
passwordHash: null,
));
$token = app(CreateEmailConfirmationToken::class)->execute(
new CreateEmailConfirmationTokenRequest(
user: $user,
minuteOffset: 10,
),
);
$response = $this->postJson('/api/confirm-email', [
'token' => $token->getToken(),
'password' => 'password123',
]);
$response->assertOk();
$response->assertJsonPath('user.email', 'user@example.com');
$confirmedUser = $userRepository->find($user->getId());
$this->assertNotNull($confirmedUser);
$passwordHash = $confirmedUser->getPasswordHash();
$this->assertNotNull($passwordHash);
$this->assertTrue(
app(PasswordHasher::class)->verify('password123', $passwordHash),
);
$this->assertNull(
app(EmailConfirmationTokenRepository::class)
->findByToken($token->getToken()),
);
$cookie = $response->getCookie(AuthMiddleware::COOKIE_NAME, false);
$this->assertNotNull($cookie);
$this->assertNotNull(
app(SessionRepository::class)->findByToken($cookie->getValue()),
);
}
public function test_confirmation_rejects_an_unknown_token(): void
{
$response = $this->postJson('/api/confirm-email', [
'token' => 'unknown-token',
'password' => 'password123',
]);
$response->assertConflict();
$response->assertJson(['error' => 'token not found']);
}
}

View file

@ -0,0 +1,50 @@
<?php
namespace Tests\Feature\Auth;
use App\Email\EmailConfirmationToken\EmailConfirmationTokenRepository;
use App\Shared\ValueObject\EmailAddress;
use App\User\CreateUserDto;
use App\User\UserRepository;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class SignupEndpointTest extends TestCase
{
use RefreshDatabase;
public function test_signup_creates_a_pending_user_and_confirmation_token(): void
{
$response = $this->postJson('/api/signup', [
'email' => 'Founder@EXAMPLE.COM',
]);
$response->assertCreated();
$user = app(UserRepository::class)->findByEmail(
new EmailAddress('Founder@example.com'),
);
$this->assertNotNull($user);
$this->assertNull($user->getPasswordHash());
$this->assertNotNull(
app(EmailConfirmationTokenRepository::class)
->findByUser($user),
);
}
public function test_signup_rejects_an_existing_confirmed_account(): void
{
app(UserRepository::class)->create(new CreateUserDto(
email: new EmailAddress('user@example.com'),
passwordHash: 'hashed-password',
));
$response = $this->postJson('/api/signup', [
'email' => 'user@example.com',
]);
$response->assertConflict();
$response->assertJson([
'error' => 'user@example.com already has an account',
]);
}
}

View file

@ -78,4 +78,23 @@ class EloquentUserRepositoryTest extends TestCase
new EmailAddress('unknown@example.com'),
));
}
public function test_it_persists_confirmation_of_a_pending_user(): void
{
$repository = app(UserRepository::class);
$user = $repository->create(new CreateUserDto(
email: new EmailAddress('pending@example.com'),
passwordHash: null,
));
$this->assertNull($user->getPasswordHash());
$user->setPasswordHash('hashed-password');
$updatedUser = $repository->update($user);
$this->assertSame('hashed-password', $updatedUser->getPasswordHash());
$this->assertDatabaseHas('users', [
'id' => $user->getId(),
'passwordHash' => 'hashed-password',
]);
}
}

View file

@ -64,6 +64,22 @@ class AuthenticateUserTest extends TestCase
));
}
public function test_pending_user_throws_unauthorized(): void
{
$this->userRepository->create(new CreateUserDto(
email: new EmailAddress('user@example.com'),
passwordHash: null,
));
$this->expectException(UnauthorizedException::class);
$this->expectExceptionMessage('invalid credentials');
$this->useCase->execute(new AuthenticateUserRequest(
email: 'user@example.com',
password: 'correct-password',
));
}
public function test_wrong_password_throws_unauthorized(): void
{
$this->createUser('correct-password');

View file

@ -5,15 +5,21 @@ namespace Tests\Unit\Http\Controllers;
use App\Auth\UseCases\AuthenticateUser\AuthenticateUser;
use App\Auth\UseCases\CreateSession\CreateSession;
use App\Auth\UseCases\Logout\Logout;
use App\Email\EmailConfirmationToken\UseCases\CreateEmailConfirmationToken;
use App\Http\Controllers\AuthController;
use App\Http\Middleware\AuthMiddleware;
use App\Shared\ValueObject\EmailAddress;
use App\User\CreateUserDto;
use App\User\UseCases\ConfirmUserEmail\ConfirmUserEmail;
use App\User\UseCases\SignupUser\SignupUser;
use DateTimeImmutable;
use DateTimeZone;
use Illuminate\Http\Request;
use PHPUnit\Framework\TestCase;
use Tests\Fakes\FakeClock;
use Tests\Fakes\FakeEmailConfirmationTokenRepository;
use Tests\Fakes\FakeEmailer;
use Tests\Fakes\FakeEmailFactory;
use Tests\Fakes\FakePasswordHasher;
use Tests\Fakes\FakeSessionRepository;
use Tests\Fakes\FakeTokenGenerator;
@ -47,7 +53,32 @@ class AuthControllerTest extends TestCase
)),
);
$logout = new Logout($this->sessionRepository);
$tokenRepository = new FakeEmailConfirmationTokenRepository;
$signupUser = new SignupUser(
$this->userRepository,
new CreateEmailConfirmationToken(
$tokenRepository,
new FakeClock(new DateTimeImmutable(
'2026-07-31T12:00:00',
new DateTimeZone('UTC'),
)),
new FakeTokenGenerator(['email-token']),
),
new FakeEmailer,
new FakeEmailFactory,
);
$confirmUserEmail = new ConfirmUserEmail(
$tokenRepository,
$this->userRepository,
$this->passwordHasher,
new FakeClock(new DateTimeImmutable(
'2026-07-31T12:00:00',
new DateTimeZone('UTC'),
)),
);
$this->controller = new AuthController(
$signupUser,
$confirmUserEmail,
$authenticateUser,
$createSession,
$logout,

View file

@ -0,0 +1,149 @@
<?php
namespace Tests\Unit\User\UseCases;
use App\Email\EmailConfirmationToken\CreateEmailConfirmationTokenDto;
use App\Exceptions\BadRequestException;
use App\Shared\ValueObject\EmailAddress;
use App\User\CreateUserDto;
use App\User\UseCases\ConfirmUserEmail\ConfirmUserEmail;
use App\User\UseCases\ConfirmUserEmail\ConfirmUserEmailRequest;
use DateTimeImmutable;
use DateTimeZone;
use DomainException;
use PHPUnit\Framework\TestCase;
use Tests\Fakes\FakeClock;
use Tests\Fakes\FakeEmailConfirmationTokenRepository;
use Tests\Fakes\FakePasswordHasher;
use Tests\Fakes\FakeUserRepository;
class ConfirmUserEmailTest extends TestCase
{
private DateTimeImmutable $now;
private FakeUserRepository $userRepository;
private FakeEmailConfirmationTokenRepository $tokenRepository;
private ConfirmUserEmail $confirmUserEmail;
protected function setUp(): void
{
$this->now = new DateTimeImmutable(
'2026-08-03T12:00:00',
new DateTimeZone('UTC'),
);
$this->userRepository = new FakeUserRepository;
$this->tokenRepository = new FakeEmailConfirmationTokenRepository;
$this->confirmUserEmail = new ConfirmUserEmail(
$this->tokenRepository,
$this->userRepository,
new FakePasswordHasher,
new FakeClock($this->now),
);
}
public function test_it_sets_the_password_and_consumes_the_token(): void
{
$this->createPendingUserToken(
'confirmation-token',
$this->now->modify('+10 minutes'),
);
$confirmedUser = $this->confirmUserEmail->execute(
new ConfirmUserEmailRequest(
token: 'confirmation-token',
password: 'password123',
),
);
$this->assertSame('hashed:password123', $confirmedUser->getPasswordHash());
$this->assertSame(
'hashed:password123',
$this->userRepository->find($confirmedUser->getId())
?->getPasswordHash(),
);
$this->assertNull(
$this->tokenRepository->findByToken('confirmation-token'),
);
}
public function test_it_rejects_an_expired_token(): void
{
$this->createPendingUserToken(
'expired-token',
$this->now->modify('-1 minute'),
);
$this->expectException(DomainException::class);
$this->expectExceptionMessage('token expired');
$this->confirmUserEmail->execute(new ConfirmUserEmailRequest(
token: 'expired-token',
password: 'password123',
));
}
public function test_it_rejects_an_unknown_token(): void
{
$this->expectException(DomainException::class);
$this->expectExceptionMessage('token not found');
$this->confirmUserEmail->execute(new ConfirmUserEmailRequest(
token: 'unknown-token',
password: 'password123',
));
}
public function test_it_requires_a_token(): void
{
$this->expectException(BadRequestException::class);
$this->expectExceptionMessage('token is required');
$this->confirmUserEmail->execute(new ConfirmUserEmailRequest(
token: null,
password: 'password123',
));
}
public function test_it_requires_a_password(): void
{
$this->expectException(BadRequestException::class);
$this->expectExceptionMessage('password is required');
$this->confirmUserEmail->execute(new ConfirmUserEmailRequest(
token: 'confirmation-token',
password: null,
));
}
public function test_it_rejects_a_short_password(): void
{
$this->expectException(BadRequestException::class);
$this->expectExceptionMessage(
'password must be at least 8 characters',
);
$this->confirmUserEmail->execute(new ConfirmUserEmailRequest(
token: 'confirmation-token',
password: 'short',
));
}
private function createPendingUserToken(
string $token,
DateTimeImmutable $availableTo,
): void {
$user = $this->userRepository->create(new CreateUserDto(
email: new EmailAddress('user@example.com'),
passwordHash: null,
));
$this->tokenRepository->create(
new CreateEmailConfirmationTokenDto(
user: $user,
availableTo: $availableTo,
token: $token,
),
);
}
}

View file

@ -0,0 +1,135 @@
<?php
namespace Tests\Unit\User\UseCases;
use App\Email\EmailConfirmationToken\UseCases\CreateEmailConfirmationToken;
use App\Exceptions\BadRequestException;
use App\Shared\ValueObject\EmailAddress;
use App\User\CreateUserDto;
use App\User\UseCases\SignupUser\SignupUser;
use App\User\UseCases\SignupUser\SignupUserRequest;
use DateTimeImmutable;
use DateTimeZone;
use DomainException;
use PHPUnit\Framework\TestCase;
use Tests\Fakes\FakeClock;
use Tests\Fakes\FakeEmailConfirmationTokenRepository;
use Tests\Fakes\FakeEmailer;
use Tests\Fakes\FakeEmailFactory;
use Tests\Fakes\FakeTokenGenerator;
use Tests\Fakes\FakeUserRepository;
class SignupUserTest extends TestCase
{
private FakeUserRepository $userRepository;
private FakeEmailConfirmationTokenRepository $tokenRepository;
private FakeEmailer $emailer;
private FakeEmailFactory $emailFactory;
private SignupUser $signupUser;
protected function setUp(): void
{
$this->userRepository = new FakeUserRepository;
$this->tokenRepository = new FakeEmailConfirmationTokenRepository;
$this->emailer = new FakeEmailer;
$this->emailFactory = new FakeEmailFactory;
$createToken = new CreateEmailConfirmationToken(
$this->tokenRepository,
new FakeClock(new DateTimeImmutable(
'2026-08-03T12:00:00',
new DateTimeZone('UTC'),
)),
new FakeTokenGenerator(['first-token', 'second-token']),
);
$this->signupUser = new SignupUser(
$this->userRepository,
$createToken,
$this->emailer,
$this->emailFactory,
);
}
public function test_it_creates_a_pending_user_token_and_email(): void
{
$this->signupUser->execute(new SignupUserRequest(
email: ' Founder@EXAMPLE.COM ',
));
$user = $this->userRepository->findByEmail(
new EmailAddress('Founder@example.com'),
);
$this->assertNotNull($user);
$this->assertNull($user->getPasswordHash());
$token = $this->tokenRepository->findByUser($user);
$this->assertNotNull($token);
$this->assertSame('first-token', $token->getToken());
$this->assertSame(
'2026-08-03T12:10:00+00:00',
$token->getAvailableTo()->format('c'),
);
$this->assertSame(1, $this->emailer->getSendCount());
$this->assertSame(
'Founder@example.com',
$this->emailer->getLastRecipient()?->value(),
);
$this->assertSame(
'Confirm your Attainly email',
$this->emailer->getLastSubject(),
);
$this->assertSame('first-token', $this->emailFactory->getLastToken());
}
public function test_it_replaces_the_token_for_a_pending_user(): void
{
$request = new SignupUserRequest(email: 'user@example.com');
$this->signupUser->execute($request);
$this->signupUser->execute($request);
$user = $this->userRepository->findByEmail(
new EmailAddress('user@example.com'),
);
$this->assertNotNull($user);
$this->assertSame(
'second-token',
$this->tokenRepository->findByUser($user)?->getToken(),
);
$this->assertSame(2, $this->emailer->getSendCount());
}
public function test_it_rejects_an_existing_confirmed_account(): void
{
$this->userRepository->create(new CreateUserDto(
email: new EmailAddress('user@example.com'),
passwordHash: 'hashed-password',
));
$this->expectException(DomainException::class);
$this->expectExceptionMessage('user@example.com already has an account');
$this->signupUser->execute(new SignupUserRequest(
email: 'user@example.com',
));
}
public function test_it_rejects_a_missing_email(): void
{
$this->expectException(BadRequestException::class);
$this->expectExceptionMessage('email is required');
$this->signupUser->execute(new SignupUserRequest(email: null));
}
public function test_it_rejects_an_invalid_email(): void
{
$this->expectException(BadRequestException::class);
$this->expectExceptionMessage('email must be valid');
$this->signupUser->execute(new SignupUserRequest(
email: 'not-an-email',
));
}
}

View file

@ -21,4 +21,19 @@ class UserTest extends TestCase
$this->assertSame($email, $user->getEmail());
$this->assertSame('hashed-password', $user->getPasswordHash());
}
public function test_it_can_confirm_a_pending_user_with_a_password(): void
{
$user = new User(
id: 42,
email: new EmailAddress('user@example.com'),
passwordHash: null,
);
$this->assertNull($user->getPasswordHash());
$user->setPasswordHash('hashed-password');
$this->assertSame('hashed-password', $user->getPasswordHash());
}
}