65 lines
2 KiB
PHP
65 lines
2 KiB
PHP
<?php
|
|
|
|
namespace App\User\UseCases\ConfirmUserEmail;
|
|
|
|
use App\Auth\Clock;
|
|
use App\Auth\PasswordHasher;
|
|
use App\Email\EmailConfirmationToken\EmailConfirmationTokenRepository;
|
|
use App\Exceptions\BadRequestException;
|
|
use App\User\User;
|
|
use App\User\UserRepository;
|
|
use DomainException;
|
|
|
|
class ConfirmUserEmail
|
|
{
|
|
private const MIN_PASSWORD_LENGTH = 8;
|
|
|
|
public function __construct(
|
|
private UserRepository $userRepo,
|
|
private EmailConfirmationTokenRepository $tokenRepo,
|
|
private PasswordHasher $hasher,
|
|
private Clock $clock,
|
|
) {}
|
|
|
|
/**
|
|
* @throws BadRequestException
|
|
* @throws DomainException
|
|
*/
|
|
public function execute(ConfirmUserEmailRequest $request): void
|
|
{
|
|
if ($request->token === null || $request->token === '') {
|
|
throw new BadRequestException('token is required');
|
|
}
|
|
if ($request->password === null || $request->password === '') {
|
|
throw new BadRequestException('password is required');
|
|
}
|
|
if (strlen($request->password) < self::MIN_PASSWORD_LENGTH) {
|
|
throw new BadRequestException(
|
|
'password must be at least '
|
|
.self::MIN_PASSWORD_LENGTH.' characters'
|
|
);
|
|
}
|
|
|
|
$token = $this->tokenRepo->findByToken($request->token);
|
|
if ($token === null) {
|
|
throw new DomainException('token not found');
|
|
}
|
|
|
|
$now = $this->clock->now();
|
|
if ($token->getAvailableTo() < $now) {
|
|
throw new DomainException('token expired');
|
|
}
|
|
|
|
$user = $token->getUser();
|
|
$confirmedUser = new User(
|
|
id: $user->getId(),
|
|
email: $user->getEmail(),
|
|
displayName: $user->getDisplayName(),
|
|
passwordHash: $this->hasher->hash($request->password),
|
|
isAdmin: $user->isAdmin(),
|
|
emailConfirmedAt: $now,
|
|
);
|
|
$this->userRepo->update($confirmedUser);
|
|
$this->tokenRepo->delete($token->getId());
|
|
}
|
|
}
|