当前位置: 首页>>代码示例>>PHP>>正文


PHP Core\SecurityContextInterface类代码示例

本文整理汇总了PHP中Symfony\Component\Security\Core\SecurityContextInterface的典型用法代码示例。如果您正苦于以下问题:PHP SecurityContextInterface类的具体用法?PHP SecurityContextInterface怎么用?PHP SecurityContextInterface使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了SecurityContextInterface类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。

示例1: setUp

 /**
  * Sets up the fixture, for example, opens a network connection.
  * This method is called before a test is executed.
  */
 protected function setUp()
 {
     $this->em = $this->getMockBuilder('Doctrine\\ORM\\EntityManager')->disableOriginalConstructor()->getMock();
     /* @var $conn Connection */
     $conn = $this->getMockBuilder('Doctrine\\DBAL\\Connection')->disableOriginalConstructor()->getMock();
     $conn->expects($this->any())->method('getDatabase')->will($this->returnValue('myDatabase'));
     /* @var $platform AbstractPlatform */
     $platform = $this->getMockForAbstractClass('Doctrine\\DBAL\\Platforms\\AbstractPlatform');
     $conn->expects($this->any())->method('getDatabasePlatform')->will($this->returnValue($platform));
     /* @var $stmt Statement */
     $stmt = $this->getMockForAbstractClass('Kunstmaan\\AdminBundle\\Tests\\Mocks\\StatementMock');
     $conn->expects($this->any())->method('executeQuery')->will($this->returnValue($stmt));
     $this->em->expects($this->any())->method('getConnection')->will($this->returnValue($conn));
     /* @var $conf Configuration */
     $conf = $this->getMockBuilder('Doctrine\\ORM\\Configuration')->disableOriginalConstructor()->getMock();
     /* @var $strat QuoteStrategy */
     $strat = $this->getMockBuilder('Doctrine\\ORM\\Mapping\\QuoteStrategy')->disableOriginalConstructor()->getMock();
     $strat->expects($this->any())->method('getTableName')->will($this->returnValue('rootTable'));
     $conf->expects($this->any())->method('getQuoteStrategy')->will($this->returnValue($strat));
     $conf->expects($this->any())->method('getDefaultQueryHints')->willReturn(array());
     $conf->expects($this->any())->method('isSecondLevelCacheEnabled')->willReturn(false);
     $this->em->expects($this->any())->method('getConfiguration')->will($this->returnValue($conf));
     /* @var $meta ClassMetadata */
     $meta = $this->getMockBuilder('Doctrine\\ORM\\Mapping\\ClassMetadata')->disableOriginalConstructor()->getMock();
     $this->em->expects($this->any())->method('getClassMetadata')->will($this->returnValue($meta));
     $this->sc = $this->getMockBuilder('Symfony\\Component\\Security\\Core\\SecurityContextInterface')->getMock();
     $this->token = $this->getMockBuilder('Symfony\\Component\\Security\\Core\\Authentication\\Token\\TokenInterface')->getMock();
     $this->sc->expects($this->any())->method('getToken')->will($this->returnValue($this->token));
     $this->rh = $this->getMockBuilder('Symfony\\Component\\Security\\Core\\Role\\RoleHierarchyInterface')->getMock();
     $this->object = new AclHelper($this->em, $this->sc, $this->rh);
 }
开发者ID:axelvnk,项目名称:KunstmaanBundlesCMS,代码行数:35,代码来源:AclHelperTest.php

示例2: login

 /**
  * {@inheritDoc}
  */
 public function login(UserInterface $user, $firewallName = 'main')
 {
     $this->userChecker->checkPreAuth($user);
     $token = new UsernamePasswordToken($user, null, $firewallName, $user->getRoles());
     $this->securityContext->setToken($token);
     $this->eventDispatcher->dispatch(UserEvents::SECURITY_IMPLICIT_LOGIN, new UserEvent($user));
 }
开发者ID:Strontium-90,项目名称:Sylius,代码行数:10,代码来源:UserLogin.php

