<?php
namespace App\Security;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\Exception\UserNotFoundException;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Doctrine\ORM\EntityManagerInterface;
use App\Entity\User;
/**
*
* @author wendell.zheng <wxzheng@ustc.edu.cn>
*/
class CasUserProvider implements UserProviderInterface
{
protected $em;
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}
public function loadUserByIdentifier(string $identifier): UserInterface
{
try {
$user = $this->fetchUser($identifier);
} catch (UserNotFoundException $notFound) {
$user = $this->createUser($identifier);
}
return $user;
}
public function loadUserByUsername(string $username): UserInterface
{
return $this->loadUserByIdentifier($username);
}
public function refreshUser(UserInterface $user): UserInterface
{
if (! $user instanceof User) {
throw new UnsupportedUserException(sprintf('Invalid user class "%s".', get_class($user)));
}
$username = $user->getUserIdentifier();
return $this->fetchUser($username);
}
public function supportsClass(string $class): bool
{
return User::class === $class || is_subclass_of($class, User::class);
}
protected function createUser(string $username): UserInterface
{
$user = new User();
$user->setUsername($username);
$user->setName('');
$this->em->persist($user);
$this->em->flush();
return $user;
}
protected function fetchUser(string $username): UserInterface
{
$user = $this->em->getRepository(User::class)->findOneByUsername($username);
if (! $user) {
throw new UserNotFoundException(sprintf('Username "%s" does not exist.', $username));
}
return $user;
}
}