<?php
namespace Biz\User;
use AppBundle\Handler\AuthenticationHelper;
use Biz\Role\Util\PermissionBuilder;
use Biz\User\Service\UserService;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\Exception\UserNotFoundException;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Topxia\Service\Common\ServiceKernel;
class UserProvider implements UserProviderInterface
{
private $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
public function loadUserByUsername($username)
{
$user = $this->getUserService()->getUserByLoginField($username);
if (empty($user)) {
throw new UserNotFoundException(sprintf('User "%s" not found.', $username));
} elseif (isset($user['type']) && 'system' == $user['type']) {
throw new UserNotFoundException(sprintf('User "%s" not found.', $username));
}
$request = $this->container->get('request_stack')->getMainRequest();
$forbidden = AuthenticationHelper::checkLoginForbidden($user['id'], $request->getClientIp());
if ('error' == $forbidden['status']) {
throw new AuthenticationException($forbidden['message']);
}
$forbidden = AuthenticationHelper::checkMayday($user, $request->request->get('isMayday', 0));
if ('error' == $forbidden['status']) {
throw new AuthenticationException($forbidden['message']);
}
$user = $this->getUserService()->getUserWithOrgScopes($user['id']);
$user['currentIp'] = $request->getClientIp();
$currentUser = new CurrentUser();
$currentUser->fromArray($user);
$currentUser->setPermissions(PermissionBuilder::instance()->findPermissionsByRoles($currentUser->getRoles()));
$currentUser['isSecure'] = $request->isSecure();
$biz = $this->container->get('biz');
$biz['user'] = $currentUser;
ServiceKernel::instance()->setCurrentUser($currentUser);
return $currentUser;
}
public function refreshUser(UserInterface $user)
{
if (!$user instanceof CurrentUser) {
throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', get_class($user)));
}
return $this->loadUserByUsername($user->getUsername());
}
public function supportsClass($class)
{
return 'Biz\User\CurrentUser' === $class;
}
protected function getRoleService()
{
return ServiceKernel::instance()->createService('Role:RoleService');
}
/**
* @return UserService
*/
protected function getUserService()
{
return $this->container->get('biz')->service('User:UserService');
}
protected function getOrgService()
{
return ServiceKernel::instance()->createService('Org:OrgService');
}
}