php Symfony-Component-Security-Core-Authentication-Token-Storage-TokenStorage类(方法)实例源码

下面列出了php Symfony-Component-Security-Core-Authentication-Token-Storage-TokenStorage 类(方法)源码代码实例,从而了解它的用法。

作者:BeerCoder    项目:portfolio-ap   
/**
  * @param TokenStorage $security
  */
 public function __construct(TokenStorage $security)
 {
     $token = $security->getToken();
     if ($token) {
         $this->user = $token->getUser();
     }
 }

作者:NeonX    项目:NightQues   
public function createMainMenu(TokenStorage $tokenStorage)
 {
     /** @var User $user */
     $user = $tokenStorage->getToken()->getUser();
     $menu = $this->factory->createItem('root', ['navbar' => true]);
     $layout = $menu->addChild('Главная страница', ['icon' => 'home', 'route' => 'homepage']);
     $layout = $menu->addChild('Архив игр', ['icon' => 'archive', 'route' => 'archive']);
     if ($user instanceof User) {
         $dropdown = $menu->addChild($user->getUsername(), ['dropdown' => true, 'caret' => true, 'icon' => 'user']);
         $dropdown->addChild('Профиль', ['route' => 'fos_user_profile_edit', 'icon' => 'user']);
         $dropdown->addChild('Выход', ['route' => 'fos_user_security_logout', 'icon' => 'sign-out']);
         $menu->addChild('Командные настройки', ['route' => 'team_settings', 'icon' => 'users']);
         if ($user->hasRole('ROLE_ADMIN')) {
             $menu->addChild('Администрирование домена', ['route' => 'sonata_admin_dashboard', 'icon' => 'edit']);
         }
     } else {
         $login = $menu->addChild('Вход', ['dropdown' => true, 'caret' => true, 'icon' => 'sign-in']);
         $login->addChild('ВКонтакте', ['route' => 'vkontakte_oauth', 'icon' => 'vk']);
         $login->addChild('Facebook', ['route' => 'facebook_oauth', 'icon' => 'facebook']);
         $login->addChild('Google+', ['route' => 'google_oauth', 'icon' => 'google-plus']);
         $login->addChild('Вход через логин/пароль', ['route' => 'fos_user_security_login', 'icon' => 'sign-in']);
         $menu->addChild('Регистрация', ['route' => 'fos_user_registration_register']);
         $menu->addChild('Сброс пароля', ['route' => 'fos_user_resetting_request']);
     }
     return $menu;
 }

作者:BusinessCookie    项目:CoffeeMachineProjec   
public function testGetSetToken()
 {
     $tokenStorage = new TokenStorage();
     $this->assertNull($tokenStorage->getToken());
     $token = $this->getMock('Symfony\\Component\\Security\\Core\\Authentication\\Token\\TokenInterface');
     $tokenStorage->setToken($token);
     $this->assertSame($token, $tokenStorage->getToken());
 }

作者:halaszbalaz    项目:issuetracke   
public function __construct(ContainerInterface $container, EntityManager $entityManager, TranslatorInterface $translator, TokenStorage $tokenStorage)
 {
     $this->request = $container->get('request');
     $this->container = $container;
     $this->em = $entityManager;
     $this->trans = $translator;
     $this->token = $tokenStorage->getToken();
 }

作者:DanieleMenar    项目:CreateSaf   
/**
  * @param \Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage    $tokenStorage
  */
 public function __construct(TokenStorage $tokenStorage)
 {
     $this->tokenStorage = $tokenStorage;
     $this->hashedUsername = password_hash($this->tokenStorage->getToken()->getUser()->getUsername(), PASSWORD_DEFAULT);
     if (strlen($this->hashedUsername) > 8) {
         $this->hashedUsername = substr($this->hashedUsername, -8);
     }
 }

