php Symfony-Component-Security-Core-SecurityContext类(方法)实例源码

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

作者:ArmelTchamal    项目:SdzBlo   
public function __construct(AkismetInterface $akismet, SecurityContext $securityContext)
 {
     $this->akismet = $akismet;
     // On détermine si l'utilisateur courant est identifié
     // Si c'est le cas, on n'utilisera pas akismet
     $this->isAuthenticated = $securityContext->isGranted('IS_AUTHENTICATED_REMEMBERED');
 }

作者:ChrisdAutum    项目:EtuUT   
/**
  * @param EntityManager $manager
  * @param SecurityContext $context
  * @param GlobalAccessorObject $globalAccessorObject
  * @param Stopwatch $stopwatch
  */
 public function __construct(EntityManager $manager, SecurityContext $context, GlobalAccessorObject $globalAccessorObject, Stopwatch $stopwatch = null)
 {
     $this->manager = $manager;
     $this->user = $context->getToken()->getUser();
     $this->globalAccessorObject = $globalAccessorObject;
     $this->stopwatch = $stopwatch;
 }

作者:alvsgithu    项目:Newscoo   
public function let(ArticleService $articleService, AuthorService $authorService, CacheService $cacheService, Container $container, ArticleRepository $articleRepository, LanguageRepository $languageRepository, ArticleTypeRepository $articleTypeRepository, PublicationRepository $publicationRepository, IssueRepository $issueRepository, SectionRepository $sectionRepository, AuthorTypeRepository $authorTypeRepository, EntityManager $entityManager, Request $request, FormFactory $formFactory, FormBuilder $formBuilder, Form $form, FormView $formView, User $user, UserService $userService, Article $article, Publication $publication, ArticleType $articleType, Issue $issue, Section $section, Language $language, Author $author, AuthorType $authorType, AbstractQuery $query, SecurityContext $security, TokenInterface $token, Router $router)
 {
     $container->get('em')->willReturn($entityManager);
     $container->get('request')->willReturn($request);
     $container->get('user')->willReturn($userService);
     $container->get('form.factory')->willReturn($formFactory);
     $container->get('newscoop_newscoop.article_service')->willReturn($articleService);
     $container->get('author')->willReturn($authorService);
     $container->get('newscoop.cache')->willReturn($cacheService);
     $container->get('router')->willReturn($router);
     $formBuilder->getForm(Argument::cetera())->willReturn($form);
     $formFactory->create(Argument::cetera())->willReturn($form);
     $form->createView()->willReturn($formView);
     $form->handleRequest(Argument::cetera())->willReturn(true);
     $form->isValid()->willReturn(true);
     $security->getToken()->willReturn($token);
     $container->get('security.context')->willReturn($security);
     $container->has('security.context')->willReturn(true);
     $this->setContainer($container);
     $entityManager->getRepository('Newscoop\\Entity\\Article')->willReturn($articleRepository);
     $entityManager->getRepository('Newscoop\\Entity\\Language')->willReturn($languageRepository);
     $entityManager->getRepository('Newscoop\\Entity\\ArticleType')->willReturn($articleTypeRepository);
     $entityManager->getRepository('Newscoop\\Entity\\Publication')->willReturn($publicationRepository);
     $entityManager->getRepository('Newscoop\\Entity\\Issue')->willReturn($issueRepository);
     $entityManager->getRepository('Newscoop\\Entity\\Section')->willReturn($sectionRepository);
     $entityManager->getRepository('Newscoop\\Entity\\AuthorType')->willReturn($authorTypeRepository);
     $articleRepository->getArticle(Argument::cetera())->willReturn($query);
     $entityManager->flush(Argument::any())->willReturn(true);
     $userService->getCurrentUser()->willReturn($user);
     $number = 64;
     $language = "en";
 }

作者:rotano    项目:fefu-social-networ   
public function __construct(EntityManager $em, SecurityContext $securityContext, ServerManager $serverManager, Translator $translator)
 {
     $this->em = $em;
     $this->user = $securityContext->getToken()->getUser();
     $this->serverManager = $serverManager;
     $this->translator = $translator;
 }

作者:nickaggarwa    项目:sample-symfony   
public function testGetSetToken()
 {
     $context = new SecurityContext($this->getMock('Symfony\\Component\\Security\\Core\\Authentication\\AuthenticationManagerInterface'), $this->getMock('Symfony\\Component\\Security\\Core\\Authorization\\AccessDecisionManagerInterface'));
     $this->assertNull($context->getToken());
     $context->setToken($token = $this->getMock('Symfony\\Component\\Security\\Core\\Authentication\\Token\\TokenInterface'));
     $this->assertSame($token, $context->getToken());
 }

