예제 #1
0
 /**
  * {@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));
 }
예제 #2
0
    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;
    }
예제 #3
0
 public function isVisible()
 {
     if ($this->securityContext === null) {
         return true;
     }
     return !$this->securityContext->getToken();
 }
예제 #4
0
 /**
  * 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()));
     }
 }
예제 #5
0
 /**
  * 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);
 }
예제 #6
0
 /**
  * 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));
 }
예제 #7
0
 /**
  * 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);
 }
 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));
         }
     }
 }
예제 #9
0
 /**
  * @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;
     }
 }
 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);
 }
 /**
  * @return \Symfony\Component\Security\Core\User\UserInterface
  */
 private function getUser()
 {
     if (is_null($this->user)) {
         $this->user = $this->securityContext->getToken()->getUser();
     }
     return $this->user;
 }
예제 #12
0
 /**
  * @param string $role
  *
  * @return bool
  */
 protected function isGranted($role)
 {
     if (!$this->securityContext) {
         $this->securityContext = $this->getSecurityContext();
     }
     return $this->securityContext->isGranted($role);
 }
예제 #13
0
 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);
 }
    /**
     * 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();
        }
    }
 /**
  * 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);
 }
예제 #16
0
 public function onKernelController(FilterControllerEvent $event)
 {
     if (!is_array($controller = $event->getController())) {
         return;
     }
     $className = class_exists('Doctrine\\Common\\Util\\ClassUtils') ? ClassUtils::getClass($controller[0]) : get_class($controller[0]);
     $object = new \ReflectionClass($className);
     $method = $object->getMethod($controller[1]);
     /**
      * @var UserType\UserTypeInterface[] $requiredUserTypes
      */
     $requiredUserTypes = array_merge($this->getConfigurations($this->reader->getClassAnnotations($object)), $this->getConfigurations($this->reader->getMethodAnnotations($method)));
     if (count($requiredUserTypes) === 0) {
         return;
     }
     $token = $this->securityContext->getToken();
     if (null === $token) {
         throw new AccessDeniedException(sprintf("You are not authenticated, a known user type is required for access."));
     }
     $user = $token->getUser();
     foreach ($requiredUserTypes as $userType) {
         $userClass = $userType->getUserClass();
         if (!interface_exists($userClass) && !class_exists($userClass)) {
             throw new RuntimeException(sprintf("The user type class '%s' does not exist", $userClass));
         }
         if (!$user instanceof $userClass) {
             throw new AccessDeniedException(sprintf("You do not have the required user type. A user type of '%s' is required.", $userClass));
         }
         unset($userType, $userClass);
     }
 }
예제 #17
0
 /**
  * {@inheritdoc}
  */
 public function handle(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     if ($this->securityContext->getToken() !== null) {
         return;
     }
     if ($request->getRequestUri() == '/app_dev.php/api/login' || $request->getRequestUri() == '/api/login') {
         return;
     }
     //Try to reach token from HTTP headers
     if ($request->headers->has('X-Auth-Token')) {
         $tokenId = $request->headers->get('X-Auth-Token');
     } else {
         $tokenId = $request->get('token');
     }
     //by token
     if (isset($tokenId)) {
         $user = $this->userProvider->findUserByToken($tokenId);
         if (!$user) {
             throw new BadCredentialsException();
         }
         try {
             $token = new ApiToken([], $this->providerId, $this->key);
             $token->setUser($user);
             $authenticatedToken = $this->authenticationManager->authenticate($token);
             $this->securityContext->setToken($authenticatedToken);
         } catch (AuthenticationException $e) {
             //log something
         }
     }
 }
예제 #18
0
 /**
  * Process form
  *
  * @param AccountUser $accountUser
  * @return bool True on successful processing, false otherwise
  */
 public function process(AccountUser $accountUser)
 {
     if (in_array($this->request->getMethod(), ['POST', 'PUT'], true)) {
         $this->form->submit($this->request);
         if ($this->form->isValid()) {
             if (!$accountUser->getId()) {
                 if ($this->form->get('passwordGenerate')->getData()) {
                     $generatedPassword = $this->userManager->generatePassword(10);
                     $accountUser->setPlainPassword($generatedPassword);
                 }
                 if ($this->form->get('sendEmail')->getData()) {
                     $this->userManager->sendWelcomeEmail($accountUser);
                 }
             }
             $token = $this->securityContext->getToken();
             if ($token instanceof OrganizationContextTokenInterface) {
                 $organization = $token->getOrganizationContext();
                 $accountUser->setOrganization($organization)->addOrganization($organization);
             }
             $this->userManager->updateUser($accountUser);
             return true;
         }
     }
     return false;
 }
