Home > other >  How can i block a user account in symfony 6?
How can i block a user account in symfony 6?

Time:11-03

Im using symfony 6 and easyadmin 4. Im trying to figure out how to block a user account on my website but i can't find a solution.

I tried to create a role named: ROLE_BLOCKED and then use a function like IsDenied in the controllers to block the access but it seems like they are no such function in symfony 6.

CodePudding user response:

use Symfony\Component\Security\Core\Security to get user details and add condition based on the status. or you can directly use isEnabled method

public function isEnabled() {
    return $this->getIsActive();
}

CodePudding user response:

To achieve what you want, you need to:

  1. Store users status (able to connect or not)
  2. Prevent user from logging in
  3. Be able to disable an user with EasyAdmin

To enable/disable users, you could just add a new $isEnabled property:

/**
 * @ORM\Column(type="boolean", options={"default":true})
 */
private bool $isEnabled = true;

public function isEnabled(): ?bool
{
    return $this->isEnabled;
}

public function setIsEnabled(bool $isEnabled): self
{
    $this->isEnabled = $isEnabled;

    return $this;
}

Don't forget to update your schema (with a new migration)


To prevent your user from logging in, if you are using the new authenticator system (5.3 ) you could just update your getUser method and add something like:

if (!$user->isEnabled()) {
    // fail authentication with a custom error
    throw new CustomUserMessageAuthenticationException('Account is disabled.');
}

And finally just add your new isEnabled boolean to your crud controller:

public function configureFields(string $pageName): iterable
{
   //...
   yield BooleanField::new('isEnabled');
}
  • Related