symfonywebsymfony4

Symfony 4: allow only active accounts to login


So I'm using symfony 4 and I managed to add a field in the user's database table called "Active", if active equals 0 then the account is not activated and vice versa. So what I'm trying to do is that whenever a user who's account is not active tries to login, a message or an alert shows and tells him that his account is currently inactive. While an active user connects without any problem. I'm not using FOSUserBundle here. So can I do that manually ?


Solution

  • You can accomplish that using a user checker.

    Eg.:

    namespace App\Security;
    
    use App\Entity\User;
    use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
    use Symfony\Component\Security\Core\User\UserCheckerInterface;
    use Symfony\Component\Security\Core\User\UserInterface;
    
    class UserChecker implements UserCheckerInterface
    {
        public function checkPreAuth(UserInterface $user): bool
        {
            if (!$user instanceof User) {
                return;
            }
    
            if (!$user->isActive()) {
                throw new CustomUserMessageAuthenticationException(
                    'Inactive account cannot log in'
                );
            }
        }
    
        public function checkPostAuth(UserInterface $user): bool
        {
            $this->checkPreAuth($user);
        }
    }
    

    Enable the checker:

    security:
        firewalls:
            main:
                // skipped for brevity
                user_checker: App\Security\UserChecker