示例3: previewContentAction

    public function previewContentAction( $contentId, $versionNo, $language, $siteAccessName = null )
    {
        try
        {
            $content = $this->contentService->loadContent( $contentId, array( $language ), $versionNo );
            $location = $this->previewHelper->getPreviewLocation( $contentId );
        }
        catch ( UnauthorizedException $e )
        {
            throw new AccessDeniedException();
        }

        if ( !$this->securityContext->isGranted( new AuthorizationAttribute( 'content', 'versionread', array( 'valueObject' => $content ) ) ) )
        {
            throw new AccessDeniedException();
        }

        $siteAccess = $this->previewHelper->getOriginalSiteAccess();
        // Only switch if $siteAccessName is set and different from original
        if ( $siteAccessName !== null && $siteAccessName !== $siteAccess->name )
        {
            $siteAccess = $this->previewHelper->changeConfigScope( $siteAccessName );
        }

        $response = $this->kernel->handle(
            $this->getForwardRequest( $location, $content, $siteAccess ),
            HttpKernelInterface::SUB_REQUEST
        );
        $response->headers->remove( 'cache-control' );
        $response->headers->remove( 'expires' );

        $this->previewHelper->restoreConfigScope();

        return $response;
    }
开发者ID:ataxel,项目名称:tp,代码行数:35,代码来源:PreviewController.php

示例4: isVisible

 public function isVisible()
 {
     if ($this->securityContext === null) {
         return true;
     }
     return !$this->securityContext->getToken();
 }
开发者ID:mikegibson,项目名称:sentient,代码行数:7,代码来源:LoginAction.php

示例5: onKernelRequest

 /**
  * Refresh organization context in token
  *
  * @param GetResponseEvent $event
  */
 public function onKernelRequest(GetResponseEvent $event)
 {
     $token = $this->context->getToken();
     if ($token instanceof OrganizationContextTokenInterface) {
         $token->setOrganizationContext($this->manager->getOrganizationById($token->getOrganizationContext()->getId()));
     }
 }
开发者ID:xamin123,项目名称:platform,代码行数:12,代码来源:ContextListener.php

示例6: handle

 /**
  * This interface must be implemented by firewall listeners.
  *
  * @param GetResponseEvent $event
  */
 public function handle(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     if (!$this->keyExtractor->hasKey($request)) {
         $response = new Response();
         $response->setStatusCode(401);
         $event->setResponse($response);
         return;
     }
     $apiKey = $this->keyExtractor->extractKey($request);
     $token = new ApiKeyUserToken();
     $token->setApiKey($apiKey);
     try {
         $authToken = $this->authenticationManager->authenticate($token);
         $this->securityContext->setToken($authToken);
         return;
     } catch (AuthenticationException $failed) {
         $token = $this->securityContext->getToken();
         if ($token instanceof ApiKeyUserToken && $token->getCredentials() == $apiKey) {
             $this->securityContext->setToken(null);
         }
         $message = $failed->getMessage();
     }
     $response = new Response();
     $response->setContent($message);
     $response->setStatusCode(403);
     $event->setResponse($response);
 }
开发者ID:tuandv2611,项目名称:api-key-bundle,代码行数:33,代码来源:ApiKeyListener.php