예제 #19
0
 /**
  * Checking request and response and decide whether we need a redirect
  *
  * @param FilterResponseEvent $event
  */
 public function onResponse(FilterResponseEvent $event)
 {
     $request = $event->getRequest();
     $response = $event->getResponse();
     if ($request->get(self::HASH_NAVIGATION_HEADER) || $request->headers->get(self::HASH_NAVIGATION_HEADER)) {
         $location = '';
         $isFullRedirect = false;
         if ($response->isRedirect()) {
             $location = $response->headers->get('location');
             if ($request->attributes->get('_fullRedirect') || !is_object($this->security->getToken())) {
                 $isFullRedirect = true;
             }
         }
         if ($response->isNotFound() || $response->getStatusCode() == 503 && !$this->isDebug) {
             $location = $request->getUri();
             $isFullRedirect = true;
         }
         if ($location) {
             $response = $this->templating->renderResponse('OroNavigationBundle:HashNav:redirect.html.twig', array('full_redirect' => $isFullRedirect, 'location' => $location));
         }
         // disable cache for ajax navigation pages and change content type to json
         $response->headers->set('Content-Type', 'application/json');
         $response->headers->addCacheControlDirective('no-cache', true);
         $response->headers->addCacheControlDirective('max-age', 0);
         $response->headers->addCacheControlDirective('must-revalidate', true);
         $response->headers->addCacheControlDirective('no-store', true);
         $event->setResponse($response);
     }
 }
 /**
  * @inheritdoc
  */
 public function consume(TokenInterface $token, Request $request)
 {
     if (!$this->security->isGranted(AbstractTokenVoter::CONSUME, $token)) {
         throw new AccessDeniedException();
     }
     return parent::consume($token, $request);
 }
 /**
  * @param GetResponseEvent $event
  */
 public function onCoreRequest(GetResponseEvent $event)
 {
     if (HttpKernel::MASTER_REQUEST != $event->getRequestType()) {
         return;
     }
     $token = $this->securityContext->getToken();
     if (!$token) {
         return;
     }
     if (!$token instanceof UsernamePasswordToken) {
         return;
     }
     $key = $this->helper->getSessionKey($this->securityContext->getToken());
     $request = $event->getRequest();
     $session = $event->getRequest()->getSession();
     $user = $this->securityContext->getToken()->getUser();
     if (!$session->has($key)) {
         return;
     }
     if ($session->get($key) === true) {
         return;
     }
     $state = 'init';
     if ($request->getMethod() == 'POST') {
         if ($this->helper->checkCode($user, $request->get('_code')) == true) {
             $session->set($key, true);
             return;
         }
         $state = 'error';
     }
     $event->setResponse($this->templating->renderResponse('SonataUserBundle:Admin:Security/two_step_form.html.twig', array('state' => $state)));
 }
 /**
  * Handles the authentication for user.
  *
  * @param GetResponseEvent $event The response event.
  *
  * @throws AuthenticationException When the request is not authenticated.
  *
  * @return void
  */
 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)) {
         return;
     }
     $token = new WsseUserToken($this->providerKey);
     $token->setUser($matches[1]);
     $token->setDigest($matches[2]);
     $token->setNonce($matches[3]);
     $token->setCreated($matches[4]);
     try {
         $authToken = $this->authenticationManager->authenticate($token);
         $this->securityContext->setToken($authToken);
         return;
     } catch (AuthenticationException $failed) {
         $failedMessage = 'WSSE Login failed for ' . $token->getUsername() . '.  Because: ' . $failed->getMessage();
         $token = $this->securityContext->getToken();
         if ($token instanceof WsseUserToken && $this->providerKey === $token->getProviderKey()) {
             $this->securityContext->setToken(null);
         }
         // deny authentication with a '403 Forbidden' HTTP response
         $response = new Response();
         $response->setStatusCode(403);
         $event->setResponse($response);
         return;
     }
     // by default deny authorization
     $response = new Response();
     $response->setStatusCode(403);
     $event->setResponse($response);
 }
