/** * Returns the current logged in user identity. * * @return TokenInterface|null */ public function getIdentity() { if (null == $this->tokenStorage) { return null; } return $this->tokenStorage->getToken(); }
public function onKernelController(FilterControllerEvent $event) { if (!is_array($controller = $event->getController())) { return; } $object = new \ReflectionObject($controller[0]); $method = $object->getMethod($controller[1]); $classConfigurations = $this->reader->getClassAnnotations($object); $methodConfigurations = $this->reader->getMethodAnnotations($method); foreach (array_merge($classConfigurations, $methodConfigurations) as $configuration) { if ($configuration instanceof OAuth2) { $token = $this->token_storage->getToken(); // If no access token is found by the firewall, then returns an authentication error if (!$token instanceof OAuth2Token) { $this->createAuthenticationException($event, 'OAuth2 authentication required'); return; } foreach ($this->getCheckers() as $checker) { $result = $checker->check($token, $configuration); if (null !== $result) { $this->createAccessDeniedException($event, $result); return; } } } } }
/** * AbstractJournalItemMailer constructor. * @param OjsMailer $ojsMailer * @param RegistryInterface $registry * @param TokenStorageInterface $tokenStorage * @param RouterInterface $router */ public function __construct(OjsMailer $ojsMailer, RegistryInterface $registry, TokenStorageInterface $tokenStorage, RouterInterface $router) { $this->ojsMailer = $ojsMailer; $this->em = $registry->getManager(); $this->user = $tokenStorage->getToken() ? $tokenStorage->getToken()->getUser() : null; $this->router = $router; }
/** * Set the username from injected security context * @param TokenStorageInterface $securityTokenStorage * @param AuditLogManager $auditLogManager */ public function __construct(TokenStorageInterface $securityTokenStorage, AuditLogManager $auditLogManager) { if (null !== $securityTokenStorage && null !== $securityTokenStorage->getToken()) { $this->user = $securityTokenStorage->getToken()->getUser(); } $this->manager = $auditLogManager; }
/** * @return \Symfony\Component\Security\Core\User\UserInterface */ private function getUser() { if (is_null($this->user)) { $this->user = $this->tokenStorage->getToken()->getUser(); } return $this->user; }
private function getUserFromTokenStorage() { if (($token = $this->tokenStorage->getToken()) !== null) { return $token->getUser(); } throw new \RuntimeException('I don\'t have a token'); }
public function __construct(ItemFactory $navigationItemFactory, TokenStorageInterface $tokenStorage, EntityManager $entityManager, TitleServiceInterface $titleService) { $this->navItemFactory = $navigationItemFactory; $this->user = !$tokenStorage->getToken() || is_string($tokenStorage->getToken()->getUser()) ? null : $tokenStorage->getToken()->getUser(); $this->em = $entityManager; $this->titleService = $titleService; }
/** * @see \Hostnet\Component\EntityBlamable\Provider\BlamableProviderInterface::getUpdatedBy() */ public function getUpdatedBy() { if (($token = $this->token_storage->getToken()) instanceof TokenInterface) { return $token->getUsername(); } return $this->username; }
/** * Validate that the submitted file is owned by the authenticated user * * @param string $value * @param Constraint $constraint */ public function validate($value, Constraint $constraint) { $fileHistory = $this->em->getRepository('JbFileUploaderBundle:FileHistory')->find($value); if (!$fileHistory) { return; } // No userid associated with file. Every one can use it. if (!$fileHistory->getUserId()) { return; } // No token. Violation as there is a user id associate with file. $token = $this->tokenStorage->getToken(); if (!$token) { return $this->createViolation($value, $constraint); } // No user. Violation as there is a user id associate with file. $user = $token->getUser(); if (!$user) { return $this->createViolation($value, $constraint); } if ($user->getId() !== $fileHistory->getUserId()) { return $this->createViolation($value, $constraint); } return; }
/** * @param FactoryInterface $factory * @param TokenStorageInterface $securityContext */ public function __construct(FactoryInterface $factory, TokenStorageInterface $securityContext) { $this->factory = $factory; if ($securityContext->getToken() && $securityContext->getToken()->getUser()) { $this->username = $securityContext->getToken()->getUser()->getUsername(); } }
/** * @param GetResponseEvent $event */ public function onCoreRequest(GetResponseEvent $event) { if (HttpKernel::MASTER_REQUEST != $event->getRequestType()) { return; } $token = $this->tokenStorage->getToken(); if (!$token) { return; } if (!$token instanceof UsernamePasswordToken) { return; } $key = $this->helper->getSessionKey($this->tokenStorage->getToken()); $request = $event->getRequest(); $session = $event->getRequest()->getSession(); $user = $this->tokenStorage->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))); }
/** * 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->tokenStorage->setToken($authToken); return; } catch (AuthenticationException $failed) { $token = $this->tokenStorage->getToken(); if ($token instanceof ApiKeyUserToken && $token->getCredentials() == $apiKey) { $this->tokenStorage->setToken(null); } $message = $failed->getMessage(); } $response = new Response(); $response->setContent($message); $response->setStatusCode(403); $event->setResponse($response); }
/** * @param FactoryInterface $factory * @param TokenStorageInterface $tokenStorage */ public function __construct(FactoryInterface $factory, TokenStorageInterface $tokenStorage) { $this->factory = $factory; if ($tokenStorage->getToken() && $tokenStorage->getToken()->getUser()) { $this->username = $tokenStorage->getToken()->getUser()->getUsername(); } }
/** * {@inheritdoc} */ public function configureOptions(OptionsResolver $resolver) { $token = $this->tokenStorage->getToken(); if ($token && $token->getUser() instanceof AccountUser) { $resolver->setDefault('grid_name', 'products-select-grid-frontend'); } }
/** * Returns the context for the given activity class and id * * @param string $class The FQCN of the activity entity * @param $id * * @return array */ public function getActivityContext($class, $id) { $currentUser = $this->securityTokenStorage->getToken()->getUser(); $userClass = ClassUtils::getClass($currentUser); $entity = $this->doctrineHelper->getEntity($class, $id); $result = []; if (!$entity || !$entity instanceof ActivityInterface) { return $result; } $targets = $entity->getActivityTargetEntities(); $entityProvider = $this->configManager->getProvider('entity'); foreach ($targets as $target) { $targetClass = ClassUtils::getClass($target); $targetId = $target->getId(); if ($userClass === $targetClass && $currentUser->getId() === $targetId) { continue; } $item = []; $config = $entityProvider->getConfig($targetClass); $safeClassName = $this->entityClassNameHelper->getUrlSafeClassName($targetClass); $item = $this->prepareItemTitle($item, $targetClass, $target, $targetId); $item['activityClassAlias'] = $this->entityAliasResolver->getPluralAlias($class); $item['entityId'] = $id; $item['targetId'] = $targetId; $item['targetClassName'] = $safeClassName; $item['icon'] = $config->get('icon'); $item['link'] = $this->getContextLink($targetClass, $targetId); $item = $this->dispatchContextTitle($item, $targetClass); $result[] = $item; } return $result; }
/** * {@inheritdoc} */ public function getParameters() { if (null === $this->tokenStorage->getToken()) { return ['settingKey' => self::SETTING_KEY]; } $user = $this->tokenStorage->getToken()->getUser(); if (!$user instanceof UserInterface) { return ['settingKey' => self::SETTING_KEY]; } $result = []; $exists = false; foreach ($user->getRoleObjects() as $role) { if (null === ($setting = $role->getSetting(self::SETTING_KEY))) { continue; } $result = array_merge_recursive($result, $setting->getValue()); $exists = true; } if (!$exists) { return ['settingKey' => self::SETTING_KEY]; } // array_merge_recursive accepts non-unique values they have to be removed foreach (array_keys($result) as $section) { $result[$section] = array_values(array_unique($result[$section])); } return ['settingKey' => self::SETTING_KEY, 'userToolbar' => $result]; }
public function buildForm(FormBuilderInterface $builder, array $options) { $token = $this->tokenStorage->getToken(); if ($token === null) { throw new \LogicException('Unable to get token from security storage for portfolio widget form!'); } $user = $token->getUser(); if (!$user) { throw new \LogicException('Unable to get connected user for portfolio widget form!'); } $builder->add('portfolio_id', 'entity', ['class' => 'IcapPortfolioBundle:Portfolio', 'query_builder' => function (EntityRepository $entityRepository) use($user) { return $entityRepository->createQueryBuilder('p')->where('p.user = :user')->setParameter('user', $user); }, 'property_path' => 'portfolio'])->add('widget_id', 'entity', ['class' => 'IcapPortfolioBundle:Widget\\AbstractWidget', 'query_builder' => function (EntityRepository $entityRepository) use($user) { return $entityRepository->createQueryBuilder('w')->where('w.user = :user')->setParameter('user', $user); }, 'property_path' => 'widget'])->add('col', 'integer')->add('row', 'integer')->add('sizeX', 'integer')->add('sizeY', 'integer'); $builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) use($user) { $form = $event->getForm(); $choices = []; $choiceTypes = $this->widgetTypeManager->getWidgetsTypes(); foreach ($choiceTypes as $choiceType) { $choices[$choiceType['name']] = $choiceType['name']; } $form->add('widget_type', 'choice', ['choices' => $choices]); }); }
public function buildForm(FormBuilderInterface $builder, array $options) { /** @var \Claroline\CoreBundle\Entity\User $user */ $user = $this->tokenStorage->getToken()->getUser(); $locale = null === $user->getLocale() ? $this->platformConfigHandler->getParameter('locale_language') : $user->getLocale(); $builder->add('badge', 'zenstruck_ajax_entity', array('attr' => array('class' => 'fullwidth'), 'theme_options' => array('control_width' => 'col-md-3'), 'placeholder' => $this->translator->trans('badge_form_badge_selection', array(), 'icap_badge'), 'class' => 'IcapBadgeBundle:Badge', 'use_controller' => true, 'repo_method' => sprintf('findByNameForAjax'), 'extra_data' => array('userId' => $user->getId(), 'locale' => $locale))); }
/** * @return Item */ private function createRootItem() { $rootItem = new Item('account'); $rootItem->setLabel($this->translator->trans('admin.welcome', array('%username%' => $this->tokenStorage->getToken()->getUsername()), 'FSiAdminSecurity')); $rootItem->setOptions(array('attr' => array('id' => 'account'))); return $rootItem; }
/** * Merge in dashboard list into runtime configuration. * * {@inheritdoc} */ public function merge(array $currentConfig) { /** @var User $user */ $user = $this->tokenStorage->getToken()->getUser(); $defaultDashboardNames = []; foreach ($this->dashboardMgr->getDefaultDashboards($user) as $dashboard) { $defaultDashboardNames[] = $dashboard->getName(); } $isDefaultFound = false; $result = array(); foreach ($this->dashboardMgr->getUserDashboards($user) as $dashboard) { if (!$dashboard->isAllowed($this->container)) { continue; } $isDefault = in_array($dashboard->getName(), $defaultDashboardNames); if ($isDefault) { $isDefaultFound = true; } $result[] = array_merge($this->serializeDashboard($dashboard), array('default' => $isDefault)); } if (!$isDefaultFound) { // if there's no default dashboard available for a given user then we will display a dashboard // where user will be able to pick one he/she needs $dashboard = new SimpleDashboard('default', 'List of user dashboards', 'Modera.backend.dashboard.runtime.DashboardListDashboardActivity'); $result[] = array_merge($this->serializeDashboard($dashboard), array('default' => true)); } return array_merge($currentConfig, array('modera_backend_dashboard' => array('dashboards' => $result))); }
public function showUser(ShowUserEvent $event) { if ($this->tokenStorage->getToken()->isAuthenticated()) { $user = $this->tokenStorage->getToken()->getUser(); $event->setUser($user); } }
/** * {@inheritdoc} */ public function generate(Request $request) { $token = $this->tokenStorage->getToken(); $user = null === $token ? 'anon.' : $token->getUser(); $version = sprintf('u:%s', is_string($user) ? $user : $user->getId()); return $version; }
/** * @param GetResponseEvent $event */ public function handle(GetResponseEvent $event) { if (null !== $this->tokenStorage->getToken()) { return; } $request = $event->getRequest(); $token = new PluginToken($this->providerKey, $request->get('integration', null)); try { $authToken = $this->authenticationManager->authenticate($token); if ($authToken instanceof PluginToken) { $response = $authToken->getResponse(); if ($authToken->isAuthenticated()) { $this->tokenStorage->setToken($authToken); if ('api' != $this->providerKey) { $response = $this->onSuccess($request, $authToken, $response); } } elseif (empty($response)) { throw new AuthenticationException('mautic.user.auth.error.invalidlogin'); } } } catch (AuthenticationException $exception) { if ('api' != $this->providerKey) { $response = $this->onFailure($request, $exception); } } if ($response) { $event->setResponse($response); } }
/** * 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->tokenStorage->getToken(); if ($token instanceof TokenInterface) { $token->setUser(new User($apiUser)); // Don't embed if we already have a LegacyToken, to avoid nested session storage. if (!$token instanceof LegacyToken) { $this->tokenStorage->setToken(new LegacyToken($token)); } } } catch (NotFoundException $e) { // Invalid user ID, the user may have been removed => invalidate the token and the session. $this->tokenStorage->setToken(null); $session->invalidate(); } }
/** * Determines if a node should be skipped from rendering based on the current * user's role * * @param CreateMenuItemFromNodeEvent $event */ public function onCreateMenuItemFromNode(CreateMenuItemFromNodeEvent $event) { $node = $event->getNode(); if ($node instanceof MenuNode) { $addRole = $node->getAddWhenGranted(); $removeRole = $node->getRemoveWhenGranted(); //This avoids issue when rendering error pages with menus //Defaults all menu items with any role requirements to no be displayed if ($this->token->getToken() === null) { if ($addRole !== null || $removeRole !== null) { $event->setSkipNode(true); } return; } if ($addRole !== null) { if (!$this->security->isGranted($addRole)) { $event->setSkipNode(true); } } if ($removeRole !== null) { if ($this->security->isGranted($removeRole)) { $event->setSkipNode(true); } } } }
/** * Get the attribute collection. * * TODO This action is only accessible via a GET or POST query, because of too long query URI. To respect standards, * a refactor must be done. * * @param Request $request * * @return JsonResponse */ public function indexAction(Request $request) { $options = []; $context = ['include_group' => true]; if ($request->request->has('identifiers')) { $options['identifiers'] = explode(',', $request->request->get('identifiers')); $context['include_group'] = false; } if ($request->request->has('types')) { $options['types'] = explode(',', $request->request->get('types')); } if (empty($options)) { $options = $request->request->get('options', ['limit' => SearchableRepositoryInterface::FETCH_LIMIT, 'locale' => null]); } $token = $this->tokenStorage->getToken(); $options['user_groups_ids'] = $token->getUser()->getGroupsIds(); if (null !== $this->attributeSearchRepository) { $attributes = $this->attributeSearchRepository->findBySearch($request->request->get('search'), $options); } else { if (isset($options['identifiers'])) { $options['code'] = $options['identifiers']; } $attributes = $this->attributeRepository->findBy($options); } $normalizedAttributes = $this->normalizer->normalize($attributes, 'internal_api', $context); return new JsonResponse($normalizedAttributes); }
private function generateErrorForException(\Exception $exception) { if ($exception instanceof CommandInvalidException) { $formError = $exception->getForm()->getErrors(true)->current(); $path = $formError->getOrigin()->getPropertyPath(); if ($path !== null) { // We got PropertyPathInterface or maybe even a string (undocumented). $path = (string) $path; } return new E\Api\BadRequest($formError->getMessage(), $path); } elseif ($exception instanceof ConstraintViolationException) { return $exception->getError(); } elseif ($exception instanceof UsernameNotFoundException) { return new E\Security\BadCredentials(); } elseif ($exception instanceof AccessDeniedException) { $token = $this->tokenStorage->getToken(); if ($token && $this->tokenStorage->getToken()->getRoles()) { return new E\Security\NotAuthorized(); } else { return new E\Security\NotAuthenticated(); } } elseif ($exception instanceof ProtocolException) { return $this->getErrorForOxygenProtocolException($exception); } else { return new E\Api\UnexpectedError(); } }
/** * Checks if there is an authenticated user. * * @return bool */ protected function hasUser() { $user = $this->tokenStorage->getToken(); if (null === $user) { return false; } return !$user instanceof AnonymousToken; }
/** * {@inheritdoc} */ public function getUser() { $token = $this->tokenStorage->getToken(); if (null !== $token) { return $token->getUser(); } return null; }
/** * @return mixed * @throws AccessDeniedException */ private function getUser() { if (!$this->authorizationChecker->isGranted('IS_AUTHENTICATED_FULLY')) { throw new AccessDeniedException(); } else { return $this->tokenStorage->getToken()->getUser(); } }