作者:ramunas    项目:platfor   
/**
  * @param EntityManager $entityManager
  * @param TranslatorInterface $translator
  * @param SecurityContext $securityContext
  * @param ServiceLink $securityFacadeLink
  * @param EmailManager $emailManager
  */
 public function __construct(EntityManager $entityManager, TranslatorInterface $translator, SecurityContext $securityContext, ServiceLink $securityFacadeLink, EmailManager $emailManager)
 {
     $this->entityManager = $entityManager;
     $this->translator = $translator;
     $this->securityContext = $securityContext;
     $this->user = $this->securityContext->getToken()->getUser();
     $this->securityFacade = $securityFacadeLink->getService();
     $this->emailManager = $emailManager;
 }

作者:jaiva    项目:SmartyBundl   
protected function createSecurityContext($granted = false)
 {
     $authManager = $this->getMock('Symfony\\Component\\Security\\Core\\Authentication\\AuthenticationManagerInterface');
     $decisionManager = $this->getMock('Symfony\\Component\\Security\\Core\\Authorization\\AccessDecisionManagerInterface');
     $decisionManager->expects($this->any())->method('decide')->will($this->returnValue($granted));
     $context = new SecurityContext($authManager, $decisionManager, false);
     $context->setToken($token = $this->getMock('Symfony\\Component\\Security\\Core\\Authentication\\Token\\TokenInterface'));
     $token->expects($this->any())->method('isAuthenticated')->will($this->returnValue(true));
     return $context;
 }

作者:Quis    项目:Evrik   
public function __construct(EntityManager $em, Session $session, SecurityContext $securityContext)
 {
     $this->em = $em;
     $this->session = $session;
     $this->securityContext = $securityContext;
     if ($token = $securityContext->getToken()) {
         $this->user = $token->getUser();
     } else {
         $this->user = null;
     }
 }

作者:josephzha    项目:map2ucor   
/**
  * @param string                  $class
  * @param ManagerRegistry         $registry
  */
 public function __construct($class, ManagerRegistry $registry, SecurityContext $securityContext)
 {
     parent::__construct($class, $registry);
     $this->user = $securityContext->getToken()->getUser();
     if ($this->user) {
         $this->userId = $this->user->getId();
     } else {
         $this->userId = 0;
     }
     $this->categories = array();
 }

作者:Belka    项目:tangara-serve   
public function __construct(EntityManager $em, $path, SecurityContext $context, $acl)
 {
     $this->em = $em;
     $this->projectsDirectory = $path;
     $this->context = $context;
     $token = $context->getToken();
     if (isset($token)) {
         $this->user = $token->getUser();
     }
     $this->acl = $acl;
 }

作者:ymarille    项目:sknif   
public function onFilterController(FilterControllerEvent $event)
 {
     list($object, $method) = $event->getController();
     // the controller could be a proxy
     $className = ClassUtils::getClass($object);
     $reflectionClass = new \ReflectionClass($className);
     $reflectionMethod = $reflectionClass->getMethod($method);
     $allControllerAnnotations = $this->annotationReader->getClassAnnotations($reflectionClass);
     $allMethodAnnotations = $this->annotationReader->getMethodAnnotations($reflectionMethod);
     $guardAnnotationsFilter = function ($annotation) {
         return $annotation instanceof Guard;
     };
     $controllerGuardAnnotations = array_filter($allControllerAnnotations, $guardAnnotationsFilter);
     $methodGuardAnnotations = array_filter($allMethodAnnotations, $guardAnnotationsFilter);
     $guardAnnotations = array_merge($controllerGuardAnnotations, $methodGuardAnnotations);
     $permissions = [];
     foreach ($guardAnnotations as $guardAnnotation) {
         $value = $guardAnnotation->value;
         if (!is_array($value)) {
             $value = [$value];
         }
         $permissions = array_merge($value, $permissions);
     }
     $permissions = array_unique($permissions);
     if (!empty($permissions) && !$this->security->isGranted($permissions)) {
         $e = new PermissionRequiredException();
         $e->setRequiredPermissions($permissions)->setCurrentPermissions($this->security->getToken()->getUser()->getPermissions());
         throw $e;
     }
 }