示例7: onAuthenticationSuccess

 /**
  * Methode qui est déclenché après l'événement InteractiveLogin
  * qui est  l'action de login dans la sécurité
  * @param InteractiveLoginEvent $event
  */
 public function onAuthenticationSuccess(InteractiveLoginEvent $event)
 {
     $now = new \DateTime('now');
     // récupére l'utilisateur  courant connecté
     $user = $this->securityContext->getToken()->getUser();
     //recupere tous les produits de l'utilisateur via le repository ProductRepository
     // et via getProductsQuantityIsLower() qui on une quantité < 5
     $products = $this->em->getRepository('StoreBackendBundle:Product')->getProductsQuantityIsLower($user);
     //pour chaque produit
     foreach ($products as $product) {
         // si la quantité du produit est égal à 1
         if ($product->getQuantity() == 1) {
             $this->notification->notify($product->getId(), 'Attention, votre produit ' . $product->getTitle() . '  a une seule quantité', 'product', 'danger');
         } else {
             $this->notification->notify($product->getId(), 'Attention, votre produit ' . $product->getTitle() . '  a quantité bientot épuisé', 'product', 'warning');
         }
     }
     // declencher une notification dans mes produits
     $date = $user->getDateAuth();
     $oldyear = new \DateTime('-2 month');
     $route = 'store_backend_index';
     // Long time to control use account
     if ($date < $oldyear || !$date) {
         $this->session->set('first', true);
         $route = 'store_backend_jeweler_myaccount';
     }
     // met à jour la date de connexion de l'utilisateur
     $user->setDateAuth($now);
     //enregistre mon utilisateur avec sa date modifié
     $this->em->persist($user);
     $this->em->flush();
     return new RedirectResponse($this->router->generate($route));
 }
开发者ID:unpetitlu,项目名称:store,代码行数:38,代码来源:AuthentificationListener.php

示例8: handle

 public function handle(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     //find out if the current request contains any information by which the user might be authenticated
     if (!$request->headers->has('X-WSSE')) {
         return;
     }
     $ae_message = null;
     $this->wsseHeader = $request->headers->get('X-WSSE');
     $wsseHeaderInfo = $this->parseHeader();
     if ($wsseHeaderInfo !== false) {
         $token = new Token($wsseHeaderInfo['Username'], $wsseHeaderInfo['PasswordDigest'], $this->providerKey);
         $token->setAttribute('nonce', $wsseHeaderInfo['Nonce']);
         $token->setAttribute('created', $wsseHeaderInfo['Created']);
         try {
             $returnValue = $this->authenticationManager->authenticate($token);
             if ($returnValue instanceof TokenInterface) {
                 return $this->tokenStorage->setToken($returnValue);
             } else {
                 if ($returnValue instanceof Response) {
                     return $event->setResponse($returnValue);
                 }
             }
         } catch (AuthenticationException $ae) {
             $event->setResponse($this->authenticationEntryPoint->start($request, $ae));
         }
     }
 }
开发者ID:MathiasDewelde,项目名称:EscapeWSSEAuthenticationBundle,代码行数:28,代码来源:Listener.php

示例9: handle

 /**
  * @param GetResponseEvent $event
  */
 public function handle(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     if (!$request->headers->has('cookie')) {
         return;
     }
     if (strstr($request->headers->get('cookie'), 'SimpleSAMLAuthToken') === false) {
         return;
     }
     if (!$request->query->has('csrf-token')) {
         $this->logger->notice('Ssp Firewall: Auth Token cookie but no CSRF Token');
         return;
     }
     $csrfToken = $request->query->getAlnum('csrf-token');
     if (!$this->csrfProvider->isCsrfTokenValid('api', $csrfToken)) {
         $this->logger->notice('Ssp Firewall: Invalid CSRF token for api use: ' . $csrfToken);
         return;
     }
     try {
         $authToken = $this->authenticationManager->authenticate(new SspToken());
         $this->securityContext->setToken($authToken);
     } catch (AuthenticationException $failed) {
         $this->logger->warning('Ssp Firewall: failed:' . $failed->getMessage());
         $token = $this->securityContext->getToken();
         if ($token instanceof SspToken) {
             $this->securityContext->setToken(null);
         }
         return;
     }
 }
开发者ID:baszoetekouw,项目名称:janus,代码行数:33,代码来源:SspListener.php

