Contao Login Case-Insensitive
Usually the login in Contao is case-sensitive. But especially when using the email address of users as there username for the login this doesn't make sense. From a technical perspective it's understandable. But there are way to many users that type there email as they see fit. Especially if there is a name in the email address as for example: christian.kolb@liplex.de. Then there are multiple versions including Christian.Kolb@liplex.de.
The easiest way to enable a case-insensitive login in Contao is to change the collation from the default utf8_bin
which is case-sensitive to utf8_general_ci
which is case-insensitive.
In your tl_member.php
in dca
folder add the following line:
<?php
// Replace utf8_bin to utf8_general_ci to make username case-insensitive
$GLOBALS['TL_DCA']['tl_member']['fields']['username']['sql'] = 'varchar(64) COLLATE utf8_general_ci NULL';
That's it!
In addition to this I normalize the email addresses on registration. For this I build a custom hook which is used in the registration process. In it I transform the entered email address in the signup form to lowercase and store it as username and email address.
<?php
namespace AppBundle\Hooks;
use AppBundle\Entity\Member;
use AppBundle\Repository\MemberRepository;
use Contao\System;
use Doctrine\ORM\ORMException;
class MemberHooks
{
/**
* @var MemberRepository
*/
private $memberRepository;
/**
* MemberDataContainer constructor.
*/
public function __construct()
{
$doctrine = System::getContainer()->get('doctrine');
$this->memberRepository = $doctrine->getRepository(Member::class);
}
/**
* Set set username to be the same as the email address.
*
* @param int $memberId
* @param array $arrData
* @param $element
*
* @throws ORMException
*/
public function onCreateMember(int $memberId, array $arrData, $element): void
{
$member = $this->memberRepository->findOneById($memberId);
if (null !== $member) {
$emailLowercase = strtolower($member->getEmail());
$member->setEmail($emailLowercase);
$member->setUsername($emailLowercase);
$this->memberRepository->store($member);
}
}
}
This hook of course has to be registered in the config.php
in your config
folder.
<?php
// Hooks
$GLOBALS['TL_HOOKS']['createNewUser'][] = [MemberHooks::class, 'onCreateMember'];