作者:sopine    项目:timeline-bundl   
/**
  * Listener for comments' votes persistence to avoid voting for own comments
  * and multiple voting for comments
  *
  * @param VotePersistEvent $event
  * @return void
  */
 public function avoidIncorrectVoting(VotePersistEvent $event)
 {
     try {
         if (!$this->context->isGranted(AuthenticatedVoter::IS_AUTHENTICATED_REMEMBERED)) {
             throw new \Exception('Avoid voting if user is not authenticated');
         }
         /** @var $vote SignedVoteInterface */
         $vote = $event->getVote();
         /** @var $user User */
         $user = $this->context->getToken()->getUser();
         if ($vote->getVoter() !== $user) {
             throw new \Exception('Attempt to vote for different user');
         }
         if ($vote->getComment()->getAuthor() === $user) {
             throw new \Exception('Attempt to vote for own comment');
         }
         $existingVote = $this->voteManager->findVoteBy(array('comment' => $vote->getComment(), 'voter' => $user));
         if ($existingVote) {
             throw new \Exception('Attempt to vote multiple times for same comment');
         }
     } catch (\Exception $e) {
         $event->abortPersistence();
         $event->stopPropagation();
     }
 }

作者:sasede    项目:alluc   
/**
  * 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->securityContext->getToken()) {
         $user = $this->securityContext->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();
         }
     }
 }

作者:glavwe    项目:GlavwebContentBlockBundl   
/**
  * @param string $blockName
  * @param array  $options
  * @param string $default
  * @return string
  */
 public function contentBlock($blockName, $options = array(), $default = null)
 {
     $em = $this->doctrine->getManager();
     $repository = $em->getRepository('GlavwebContentBlockBundle:ContentBlock');
     $contentBlock = $repository->findOneByName($blockName);
     $tag = isset($options['tag']) ? $options['tag'] : 'div';
     $attr = isset($options['attr']) ? $options['attr'] : array();
     if (isset($options['class'])) {
         $attr['class'] = $options['class'];
     }
     if (isset($options['href'])) {
         $attr['href'] = $options['href'];
     }
     if (!$contentBlock) {
         $contentBlock = new ContentBlock();
         $contentBlock->setName($blockName);
         $contentBlock->setBody($default ? $default : $blockName);
         $em->persist($contentBlock);
         $em->flush();
     }
     $contentEditable = '';
     $dataBlockName = '';
     $isEditable = $this->request && $this->request->get('contenteditable') && $this->securityContext->isGranted('ROLE_ADMIN');
     if ($isEditable) {
         $contentEditable = ' contenteditable="true"';
         $dataBlockName = ' data-block-name="' . $blockName . '"';
         $attr['class'] = isset($attr['class']) ? $attr['class'] . ' js-content-block' : 'js-content-block';
     }
     $attrParts = array();
     foreach ($attr as $attrName => $value) {
         $attrParts[] = sprintf('%s="%s"', $attrName, $value);
     }
     return '<' . $tag . ' ' . implode(' ', $attrParts) . ' ' . $contentEditable . $dataBlockName . '>' . $contentBlock->getBody() . '</' . $tag . '>';
 }

作者:holtchesle    项目:Zeeg   
public function onKernelRequest(GetResponseEvent $event)
 {
     if ($this->kernel->getEnvironment() != "dev") {
         if (preg_match("/\\/api\\//", $event->getRequest()->getUri())) {
             $requestUri = $event->getRequest()->getUri();
             $requestMethod = $event->getRequest()->getMethod();
             if ($requestMethod !== "GET") {
                 $token = $this->context->getToken();
                 if (isset($token)) {
                     $user = $token->getUser();
                     if (!isset($user) || "anon." === $user) {
                         if (!$event->getRequest()->query->has('api_key')) {
                             $event->setResponse(new Response(json_encode(array("code" => 401, "message" => "The request requires user authentication")), 401));
                         }
                     }
                 } else {
                     $event->setResponse(new Response(json_encode(array("code" => 401, "message" => "The request requires user authentication")), 401));
                 }
             }
         }
     }
     $request = $event->getRequest();
     if (!count($request->request->all()) && in_array($request->getMethod(), array('POST', 'PUT', 'PATCH', 'DELETE'))) {
         $contentType = $request->headers->get('Content-Type');
         $format = null === $contentType ? $request->getRequestFormat() : $request->getFormat($contentType);
         if (!$this->decoderProvider->supports($format)) {
             return;
         }
         $decoder = $this->decoderProvider->getDecoder($format);
         $data = $decoder->decode($request->getContent(), $format);
         if (is_array($data)) {
             $request->request = new ParameterBag($data);
         }
     }
 }

