Skip to content

Open-source event management and ticket selling platform — perfect for concerts, conferences, and everything in between 🎟️ If you find this project helpful, please consider giving us a star ⭐️

1.6 KB
Raw Blame
<?php

namespace HiEvents\Services\Application\Handlers\User\TwoFactor;

use HiEvents\Exceptions\InvalidTwoFactorCodeException;
use HiEvents\Exceptions\ResourceConflictException;
use HiEvents\Exceptions\TwoFactorLockedOutException;
use HiEvents\Repository\Interfaces\UserRepositoryInterface;
use HiEvents\Services\Domain\Auth\TwoFactor\RecoveryCodeService;
use HiEvents\Services\Domain\Auth\TwoFactor\TwoFactorAuthenticationService;
use HiEvents\Services\Domain\Auth\TwoFactor\TwoFactorVerifier;

class RegenerateRecoveryCodesHandler
{
    public function __construct(
        private readonly UserRepositoryInterface $userRepository,
        private readonly TwoFactorAuthenticationService $twoFactorAuthenticationService,
        private readonly RecoveryCodeService $recoveryCodeService,
        private readonly TwoFactorVerifier $twoFactorVerifier,
    ) {}

    /**
     * @return string[]
     *
     * @throws ResourceConflictException
     * @throws InvalidTwoFactorCodeException
     * @throws TwoFactorLockedOutException
     */
    public function handle(int $userId, string $code): array
    {
        $user = $this->userRepository->findById($userId);

        if (! $this->twoFactorAuthenticationService->isEnabled($user)) {
            throw new ResourceConflictException(__('Two-factor authentication is not enabled.'));
        }

        if (! $this->twoFactorVerifier->verify($user, $code)) {
            throw new InvalidTwoFactorCodeException(__('That code is not valid. Check your authenticator app and try again.'));
        }

        return $this->recoveryCodeService->regenerate($userId);
    }
}