Symfony2 FosUserBundle customize Login query

百般思念 提交于 2019-12-11 12:12:45

问题


i'm using FosUserBundle in my Symfony2 project, i have the login working, i want to now further customize login to include checking for id along with username, email and password. i have a User entity in the Entity folder, i have a UserRepository in the Repository folder

  • How do i customize Fos UserBundle login to include id in its query
  • What are the list of possible different ways i could do this
  • any other suggestion to improve code are welcomed

-thankyou

The User Entity:

<?php
    namespace Example\Bundle\ExampleBundle\Entity;

    use FOS\UserBundle\Entity\User as BaseUser;
    use Doctrine\ORM\Mapping as ORM;
    use Symfony\Component\Validator\Constraints as Assert;

 /**
  * User
  *
  * @ORM\Table(name="Example_user")
  * @ORM\Entity(repositoryClass="Example\Bundle\ExampleBundle\Repository\UserRepository")
  */
class User extends BaseUser {

/**
 * @var integer
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
protected $id;

/*
*  some Class properties here 
*
*/

/**
 * Get id
 *
 * @return integer 
 */
public function getId() {
    return $this->id;
}

/*
* some setters and getters here
*/
}

The User Repository

<?php
  namespace Example\Bundle\ExampleBundle\Repository;

  use Doctrine\ORM\EntityRepository;
  use Symfony\Component\Security\Core\User\UserProviderInterface;

  use Example\Bundle\ExampleBundle\siteConfig;

  class UserRepository extends EntityRepository implements UserProviderInterface{

public $university = siteConfig::university_id;

/**
 * 
 * @param type $username
 */
public function FindUsernameOrEmailInUniversity($username, $universityId) {

    return  $this->createQueryBuilder('user')
            ->where('user.university_id = :universityId')
            ->andWhere('user.username = :username OR user.email = :email')
            ->setParameter('universityId', $universityId)
            ->setParameter('username', $username)
            ->setParameter('email', $username)
            ->getQuery()
            ->getOneOrNullResult();

}

/**
 * 
 * @param type $username
 */
public function loadUserByUsername($username) {

    $user = $this->FindUsernameOrEmailInUniversity($username, $this->university); //check order of parameters use type hinting

    if(!$user){
        throw new \Symfony\Component\Security\Core\Exception\UsernameNotFoundException('User Name '.$username.' Not Found');
    }

    return $user;
}

/**
 * 
 * @param \Symfony\Component\Security\Core\User\UserInterface $user
 */
public function refreshUser(\Symfony\Component\Security\Core\User\UserInterface $user) {

    return $user;
}

/**
 * 
 * @param type $class
 */
public function supportsClass($class) {

    return ;
}
}

The Security.yml

# app/config/security.yml
security:
    encoders:
        FOS\UserBundle\Model\UserInterface: bcrypt

role_hierarchy:
    ROLE_ADMIN:       ROLE_USER
    ROLE_SUPER_ADMIN: ROLE_ADMIN

providers:
    fos_userbundle:
        entity: { class: Example\Bundle\ExampleBundle\Repository\UserRepository }

firewalls:
    main:
        pattern: ^/
        form_login:
            provider: fos_userbundle
            csrf_provider: security.csrf.token_manager # Use form.csrf_provider instead for Symfony <2.4
        logout:       true
        anonymous:    true

access_control:
    - { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/admin/, role: ROLE_ADMIN }

Here is the error i'm getting

The class 'Example\Bundle\ExampleBundle\Repository\UserRepository' was not found in the chain configured namespaces Example\Bundle\ExampleBundle\Entity, FOS\UserBundle\Entity

回答1:


Create a class inside entity folder that extends FOS\UserBundle\Doctrine\UserManager (i'm assuming there is a class called siteConfig.php with a static University_id field updated by a db query)

<?php
namespace Example\Bundle\ExampleBundle\Entity

use FOS\UserBundle\Doctrine\UserManager as BaseUserManager;
use Doctrine\ORM\EntityManager;
use Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface;
use FOS\UserBundle\Util\CanonicalizerInterface;
use FOS\UserBundle\Model\UserInterface;
use Example\Bundle\ExampleBundle\siteConfig;

class UserManager extends BaseUserManager {
public function __construct(EncoderFactoryInterface $encoderFactory, CanonicalizerInterface $usernameCanonicalizer, 
                                    CanonicalizerInterface $emailCanonicalizer, EntityManager $em, $class) {

    parent::__construct($encoderFactory, $usernameCanonicalizer, $emailCanonicalizer, $em, $class);

}
/**
 * this overides the findUserByUsernameOrEmail in FOS\UserBundle\Doctrine\UserManager
 **/
public function findUserByUsernameOrEmail($usernameOrEmail) {
    if (filter_var($usernameOrEmail, FILTER_VALIDATE_EMAIL)) {
        return $this->findUserBy(array('emailCanonical' => $this->canonicalizeEmail($usernameOrEmail), 'university' => siteConfig::$university_id));
    }

    return $this->findUserBy(array('usernameCanonical' => $this->canonicalizeUsername($usernameOrEmail), 'university' => siteConfig::$university_id));
}
}

Dependency injection for User manager, inside services.yml

ExampleUserManager:
class: namespace Example\Bundle\ExampleBundle\Entity\UserManager
     arguments: [@security.encoder_factory, @fos_user.util.username_canonicalizer, @fos_user.util.email_canonicalizer, @fos_user.entity_manager, namespace Example\Bundle\ExampleBundle\Entity\User]

Inside config.yml add the following configuration under fos_user

service:
    user_manager: ExampleUserManager

Inside security.yml under provider add the following

providers:
    fos_userbundle:
        id: fos_user.user_provider.username_email



回答2:


First of all there is mistype - an extra paranthese in defining repository class for entity line:

/**
 * User
 *
 * @ORM\Table(name="Example_user")
 * @ORM\Entity(repositoryClass="Example\Bundle\ExampleBundle\Repository\UserRepository")
 */
 class User extends BaseUser {

Try this, I made some corrections to your method:

/**
 * @param type $username
 */
 public function FindUsernameOrEmailInUniversity($username, University $university) {

      return  $this->createQueryBuilder('user') //It should be alias for your entity name, and it could be anything you write, like 'user' or just 'u'
          ->where('user.university = :university')
          ->andWhere('user.username = :username OR user.email = :email')
          ->setParameter('university', $university)
          ->setParameter('username', $username)
          ->setParameter('email', $username)
          ->getQuery()
          ->getOneOrNullResult();

}

Also do you have getters, setters and properties for university, email and username? I assume that you want to make university as relation to User, so you would want to setup properly doctrine relation.



来源:https://stackoverflow.com/questions/31921393/symfony2-fosuserbundle-customize-login-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!