示例10: testBuild

 public function testBuild()
 {
     $organization = new Organization();
     $type = 'history';
     $userId = 1;
     $user = $this->getMockBuilder('stdClass')->setMethods(array('getId'))->getMock();
     $user->expects($this->once())->method('getId')->will($this->returnValue($userId));
     $token = $this->getMockBuilder('Oro\\Bundle\\SecurityBundle\\Authentication\\Token\\UsernamePasswordOrganizationToken')->disableOriginalConstructor()->getMock();
     $token->expects($this->once())->method('getUser')->will($this->returnValue($user));
     $token->expects($this->once())->method('getOrganizationContext')->will($this->returnValue($organization));
     $this->securityContext->expects($this->atLeastOnce())->method('getToken')->will($this->returnValue($token));
     $item = $this->getMock('Oro\\Bundle\\NavigationBundle\\Entity\\NavigationItemInterface');
     $this->factory->expects($this->once())->method('createItem')->with($type, array())->will($this->returnValue($item));
     $repository = $this->getMockBuilder('Oro\\Bundle\\NavigationBundle\\Entity\\Repository\\HistoryItemRepository')->disableOriginalConstructor()->getMock();
     $items = array(array('id' => 1, 'title' => 'test1', 'url' => '/'), array('id' => 2, 'title' => 'test2', 'url' => '/home'));
     $repository->expects($this->once())->method('getNavigationItems')->with($userId, $organization, $type)->will($this->returnValue($items));
     $this->em->expects($this->once())->method('getRepository')->with(get_class($item))->will($this->returnValue($repository));
     $menu = $this->getMockBuilder('Knp\\Menu\\MenuItem')->disableOriginalConstructor()->getMock();
     $childMock = $this->getMock('Knp\\Menu\\ItemInterface');
     $childMock2 = clone $childMock;
     $children = array($childMock, $childMock2);
     $matcher = $this->getMock('\\Knp\\Menu\\Matcher\\Matcher');
     $matcher->expects($this->once())->method('isCurrent')->will($this->returnValue(true));
     $this->builder->setMatcher($matcher);
     $menu->expects($this->exactly(2))->method('addChild');
     $menu->expects($this->once())->method('setExtra')->with('type', $type);
     $menu->expects($this->once())->method('getChildren')->will($this->returnValue($children));
     $menu->expects($this->once())->method('removeChild');
     $n = rand(1, 10);
     $configMock = $this->getMockBuilder('Oro\\Bundle\\ConfigBundle\\Config\\ConfigManager')->disableOriginalConstructor()->getMock();
     $configMock->expects($this->once())->method('get')->with($this->equalTo('oro_navigation.maxItems'))->will($this->returnValue($n));
     $this->manipulator->expects($this->once())->method('slice')->with($menu, 0, $n);
     $this->builder->setOptions($configMock);
     $this->builder->build($menu, array(), $type);
 }
开发者ID:Maksold,项目名称:platform,代码行数:35,代码来源:NavigationHistoryBuilderTest.php

示例11: getUser

 /**
  * @return \Symfony\Component\Security\Core\User\UserInterface
  */
 private function getUser()
 {
     if (is_null($this->user)) {
         $this->user = $this->securityContext->getToken()->getUser();
     }
     return $this->user;
 }
开发者ID:hyrmedia,项目名称:KunstmaanBundlesCMS,代码行数:10,代码来源:LogPageEventsSubscriber.php

示例12: isGranted

 /**
  * @param string $role
  *
  * @return bool
  */
 protected function isGranted($role)
 {
     if (!$this->securityContext) {
         $this->securityContext = $this->getSecurityContext();
     }
     return $this->securityContext->isGranted($role);
 }
开发者ID:peterAK,项目名称:pgs-sts,代码行数:12,代码来源:BaseController.php

