Symfony 3 - Login with extra field

511 views Asked by At

I need to login users with 3 fields
- email
- password
- office (an entity with a oneToMany relation with my user entity)

I already have a provider based on my user entity

providers:
    admin:
        entity: { class: AdminBundle\Entity\User, property: email }

Logging with email / password work without any problem.

I need now to add an extra check as a same email can have multiple account (one per office) with different password, so in my login form, i have added an extra field Office (a choiceType referencing the offices IDs).

How can I pass this extra field information to my custom LoadUserByUsername to add a check on office so i have the couple email / office validated : WHERE u.office = :office AND u.email = :email.

Thanks !

1

There are 1 answers

7
Robert On

Hi can you try like this

security.yml

security:
# ...

   providers:
       our_db_provider:
            entity:
                 class: AppBundle:User 

and you need write mapping for that

// src/AppBundle/Repository/UserRepository.php
namespace AppBundle\Repository;

use Symfony\Bridge\Doctrine\Security\User\UserLoaderInterface;
use Doctrine\ORM\EntityRepository;

class UserRepository extends EntityRepository implements UserLoaderInterface
 {
    public function loadUserByUsername($username)
      {

       return $em->createQueryBuilder()
            ->select('u')
            ->from('YourBundle:User', 'a')
            ->join('YourBundle:Office', 'b', 'WITH', 'b.id = a.officeid')
            ->where('b.officeid = :office')
            ->ANDwhere('a.username = :username')
            ->setParameter('username', $username)
            ->setParameter('office', $office)
            ->getQuery()
            ->getOneOrNullResult();
       }
   }

source symfony document