TIDE/backend/app/User/UseCases/SignupUser/SignupUser.php
Yisroel Baum f3c6e2e000
implement SignupUser two-step confirm flow
Signup now collects only email + displayName, creates an
unconfirmed user with empty password hash, mints an
EmailConfirmationToken, and dispatches a confirmation email.
Password is set during ConfirmUserEmail.
2026-05-06 22:08:54 +03:00

90 lines
2.7 KiB
PHP

<?php
namespace App\User\UseCases\SignupUser;
use App\Auth\Clock;
use App\Email\EmailConfirmationToken\CreateEmailConfirmationTokenDto;
use App\Email\EmailConfirmationToken\EmailConfirmationTokenRepository;
use App\Email\Emailer;
use App\Email\EmailFactory;
use App\Exceptions\BadRequestException;
use App\Shared\ValueObject\EmailAddress;
use App\User\CreateUserDto;
use App\User\User;
use App\User\UserRepository;
use DomainException;
use InvalidArgumentException;
class SignupUser
{
private const DISPLAY_NAME_PATTERN = '/^[a-z0-9_-]{3,30}$/';
private const TOKEN_LIFETIME = '+1 day';
public function __construct(
private UserRepository $userRepo,
private EmailConfirmationTokenRepository $tokenRepo,
private Emailer $emailer,
private EmailFactory $emailFactory,
private Clock $clock,
private string $fromAddress,
) {}
/**
* @throws BadRequestException
* @throws DomainException
*/
public function execute(SignupUserRequest $request): User
{
if ($request->email === null || $request->email === '') {
throw new BadRequestException('email is required');
}
if ($request->displayName === null || $request->displayName === '') {
throw new BadRequestException('displayName is required');
}
if (
preg_match(
self::DISPLAY_NAME_PATTERN,
$request->displayName,
) !== 1
) {
throw new BadRequestException(
'displayName must be 3-30 chars of [a-z0-9_-]'
);
}
try {
$email = new EmailAddress($request->email);
} catch (InvalidArgumentException $exception) {
throw new BadRequestException($exception->getMessage());
}
if ($this->userRepo->findByEmail($email) !== null) {
throw new DomainException('email already registered');
}
if ($this->userRepo->findByDisplayName($request->displayName) !== null) {
throw new DomainException('displayName already taken');
}
$user = $this->userRepo->create(new CreateUserDto(
email: $email,
displayName: $request->displayName,
passwordHash: '',
isAdmin: false,
emailConfirmedAt: null,
));
$token = $this->tokenRepo->create(new CreateEmailConfirmationTokenDto(
user: $user,
availableTo: $this->clock->now()->modify(self::TOKEN_LIFETIME),
));
$this->emailer->send(
$this->fromAddress,
$user->getEmail()->value(),
$this->emailFactory->makeConfirmationEmail($token->getToken()),
);
return $user;
}
}