作者:ayoa    项目:symfon   
public function testIntegrationNoUser()
 {
     $token = $this->getMock(TokenInterface::class);
     $tokenStorage = new TokenStorage();
     $tokenStorage->setToken($token);
     $argumentResolver = new ArgumentResolver(null, array(new SecurityUserValueResolver($tokenStorage), new DefaultValueResolver()));
     $this->assertSame(array(null), $argumentResolver->getArguments(Request::create('/'), function (UserInterface $user = null) {
     }));
 }

作者:Chill-projec    项目:Activit   
public function __construct(EntityManager $em, AuthorizationHelper $helper, TokenStorage $storage)
 {
     $this->em = $em;
     $this->helper = $helper;
     if (!$storage->getToken()->getUser() instanceof \Chill\MainBundle\Entity\User) {
         throw new \RuntimeException('A user should be authenticated !');
     }
     $this->user = $storage->getToken()->getUser();
 }

作者:sasede    项目:acf-exper   
/**
  * Update the user "lastActivity" on each request
  *
  * @param FilterControllerEvent $event
  */
 public function onCoreController(FilterControllerEvent $event)
 {
     // Here we are checking that the current request is a "MASTER_REQUEST",
     // and ignore any
     // subrequest in the process (for example when
     // doing a render() in a twig template)
     if ($event->getRequestType() !== HttpKernel::MASTER_REQUEST) {
         return;
     }
     // We are checking a token authentification is available before using
     // the User
     if ($this->tokenStorage->getToken()) {
         $user = $this->tokenStorage->getToken()->getUser();
         // We are using a delay during wich the user will be considered as
         // still active, in order to
         // avoid too much UPDATE in the
         // database
         // $delay = new \DateTime ();
         // $delay
         // ->setTimestamp (strtotime ('2 minutes ago'));
         // We are checking the Admin class in order to be certain we can
         // call "getLastActivity".
         // && $user->getLastActivity() < $delay) {
         if ($user instanceof User) {
             $user->isActiveNow();
             $this->em->persist($user);
             $this->em->flush();
         }
     }
 }

作者:mishki-svam    项目:pa-cor   
protected function isGranted($attribute, $object, $user = null)
 {
     if (!$user) {
         $user = $this->tokenStorage->getToken()->getUser();
     }
     if (!is_object($user)) {
         return false;
     }
     if (in_array('ROLE_ADMINISTRATOR', $user->getRoles())) {
         return true;
     }
     if (!in_array('ROLE_USER', $user->getRoles())) {
         return false;
     }
     if (in_array($attribute, [self::ATTRIBUTE_VIEW, self::ATTRIBUTE_CREATE])) {
         return true;
     }
     /**
      * @var Subcontractor $object
      */
     if ($attribute == self::ATTRIBUTE_EDIT) {
         return $object->getCreatedBy() && $user->getId() == $object->getCreatedBy()->getId() || in_array('ROLE_SUBCONTRACTOR_MANAGER', $user->getRoles());
     }
     return false;
 }

作者:fulcrum3    项目:PartKeep   
/**
  * Returns the PartKeeprUser based on the user token within the Symfony2 environment.
  *
  * @return User The proxy user
  */
 public function getUser()
 {
     $tokenProvider = $this->tokenStorage->getToken()->getAttribute("provider");
     $provider = $this->getProvider($tokenProvider);
     $username = $this->tokenStorage->getToken()->getUsername();
     return $this->getProxyUser($username, $provider, true);
 }