作者:mithilpatel0    项目:caci   
/**
  * Do the magic.
  *
  * @param InteractiveLoginEvent $event
  */
 public function onSecurityInteractiveLogin(InteractiveLoginEvent $event)
 {
     if ($this->securityContext->isGranted('IS_AUTHENTICATED_FULLY')) {
         // user has just logged in
     }
     if ($this->securityContext->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
         // user has logged in using remember_me cookie
     }
     // do some other magic here
     $session = $event->getRequest()->getSession();
     $referrer = $session->get('referrer');
     if (empty($referrer)) {
         $referrer = $event->getRequest()->getUri();
     }
     $user = $event->getAuthenticationToken()->getUser();
     $log = new Log();
     $log->setIdUsuario($user);
     $log->setDtAcao(new \DateTime());
     $log->setNmTabela('acesso');
     $log->setCsAcao('ACE');
     $log->setTeIpOrigem($event->getRequest()->getClientIp());
     $log->setNmScript($referrer);
     // Registra login
     $this->em->persist($log);
     $this->em->flush();
     // TODO: Redireciona para útima página visitada
 }

作者:webburz    项目:sylius-wishlist-bundl   
/**
  * @return CustomerInterface null
  */
 protected function getCustomer()
 {
     $customer = null;
     if ($user = $this->securityContext->getToken()->getUser()) {
         $customer = $user->getCustomer();
     }
     return $customer;
 }

作者:cobas    项目:cobas   
/**
  * Return current user's entity or null if not logged in
  *
  * @return null|App/UserBundle/Entity/User
  */
 public function getCurrentUser()
 {
     $user = $this->security->getToken()->getUser();
     if ($user === 'anon.') {
         return null;
     }
     return $user;
 }

作者:binse    项目:hookah.de   
public function buildForm(FormBuilderInterface $builder, array $options)
 {
     $user = $this->securityContext->getToken()->getUser();
     if ($user === 'anon.') {
         $user = false;
     }
     $builder->add('clientFirstName', null, array('attr' => array('placeholder' => 'Иван', 'class' => 'input_block'), 'label' => 'Имя', 'data' => $user ? $user->getFirstname() : ''))->add('clientLastName', null, array('attr' => array('placeholder' => 'Иванов', 'class' => 'input_block'), 'label' => 'Фамилия', 'data' => $user ? $user->getLastname() : ''))->add('telephone', null, array('attr' => array('placeholder' => '+7 910 001 10 10', 'class' => 'input_block'), 'label' => 'Телефон', 'data' => $user ? $user->getPhone() : ''))->add('email', EmailType::class, array('attr' => array('placeholder' => 'mail@mail.ru', 'class' => 'input_block'), 'label' => 'E-mail', 'data' => $user ? $user->getEmail() : ''))->add('address', new AddressOrderType(), array('label' => false, 'required' => false, 'data_class' => 'ShopBundle\\Entity\\AddressOrder'))->add('wishes', null, array('label' => 'Ваши пожелания'))->add('deliveryType', 'hidden', array('data' => DeliveryType::PICKUP))->add('products', 'hidden', array('data' => $this->session->get('ids')))->add('summ', 'hidden', array('data' => $this->session->get('basketSumm')))->add('bonus', 'hidden', array('data' => 0));
 }

作者:blab201    项目:se   
/**
  * @param FormBuilderInterface $builder
  * @param array $options
  */
 public function buildForm(FormBuilderInterface $builder, array $options)
 {
     $user = $this->securityContext->getToken()->getUser();
     $builder->add('srcCard', 'entity', array('label' => 'account.main.card.issuing.loyalty', 'required' => false, 'class' => 'SehBundle:Customer\\AccentCard', 'property' => 'number', 'empty_value' => false, 'multiple' => false, 'expanded' => false, 'query_builder' => function (EntityRepository $er) use($user) {
         return $er->createQueryBuilder('u')->where('u.customer = :user')->andWhere('u.status = :active')->setParameters(array('user' => $user, 'active' => AccentCard::ACTIF));
     }))->add('destCard', 'entity', array('label' => 'account.main.receiving.loyalty.card', 'required' => false, 'class' => 'SehBundle:Customer\\AccentCard', 'property' => 'number', 'empty_value' => false, 'multiple' => false, 'expanded' => false, 'query_builder' => function (EntityRepository $er) use($user) {
         return $er->createQueryBuilder('u')->where('u.customer = :user')->andWhere('u.status = :active')->setParameters(array('user' => $user, 'active' => AccentCard::ACTIF));
     }))->add('nbPoints', 'text', array('label' => 'account.main.point.transferred', 'required' => false));
 }


问题


面经


文章

微信
公众号

扫码关注公众号