大家好!我想登录我的用户,这是一个微不足道的任务。但问题是检查用户数组的值!
例如,我有实体用户和电话。用户有多部手机。我需要登录所有手机的用户。如何使用安全包的默认工具?
我没有发现任何像我这样的问题,并且阅读了所有关于Symfony安全的文档。我唯一想做的是创建自定义提供程序。但我不认为这能解决我的问题。
亲爱的symfoners,有什么想法吗?:)你必须在security中设置一个安全提供者。yml
security:
# http://symfony.com/doc/current/book/security.html#where-do-users-come-from-user-providers
...
providers:
my_db_provider:
entity:
class: AppBundle:User
...
那么你的实体AppBundle:User
应该实现接口Symfony'Component'Security'Core'User'UserInterface
,并有一个自定义存储库,例如UserRepository
实现接口Symfony'Bridge'Doctrine'Security'User'UserLoaderInterface
。你的UserRepository
类应该是这样的:
<?php
use Doctrine'ORM'NonUniqueResultException;
use Doctrine'ORM'NoResultException;
use AppBundle'Entity'User;
use Symfony'Bridge'Doctrine'Security'User'UserLoaderInterface;
use Symfony'Component'Security'Core'Exception'UsernameNotFoundException;
class UserRepository extends EntityRepository implements UserLoaderInterface
{
/**
* Loads the user for the given username.
*
* This method must return null if the user is not found.
*
* @param string $username The username
* @return null|Utilisateur
* @throws 'Exception
*/
public function loadUserByUsername($username)
{
//Here you write a custom query to retrive the user base on the fields you require.
// Here I have used username, email and phone number
$q = $this
->createQueryBuilder('u')
->select('u')
->leftJoin('u.phones', 'p')
->where('u.username = :username or u.email= :email or p.phoneNumber= :phone')
->setParameter('username', $username)
->setParameter('email', $username)
->setParameter('phone ', $username)
->getQuery();
try {
$user = $q->getSingleResult();
} catch (NoResultException $e) {
throw new UsernameNotFoundException(sprintf('Unable to find an active user AppBundle:User object identified by "%s".', $username), 0, $e);
} catch (NonUniqueResultException $ex) {
throw new 'Exception("The user you provided is not unique");
}
return $user;
}
}
你的AppByndle:User
实体类应该是这样的:
<?php
use Doctrine'Common'Collections'ArrayCollection;
use Doctrine'Common'Collections'Collection;
use Doctrine'ORM'Mapping as ORM;
use Symfony'Component'Security'Core'User'UserInterface;
/**
* User
*
* @ORM'Table(name="user")
* @ORM'Entity(repositoryClass="AppBundle'Dao'UserRepository")
*/
class User implements UserInterface
{
/**
* @var integer
*
* @ORM'Column(name="id", type="integer", nullable=false)
* @ORM'Id
* @ORM'GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @var string
*
* @ORM'Column(name="username", type="string", length=254, nullable=false, unique=true)
*/
private $username;
....
....
}