예제 #23
0
 /**
  * Get the customer.
  *
  * @throws \RuntimeException
  *
  * @return \Sonata\Component\Customer\CustomerInterface
  */
 public function get()
 {
     $customer = null;
     $user = null;
     if (true === $this->securityContext->isGranted('IS_AUTHENTICATED_FULLY')) {
         // user is authenticated
         $user = $this->securityContext->getToken()->getUser();
         if (!$user instanceof UserInterface) {
             throw new \RuntimeException('User must be an instance of FOS\\UserBundle\\Model\\UserInterface');
         }
         $customer = $this->customerManager->findOneBy(array('user' => $user->getId()));
     }
     if (!$customer) {
         $basket = $this->getBasket();
         if ($basket && $basket->getCustomer()) {
             $customer = $basket->getCustomer();
         }
     }
     if (!$customer) {
         $customer = $this->customerManager->create();
     }
     if (!$customer->getLocale()) {
         $customer->setLocale($this->locale);
     }
     if ($user && $customer) {
         $customer->setUser($user);
     }
     return $customer;
 }
 /**
  * Handles basic authentication.
  *
  * @param GetResponseEvent $event A GetResponseEvent instance
  */
 public function handle(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     if (false === ($username = $request->headers->get('PHP_AUTH_USER', false))) {
         return;
     }
     if (null !== ($token = $this->securityContext->getToken())) {
         if ($token instanceof OrganizationContextTokenInterface && $token->isAuthenticated() && $token->getUsername() === $username) {
             return;
         }
     }
     $this->logProcess($username);
     try {
         $organizationId = $request->headers->get('PHP_AUTH_ORGANIZATION');
         if ($organizationId) {
             $authToken = new UsernamePasswordOrganizationToken($username, $request->headers->get('PHP_AUTH_PW'), $this->providerKey, $this->manager->getOrganizationById($organizationId));
         } else {
             $authToken = new UsernamePasswordToken($username, $request->headers->get('PHP_AUTH_PW'), $this->providerKey);
         }
         $this->securityContext->setToken($this->authenticationManager->authenticate($authToken));
     } catch (AuthenticationException $failed) {
         $token = $this->securityContext->getToken();
         if ($token instanceof UsernamePasswordToken && $this->providerKey === $token->getProviderKey()) {
             $this->securityContext->setToken(null);
         }
         $this->logError($username, $failed->getMessage());
         if ($this->ignoreFailure) {
             return;
         }
         $event->setResponse($this->authenticationEntryPoint->start($request, $failed));
     }
 }
예제 #25
0
 /**
  * @return bool
  */
 private function isUserAuthenticated()
 {
     // IS_AUTHENTICATED_FULLY inherits from IS_AUTHENTICATED_REMEMBERED.
     // User can be either authenticated by providing credentials during current session
     // or by "remember me" if available.
     return $this->securityContext->isGranted('IS_AUTHENTICATED_REMEMBERED');
 }
 /**
  * Check if the node on the event is published, otherwise skip it.
  *
  * @param CreateMenuItemFromNodeEvent $event
  */
 public function onCreateMenuItemFromNode(CreateMenuItemFromNodeEvent $event)
 {
     $node = $event->getNode();
     if (!$this->publishWorkflowChecker->isGranted($this->publishWorkflowPermission, $node)) {
         $event->setSkipNode(true);
     }
 }
예제 #27
0
 /**
  * Gets customer based on currently logged user.
  *
  * @return CustomerInterface|null
  */
 public function getCustomer()
 {
     if ($this->securityContext->getToken() && $this->securityContext->isGranted('IS_AUTHENTICATED_REMEMBERED') && $this->securityContext->getToken()->getUser() instanceof UserInterface) {
         return $this->securityContext->getToken()->getUser()->getCustomer();
     }
     return null;
 }
 /**
  * @param string $attributes
  * @param $object
  *
  * @return bool
  */
 public function isGranted($attributes, $object)
 {
     if (!is_object($object) && !is_string($object)) {
         return false;
     }
     $objectIdentity = null;
     /** @var Owned $object */
     if (is_object($object)) {
         $objectIdentity = get_class($object);
         $user = $this->securityContext->getToken()->getUser();
         $objectOwner = $object->getOwner();
         if ($attributes == 'EDIT' || $attributes == 'DELETE' || $attributes == 'VIEW') {
             if ($objectOwner->isDiamanteUser()) {
                 $ownerId = $this->diamanteUserRepository->findUserByEmail($user->getUserName())->getId();
                 if ($ownerId != $objectOwner->getId()) {
                     return false;
                 }
             }
         }
     }
     if (is_string($object)) {
         $objectIdentity = $object;
     }
     if (array_key_exists($objectIdentity, $this->permissionsMap)) {
         if (in_array($attributes, $this->permissionsMap[$objectIdentity])) {
             return true;
         }
     }
     return false;
 }
예제 #29
0
 /**
  * @param FormInterface            $form
  * @param Request                  $request
  * @param RegistryInterface        $registry
  * @param SecurityContextInterface $security
  */
 public function __construct(FormInterface $form, Request $request, RegistryInterface $registry, SecurityContextInterface $security)
 {
     $this->form = $form;
     $this->request = $request;
     $this->manager = $registry->getManager();
     $this->organization = $security->getToken()->getOrganizationContext();
 }
    public function isGranted($route = "ibrows_simple_cms_content", $parameters=array()) {
        
        
    
        
   
        try {
            if (false === $this->securityContext->isGranted($this->globalRole)) {
                return false;
            }
        }  catch (AuthenticationCredentialsNotFoundException $e){
            return true;
        }
        if(isset($parameters['type']) && key_exists($parameters['type'], $this->securityMap)){
            $roles = $this->securityMap[$parameters['type']];             
            foreach($roles as $roletype => $role){              
                if(stripos($route, $roletype) !== false || $roletype == 'general') {                    
                    if(false === $this->securityContext->isGranted($role)){
                        return false;
                    }
                    
                }
            }            
        }
        

        
        
        return true;
        
    }