示例13: logInUser

 public final function logInUser($firewallName, UserInterface $user, Response $response = null)
 {
     $this->userChecker->checkPostAuth($user);
     $token = $this->createToken($firewallName, $user);
     $request = null;
     if ($this->container->has('request_stack')) {
         $request = $this->container->get('request_stack')->getCurrentRequest();
     } elseif (method_exists($this->container, 'isScopeActive') && $this->container->isScopeActive('request')) {
         // BC for SF <2.4
         $request = $this->container->get('request');
     }
     if (null !== $request) {
         $this->sessionStrategy->onAuthentication($request, $token);
         if (null !== $response) {
             $rememberMeServices = null;
             if ($this->container->has('security.authentication.rememberme.services.persistent.' . $firewallName)) {
                 $rememberMeServices = $this->container->get('security.authentication.rememberme.services.persistent.' . $firewallName);
             } elseif ($this->container->has('security.authentication.rememberme.services.simplehash.' . $firewallName)) {
                 $rememberMeServices = $this->container->get('security.authentication.rememberme.services.simplehash.' . $firewallName);
             }
             if ($rememberMeServices instanceof RememberMeServicesInterface) {
                 $rememberMeServices->loginSuccess($request, $response, $token);
             }
         }
     }
     $this->tokenStorage->setToken($token);
 }
开发者ID:acorbel,项目名称:FOSUserBundle,代码行数:27,代码来源:LoginManager.php

示例14: onKernelRequest

    /**
     * If user is logged-in in legacy_mode (e.g. legacy admin interface),
     * will inject currently logged-in user in the repository.
     *
     * @param GetResponseEvent $event
     */
    public function onKernelRequest( GetResponseEvent $event )
    {
        /** @var \eZ\Publish\Core\MVC\ConfigResolverInterface $configResolver */
        $request = $event->getRequest();
        $session = $request->getSession();
        if (
            $event->getRequestType() !== HttpKernelInterface::MASTER_REQUEST
            || !$this->configResolver->getParameter( 'legacy_mode' )
            || !( $session->isStarted() && $session->has( 'eZUserLoggedInID' ) )
        )
        {
            return;
        }

        try
        {
            $apiUser = $this->repository->getUserService()->loadUser( $session->get( 'eZUserLoggedInID' ) );
            $this->repository->setCurrentUser( $apiUser );

            $token = $this->securityContext->getToken();
            if ( $token instanceof TokenInterface )
            {
                $token->setUser( new User( $apiUser ) );
                $token->setAuthenticated( true );
            }
        }
        catch ( NotFoundException $e )
        {
            // Invalid user ID, the user may have been removed => invalidate the token and the session.
            $this->securityContext->setToken( null );
            $session->invalidate();
        }
    }
开发者ID:ezsystemstraining,项目名称:ez54training,代码行数:39,代码来源:RequestListener.php

示例15: includeJSFilesAction

 /**
  * Render js inclusion for create.js and dependencies and bootstrap code.
  *
  * THe hallo editor is bundled with create.js and available automatically.
  * To use aloha, you need to download the zip, as explained in step 8 of
  * the README.
  *
  * @param string $editor the name of the editor to load, currently hallo and aloha are supported
  */
 public function includeJSFilesAction($editor = 'hallo')
 {
     if ($this->securityContext && false === $this->securityContext->isGranted($this->requiredRole)) {
         return new Response('');
     }
     // We could inject a list of names to template mapping for this
     // to allow adding other editors without changing this bundle
     $view = new View();
     switch ($editor) {
         case 'hallo':
             if ($this->coffee) {
                 $view->setTemplate('SymfonyCmfCreateBundle::includecoffeefiles-hallo.html.twig');
             } else {
                 $view->setTemplate('SymfonyCmfCreateBundle::includejsfiles-hallo.html.twig');
             }
             break;
         case 'aloha':
             $view->setTemplate('SymfonyCmfCreateBundle::includejsfiles-aloha.html.twig');
             break;
         default:
             throw new \InvalidArgumentException("Unknown editor '{$editor}' requested");
     }
     $view->setData(array('cmfCreateStanbolUrl' => $this->stanbolUrl, 'cmfCreateImageUploadEnabled' => (bool) $this->imageClass));
     return $this->viewHandler->handle($view);
 }
开发者ID:notsentient,项目名称:CreateBundle,代码行数:34,代码来源:JsloaderController.php


注:本文中的Symfony\Component\Security\Core\SecurityContextInterface类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。