作者:nabelh    项目:ap   
/**
  * @param Request $request
  *
  * @return JsonResponse
  *
  * @throws \Assert\AssertionFailedException
  * @throws InvalidMobileApiException
  * @throws BlankAliasApiException
  * @throws NoTopicsApiException
  * @throws InsufficientBalanceApiException
  * @throws ExistentMobileApiException
  */
 protected function create(Request $request)
 {
     /** @var UsernamePasswordToken $token */
     $token = $this->tokenStorage->getToken();
     $uniqueness = $token->getUsername();
     $data = $request->request->all();
     foreach (array('mobile', 'alias', 'topics') as $key) {
         Assertion::keyExists($data, $key);
     }
     try {
         $this->createSubscriptionApiWorker->create($data['mobile'], $uniqueness, $data['alias'], $data['topics'], $data['resellPackage']);
     } catch (InvalidMobileApiException $e) {
         return new JsonResponse(array('code' => 'INFO_SMS.SUBSCRIPTION.INVALID_MOBILE'), 400);
     } catch (BlankAliasApiException $e) {
         return new JsonResponse(array('code' => 'INFO_SMS.SUBSCRIPTION.BLANK_ALIAS'), 400);
     } catch (ExistentMobileApiException $e) {
         return new JsonResponse(array('code' => 'INFO_SMS.SUBSCRIPTION.EXISTENT_MOBILE'), 400);
     } catch (NoTopicsApiException $e) {
         return new JsonResponse(array('code' => 'INFO_SMS.SUBSCRIPTION.NO_TOPICS'), 400);
     } catch (NoResellPackageApiException $e) {
         return new JsonResponse(array('code' => 'INFO_SMS.SUBSCRIPTION.NO_RESELL_PACKAGE'), 400);
     } catch (TrialNotAcceptedApiException $e) {
         return new JsonResponse(array('code' => 'INFO_SMS.SUBSCRIPTION.TRIAL_NOT_ACCEPTED'), 400);
     } catch (InsufficientBalanceApiException $e) {
         return new JsonResponse(array('code' => 'INFO_SMS.PROFILE.INSUFFICIENT_BALANCE'), 400);
     }
     return new JsonResponse();
 }

作者:octav    项目:cm   
/**
  * @param \Sonata\AdminBundle\Admin\AdminInterface $admin
  * @param string|array $attributes
  * @param null $object
  *
  * @return boolean
  */
 public function isGranted(AdminInterface $admin, $attributes, $object = null)
 {
     /** @var Administrator $administrator */
     $administrator = $this->tokenStorage->getToken()->getUser();
     if (!$administrator instanceof Administrator) {
         return false;
     }
     $availableResources = $administrator->getAvailableResources();
     $list = $this->entityManager->getRepository('OctavaAdministratorBundle:Resource')->getList();
     if (!is_array($attributes)) {
         $attributes = [$attributes];
     }
     foreach ($attributes as $attribute) {
         if (in_array($attribute, ["EXPORT", "VIEW"])) {
             $attribute = 'LIST';
         }
         if (!isset($list[get_class($admin)][$attribute])) {
             continue;
         }
         $currentId = $list[get_class($admin)][$attribute];
         if (isset($availableResources[$currentId])) {
             return true;
         }
     }
     return false;
 }

作者:klink    项目:time   
/**
  * @param FormBuilderInterface $builder
  * @param array $options
  */
 public function buildForm(FormBuilderInterface $builder, array $options)
 {
     $user = $this->tokenStorage->getToken()->getUser();
     $builder->add('text')->add('task', EntityType::class, ['class' => 'AppBundle:Task', 'choice_label' => 'name', 'placeholder' => '===== SELECT TASK =====', 'query_builder' => function (EntityRepository $er) use($user) {
         return $er->createQueryBuilder('task')->where('task.owner = :user')->setParameter('user', $user)->orderBy('task.isDefault', 'DESC')->addOrderBy('task.name', 'ASC');
     }])->add('finish', CheckboxType::class, ['mapped' => false, 'required' => false]);
 }

作者:nabelh    项目:ap   
/**
  * @Req\Route("/info-sms/me/pick-profile")
  * @Req\Method({"GET"})
  *
  * @return JsonResponse
  */
 public function pickAction()
 {
     /** @var UsernamePasswordToken $token */
     $token = $this->tokenStorage->getToken();
     $uniqueness = $token->getUsername();
     return new JsonResponse($this->pickProfileApiWorker->pick($uniqueness));
 }

