src/ApiV3Bundle/Security/Firewall/AnonymousListener.php line 54

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the Symfony package.
  4.  *
  5.  * (c) Fabien Potencier <fabien@symfony.com>
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. namespace ApiV3Bundle\Security\Firewall;
  11. use Biz\Role\Util\PermissionBuilder;
  12. use Biz\User\CurrentUser;
  13. use Symfony\Component\HttpFoundation\Request;
  14. use Symfony\Component\Security\Core\Authentication\Token\AnonymousToken;
  15. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  16. class AnonymousListener implements ListenerInterface
  17. {
  18.     private $tokenStorage;
  19.     public function __construct(TokenStorageInterface $tokenStorage)
  20.     {
  21.         $this->tokenStorage $tokenStorage;
  22.     }
  23.     public function handle(Request $request)
  24.     {
  25.         if (null !== $this->tokenStorage->getToken()) {
  26.             return;
  27.         }
  28.         $token $this->createAnonymousToken($request->getClientIp());
  29.         $this->tokenStorage->setToken($token);
  30.     }
  31.     private function createAnonymousToken($clientIp)
  32.     {
  33.         $user = [
  34.             'id' => 0,
  35.             'nickname' => '游客',
  36.             'email' => 'fakeUser',
  37.             'locale' => 'zh_CN',
  38.             'roles' => [],
  39.             'currentIp' => $clientIp,
  40.         ];
  41.         $currentUser = new CurrentUser();
  42.         $currentUser->fromArray($user);
  43.         $currentUser->setPermissions(PermissionBuilder::instance()->findPermissionsByRoles($currentUser->getRoles()));
  44.         return new AnonymousToken(''$currentUser);
  45.     }
  46. }