4
votes

I am using FOSUserBundle with Symfony 3.4 to login my users. When they enter a wrong password the following message is displayed:

enter image description here

I would like to add a check for the user type and add a custom error message such as: "You must be a Customer in order to login.".

I implemented a user checker in order to accomplish this task but it's not working as expected:

class CustomerUserChecker implements UserCheckerInterface
{
    public function checkPreAuth(UserInterface $user)
    {
        // nothing to do here
        return;
    }

    public function checkPostAuth(UserInterface $user)
    {
        if (!$user instanceof CustomerUser) {
            throw new AuthenticationException('You must be a customer in order to login');
        }

        return;
    }
}

I am getting this error:

enter image description here

How can I add a new error with my text?

3

3 Answers

4
votes

I was able to achieve my goal using a custom exception:

<?php

namespace AppBundle\Security;

use Symfony\Component\Security\Core\Exception\AccountStatusException;

class CustomerUserException extends AccountStatusException
{
    /**
     * {@inheritdoc}
     */
    public function getMessageKey()
    {
        return 'You must be a customer in order to login.';
    }
}

The user checker is now like this:

<?php

namespace AppBundle\Security;

use Application\Sonata\UserBundle\Entity\CustomerUser;
use Application\Sonata\UserBundle\Entity\User;
use Symfony\Component\Security\Core\User\UserCheckerInterface;
use Symfony\Component\Security\Core\User\UserInterface;

class CustomerUserChecker implements UserCheckerInterface
{
    public function checkPreAuth(UserInterface $user)
    {
        // nothing to do here
        return;
    }

    public function checkPostAuth(UserInterface $user)
    {
        if (!$user instanceof User) {
            return;
        }

        if (!$user instanceof CustomerUser) {
            throw new CustomerUserException();
        }
    }
}

[Optional] I created a new translation file in app/Resources/translations/security.en.xlf:

<?xml version="1.0"?>
<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
    <file source-language="en" datatype="plaintext" original="file.ext">
        <body>
            <trans-unit id="You must be a customer in order to login.">
                <source>You must be a customer in order to login.</source>
                <target>You must be a customer in order to login.</target>
            </trans-unit>
        </body>
    </file>
</xliff>

And the message is correctly displayed:

enter image description here

1
votes

It will work if you throw a CustomUserMessageAuthenticationException instead of an AuthenticationException.

0
votes

Another method is to override validators.en.yml by copying it from ...vendor/friendsofsymfony/user-bundle/Resources/translations to ...app/Resources/translations. Make any desired changes there.