作者:ESNFranceG33kTea    项目:sf_faucondo   
public function handle(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     $wsseRegex = '/UsernameToken Username="([^"]+)", PasswordDigest="([^"]+)", Nonce="([^"]+)", Created="([^"]+)"/';
     if (!$request->headers->has('x-wsse') || 1 !== preg_match($wsseRegex, $request->headers->get('x-wsse'), $matches)) {
         $response = new Response();
         $response->setStatusCode(403);
         $response->setContent('Invalid or missing WSSE.');
         $event->setResponse($response);
         return;
     }
     $token = new WsseUserToken();
     $token->setUser($matches[1]);
     $token->digest = $matches[2];
     $token->nonce = $matches[3];
     $token->created = $matches[4];
     try {
         $authToken = $this->authenticationManager->authenticate($token);
         $this->tokenStorage->setToken($authToken);
     } catch (AuthenticationException $failed) {
         $response = new Response();
         $response->setStatusCode(403);
         $response->getContent($failed->getMessage());
         $event->setResponse($response);
     }
 }

作者:sainthardawa    项目:atlassian-connect-bundl   
public function onKernelRequest(GetResponseEvent $event)
 {
     if (!$event->isMasterRequest()) {
         return;
     }
     $request = $event->getRequest();
     $routes = $this->router->getRouteCollection();
     $route = $routes->get($request->attributes->get('_route'));
     if (!$route->getOption('requires_license')) {
         return;
     }
     if ('active' != $request->get('lic') && $this->kernel->getEnvironment() == 'prod') {
         // Checking for whitelisted users
         try {
             $user = $this->tokenStorage->getToken()->getUser();
             $today = date('Y-m-d');
             if ($user instanceof UserInterface) {
                 $whitelist = $this->kernel->getContainer()->getParameter('license_whitelist');
                 foreach ($whitelist as $allowed) {
                     if ($allowed['client_key'] == $user->getClientKey() && $today <= $allowed['valid_till']) {
                         return;
                     }
                 }
             }
         } catch (\Exception $e) {
             // Do nothing
         }
         $url = $this->router->generate('atlassian_connect_unlicensed');
         $response = new RedirectResponse($url);
         $event->setResponse($response);
     }
 }

作者:ekreativ    项目:server-manage   
/**
  * @return User|null
  */
 private function getUser()
 {
     if ($token = $this->tokenStorage->getToken()) {
         return $token->getUser();
     }
     return null;
 }

作者:Opife    项目:Cm   
public function save(ContentInterface $content)
 {
     if (!$content->getId()) {
         $content->setAuthor($this->tokenStorage->getToken()->getUser());
     }
     return parent::save($content);
 }

作者:nabelh    项目:ap   
/**
  * @Req\Route("/credit/me/profile/balance/collect-operations")
  * @Req\Method({"GET"})
  *
  * @return JsonResponse
  */
 public function collectByUniquenessAction()
 {
     /** @var UsernamePasswordToken $token */
     $token = $this->tokenStorage->getToken();
     $uniqueness = $token->getUsername();
     return new JsonResponse($this->collectOperationsApiWorker->collect($uniqueness));
 }

作者:Eraa    项目:rest-projec   
public function onKernelTerminate(PostResponseEvent $event)
 {
     /** @var Request $request */
     $request = $event->getRequest();
     if (!$this->isEnable || !$this->isLoggableRequest($request)) {
         return;
     }
     try {
         /** @var Response $response */
         $response = $event->getResponse();
         $route = $request->get('_route');
         $content = $this->cleanSensitiveContent($route, $request->getContent());
         $token = $this->tokenStorage->getToken();
         $user = !is_null($token) ? $token->getUser() : null;
         $logRequest = new LogRequest();
         $logRequest->setRoute($route)->setPath($request->getPathInfo())->setMethod($request->getMethod())->setQuery(urldecode($request->getQueryString()))->setContent($content)->setStatus($response->getStatusCode())->setIp($request->getClientIp())->setUser(!is_string($user) ? $user : null);
         if ($this->logResponse($response)) {
             $logRequest->setResponse($response->getContent());
         }
         $this->em->persist($logRequest);
         $this->em->flush();
     } catch (\Exception $e) {
         $this->logger->error(sprintf("LogRequest couldn't be persist : %s", $e->getMessage()));
     }
 }


问题


面经


文章

微信
公众号

扫码关注公众号