问题
By default, Symfony2 matches usernames case-sensitively. I want users to be able to enter johnsmith, JohnSmith, johnSMITH, or any variant of that, and have them all register as johnsmith. How do I do this?
I though the easiest way would be to always convert each username to lower-case before comparing them. This is easy to do on the one side (just throw a lower()
into the SQL statement), but how do I do that for what the user types in in the login form? Since Symfony automatically takes care of the login_check
route handling, I can't figure it out.
Better yet, is there some option I can set to enable case-insensitivity instead?
回答1:
You already fixed it, but I will explain another solution for users with similar problems:
- You have to implement your own Provider this way: http://symfony.com/doc/current/cookbook/security/entity_provider.html#authenticating-someone-with-a-custom-entity-provider
Use the following query instead in method
loadUserByUsername
:$user = $this->findOneBy(array('username' => strtolower($username)));
This worked for me. (Also in Doctrine Mongo ODM)
回答2:
Just write correct loadUserByUsername function in UserRepository. It must not be case sensitive:
public function loadUserByUsername($username)
{
$user = $this->createQueryBuilder('u')
->where('LOWER(u.email) = :username')
->setParameter('username', strtolower($username))
->getQuery()
->getOneOrNullResult();
if ($user){
return $user;
}
throw new UsernameNotFoundException('Unable to find user "' . $username . '"');
}
回答3:
Did you try to convert the input into lowercase using CSS ? There are actually ways to control data input before it is handed to the login_check controller, but if you want a quick fix :
p {
text-transform: lowercase;
}
回答4:
In your setUsername
you could just have the text changed to lowercase like..
public function setUsername($username)
{
$this->username = mb_strtolower($username);
return $this;
}
For reference, FOSUserBundle handles this by "canonicalizing" the username (to usernameCanonical
) and email address (to canonicalEmail
) in the updateUser
call (see Doctrine\UserManager that calls the Canonicalizer) which it then uses for searches.
回答5:
I feel like an idiot. All I had to do was add another lower()
around the where
clause in my SQL statement. Like this:
select lower(USERNAME) as USERNAME, PASSWORD, ROLES, ALL_CUSTOMER_ACCESS
from COMPANYNAME_USERS
where lower(USERNAME) = lower(:username)
来源:https://stackoverflow.com/questions/31662683/case-insensitive-user-names-in-symfony2