* @copyright Since 2007 PrestaShop SA and Contributors * @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) */ namespace PrestaShopBundle\Security\Admin; use Access; use PrestaShop\PrestaShop\Adapter\LegacyContext; use Psr\Cache\CacheItemPoolInterface; use Symfony\Component\Security\Core\Exception\UnsupportedUserException; use Symfony\Component\Security\Core\Exception\UsernameNotFoundException; use Symfony\Component\Security\Core\User\UserInterface; use Symfony\Component\Security\Core\User\UserProviderInterface; /** * Class EmployeeProvider To retrieve Employee entities for the Symfony security components. */ class EmployeeProvider implements UserProviderInterface { public const ROLE_EMPLOYEE = 'ROLE_EMPLOYEE'; private $legacyContext; /** * @var CacheItemPoolInterface */ private $cache; public function __construct(LegacyContext $context, CacheItemPoolInterface $cache) { $this->legacyContext = $context->getContext(); $this->cache = $cache; } /** * Fetch the Employee entity that matches the given username. * Cache system doesn't supports "@" character, so we rely on a sha1 expression. * * @param string $username * * @return Employee * * @throws UsernameNotFoundException */ public function loadUserByUsername($username) { $cacheKey = sha1($username); $cachedEmployee = $this->cache->getItem("app.employees_${cacheKey}"); if ($cachedEmployee->isHit()) { return $cachedEmployee->get(); } if ( null !== $this->legacyContext->employee && $this->legacyContext->employee->email === $username ) { $employee = new Employee($this->legacyContext->employee); $employee->setRoles( array_merge([self::ROLE_EMPLOYEE], Access::getRoles($this->legacyContext->employee->id_profile)) ); $cachedEmployee->set($employee); $this->cache->save($cachedEmployee); return $cachedEmployee->get(); } throw new UsernameNotFoundException(sprintf('Username "%s" does not exist.', $username)); } /** * Reload an Employee and returns a fresh instance. * * @param UserInterface $employee * * @return Employee */ public function refreshUser(UserInterface $employee) { if (!$employee instanceof Employee) { throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', get_class($employee))); } return $this->loadUserByUsername($employee->getUsername()); } /** * Tests if the given class supports the security layer. Here, only Employee class is allowed to be used to authenticate. * * @param string $class * * @return bool */ public function supportsClass($class) { return $class === 'PrestaShopBundle\Security\Admin\Employee'; } }