Symfony2 FOSUserBundle – Validate against “user active” flag on login

后端 未结 1 1558
闹比i
闹比i 2021-01-01 01:09

I have a flag on my users for \'active\' and if set to zero or null, I will not allow login.

I have tried a couple of approaches and come up short.

If I do t

1条回答
  •  北海茫月
    2021-01-01 01:51

    FOSUserBundle / Symfony already has some kind of "active" flag integrated.

    FOS\UserBundle\Model\User already provides the properties "locked" and "enabled" which are intended basically for this purpose. The difference between those two properties is the following ( quoting @stof's comment here)

    From the Security component point of view, there is no real difference: both are forbidden to log in. The difference is a semantic one: disabled users are generally users that need to activate their account (for instance, when you activate the need to confirm the email in FOSUserBundle, the user is disabled on creation and enabled on confirmation). On the other hand, locking a user is generally an action done by the admin of the site to ban a user. Using the same field in the database does not make sense as it would allow banned user to have access again by simply going through the confirmation process.

    The check for locked/disabled users is being performed by a UserChecker ( symfony provides this one as @security.user_checker ) in FOSUserBundle's AuthenticationListener which implements Symfony\Component\Security\Core\User\UserCheckerInterface.

    Now in order to redirect inactive user's to a different route you would:

    1. Catch the Symfony\Component\Security\Core\Exception\DisabledException in the try/catch block in an extended AuthenticationListener
    2. Redirect the user to a certain route if the caught exception is of type InactiveUserException

    Optionally move the redirect to a newly created EventListener/-Subscriber which is being dispatched in the extended AuthenticationListener. This way you could later create additional Listeners i.e. for logging purposes and just subscribe them to the inactive-user login-attempt event.

    0 讨论(0)
提交回复
热议问题