Const Se
Const Se

Reputation: 23

How to use nonstandard username for authentication in Symfony2

On my site authentication is performed using mobile phone. Phone consists of two parts: code and number ("+7 (code) number"). It is realized via inherited form field type:

PhoneType.php

class PhoneType extends TextType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('code', 'text')->add('number', 'text')
            ->addModelTransformer(new PhoneToStringTransformer());
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array('compound' => true));
    }
}

PhoneToStringTransformer.php

class PhoneToStringTransformer implements DataTransformerInterface
{
    public function transform($string)
    {
        if (!empty($string) && !preg_match('/^\+7\d{10}$/', $string)) {
            throw new TransformationFailedException('Incorrect phone format');
        }
        return array(
            'code' => substr($string, 2, 3),
            'number' => substr($string, 5));
    }

    public function reverseTransform($phone)
    {
         return sprintf('+7%s%s', $phone['code'], $phone['number']);
    }
}

But when I try to authenticate, I have this warning:

Warning: trim() expects parameter 1 to be string, array given in \path\to\project\vendor\symfony\symfony\src\Symfony\Component\Security\Http\Firewall\UsernamePasswordFormAuthenticationListener.php line 79

Warning occurs because it requires the username as a string, but login form return value is an array.
How can I make authentication with nonstandard "username" (my phone as array)?
I use the standard SecurityBundle.

app/config/security.yml

providers:
    main:
        entity: { class: MyProject:User, property: phone }

firewalls:
    main:
        form_login:
            username_parameter: userForm[phone]

I don't know, how to specify username_parameter to have it passed to UsernamePasswordFormAuthenticationListener as a string userForm[phone][code] + userForm[phone][number].

Upvotes: 1

Views: 441

Answers (1)

Tek
Tek

Reputation: 3060

Make sure your yml file is properly indented. That format you're using userForm[phone] should work since I just had a similar issue by writing out parameters like that.

Symfony2, forms, username_parameter and firewall parameters

Upvotes: 1

Related Questions