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; } }
/** * 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(); } }
/** * @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 . '>'; }
/** * 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 }
/** * Gets permissions of the given user * * @param User $user * @param Criteria|null $filters * * @return array */ public function getUserPermissions(User $user, Criteria $filters = null) { $entityAclExtension = $this->aclSelector->select($user); $resources = array_map(function (AclClassInfo $class) use($entityAclExtension) { return ['type' => $entityAclExtension->getExtensionKey(), 'resource' => $class->getClassName()]; }, $entityAclExtension->getClasses()); if ($filters) { $collection = new ArrayCollection($resources); $resources = $collection->matching($filters)->toArray(); } $result = []; $originalToken = $this->impersonateUser($user); try { foreach ($resources as $resource) { $oid = new ObjectIdentity($resource['type'], $resource['resource']); $permissions = []; foreach ($entityAclExtension->getAllowedPermissions($oid) as $permission) { if ($this->securityContext->isGranted($permission, $oid)) { $permissions[] = $permission; } } $result[] = array_merge($resource, ['permissions' => $permissions]); } $this->undoImpersonation($originalToken); } catch (\Exception $e) { $this->undoImpersonation($originalToken); throw $e; } return $result; }
/** * Construit le menu supplémentaire de la gestion des services du serveur * * @param SidebarItem $sidebar Sidebar d'origine à completer */ public function build(SidebarItem $sidebar) { if (!$this->context->isGranted('ROLE_SUPER_ADMIN')) { return; } $server = $sidebar->addChild('olix_server', array('label' => 'Gestion du serveur', 'icon' => 'fa fa-server fa-fw')); $server->addChild('olix_server_monit', array('label' => 'Gestion des services', 'icon' => 'fa fa-circle fa-fw', 'route' => 'olix_server_monit')); $server->addChild('olix_server_collectd', array('label' => 'Monitoring', 'icon' => 'fa fa-area-chart fa-fw', 'route' => 'olix_server_collectd')); }
public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('grid', 'enhavo_grid', array('label' => 'form.label.content', 'translation_domain' => 'EnhavoAppBundle')); if ($this->securityContext->isGranted('WORKFLOW_ACTIVE', $this->dataClass)) { $entityName = array(); $entityName[0] = $this->dataClass; $builder->add('workflow_status', 'enhavo_workflow_status', array('label' => 'workflow.form.label.next_state', 'translation_domain' => 'EnhavoWorkflowBundle', 'attr' => $entityName)); } }
/** * Do the magic. * * @param InteractiveLoginEvent $event */ public function onSecurityInteractiveLogin(InteractiveLoginEvent $event) { if ($this->securityContext->isGranted('IS_AUTHENTICATED_FULLY')) { $user = $this->securityContext->getToken()->getUser(); if ($user instanceof User) { $user->setLastLoginAt(new DateTime()); $this->em->persist($user); $this->em->flush($user); } } }
/** * {@inheritdoc} */ public function setDefaultOptions(OptionsResolverInterface $resolver) { $choices = []; if ($this->context->isGranted(User::ROLE_SUPER_ADMIN)) { $choices = $this->repository->findAll(); } else { $groups = $this->groupResolver->getAccessibleGroupsId(); $choices = $this->repository->findByGroups($groups); } $resolver->setDefaults(array('label' => 'game.selectMachine', 'class' => 'DPMachineBundle:Machine', 'choices' => $choices)); }
/** * @Route("/check", name="check_oauth") * Cette action vérifie que l'utilisateur a remplis son inscription et que le compte est actif. */ public function checkAction() { $this->securityContext = $this->get('security.context'); $this->token = $this->securityContext->getToken(); if (!$this->securityContext->isGranted('ROLE_ORGA')) { // Si l'utilisateur ne s'est pas enregistré return $this->redirect($this->generateUrl("register_oauth")); } else { return $this->redirect($this->generateUrl("base_accueil")); } }
/** * @param array $roles * @return bool */ public function checkAnyRole(array $roles) { if ($this->securityContext->isGranted('ROLE_SUPER_ADMIN')) { return true; } foreach ($roles as $role) { if ($this->securityContext->isGranted($role)) { return true; } } return false; }
/** * */ public function onSlugSecurityEvent() { $node = $this->request->attributes->get('_nodeTranslation')->getNode(); /* @var SecurityContextInterface $securityContext */ if (false === $this->securityContext->isGranted(PermissionMap::PERMISSION_VIEW, $node)) { throw new AccessDeniedException('You do not have sufficient rights to access this page.'); } $locale = $this->request->attributes->get('_locale'); $preview = $this->request->attributes->get('preview'); $nodeMenu = new NodeMenu($this->em, $this->securityContext, $this->acl, $locale, $node, PermissionMap::PERMISSION_VIEW, $preview); $this->request->attributes->set('_nodeMenu', $nodeMenu); }
/** * @param Request $request * * @return \Knp\Menu\ItemInterface */ public function createUserMenu(Request $request) { $menu = $this->factory->createItem('user'); if (false === $this->securityContext->isGranted('IS_AUTHENTICATED_FULLY')) { $menu->addChild('login', ['route' => 'fos_user_security_login', 'label' => $this->translator->trans('login', [], 'menu')]); } else { $user = $this->securityContext->getToken()->getUser(); $currentUserMenu = $menu->addChild('current_user', ['label' => $user->getUsername()]); $currentUserMenu->addChild('profile', ['route' => 'fos_user_profile_show', 'label' => '.icon-user ' . $this->translator->trans('profile', [], 'menu')]); $currentUserMenu->addChild('logout', ['route' => 'fos_user_security_logout', 'label' => '.icon-off ' . $this->translator->trans('logout', [], 'menu')]); } return $menu; }
/** * 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 $user = $event->getAuthenticationToken()->getUser(); // ... $this->getUserService()->markLoginInfo(); }
/** * @TODO: Move below to config * * @param Request $request * * @return \Knp\Menu\ItemInterface */ public function createMainMenu(Request $request) { $menu = $this->factory->createItem('root'); $menu->setChildrenAttributes(array('class' => 'navbar-nav nav')); $menu->addChild('nav.home', array('route' => 'quickstart_app_homepage')); if ($this->securityContext->isGranted('IS_AUTHENTICATED_FULLY')) { $menu->addChild($this->securityContext->getToken()->getUser()->getEmail(), array('route' => 'quickstart_app_account')); $menu->addChild('nav.logout', array('route' => 'fos_user_security_logout')); } else { $menu->addChild('nav.register', array('route' => 'fos_user_registration_register')); $menu->addChild('nav.login', array('route' => 'fos_user_security_login')); } return $menu; }
/** * Perform basic security checks * * @param SlugSecurityEvent $event * * @throws AccessDeniedException * @throws NotFoundHttpException */ public function onSlugSecurityEvent(SlugSecurityEvent $event) { $node = $event->getNode(); $nodeTranslation = $event->getNodeTranslation(); $request = $event->getRequest(); /* @var SecurityContextInterface $securityContext */ if (false === $this->securityContext->isGranted(PermissionMap::PERMISSION_VIEW, $node)) { throw new AccessDeniedException('You do not have sufficient rights to access this page.'); } $isPreview = $request->attributes->get('preview'); if (!$isPreview && !$nodeTranslation->isOnline()) { throw new NotFoundHttpException('The requested page is not online'); } }
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'); }
/** * Adds Export * * @param ExportInterface $export * * @return self */ public function addExport(ExportInterface $export) { if ($export->getRole() === null || $this->securityContext->isGranted($export->getRole())) { $this->exports[] = $export; } return $this; }
/** * Load entities that user has access to * * @param null|string Workflow state the entity has to be in * @param null|string Workflow state the entity must NOT be in * @param null|string Field to sort on * @param null|string Direction to sort in ('ASC'|'DESC') * @return bool True on success and false on error. * @since Method available since Release 1.0.0 * @throws Exception if loading fails */ private function _loadEntities($state = null, $state_exclude = null, $sort = null, $order = null) { if (!$this->securityContext->isGranted('allentities')) { $allowedUserId = $this->_user->getUid(); } else { $allowedUserId = null; } $filter = array('state' => $state, 'stateExclude' => $state_exclude, 'allowedUserId' => $allowedUserId); $connectionCollection = $this->connectionService->findDescriptorsForFilters($filter, $sort, $order); $this->_entities = array(); /** @var $connectionDto \Janus\ServiceRegistry\Connection\ConnectionDto */ foreach ($connectionCollection->connections as $connectionDto) { $entity = new sspmod_janus_Entity($this->_config); $entity->setEid($connectionDto->id); $entity->setRevisionid($connectionDto->revisionNr); if (!is_null($state)) { $entity->setWorkflow($state); } if ($entity->load()) { $this->_entities[] = $entity; } else { SimpleSAML_Logger::error('JANUS:UserController:_loadEntities - Entity could not be loaded: ' . var_export($entity, true)); } } return true; }
/** * @param GetResponseEvent $event */ public function onKernelRequest(GetResponseEvent $event) { $request = $event->getRequest(); $host = $request->getHost(); $baseHost = $this->baseHost; $subdomain = str_replace('.' . $baseHost, '', $host); //Check subDomain $this->checkOldDomains($subdomain); //Fix logout bug $str = $baseHost . "/login"; if ($host != $baseHost && strstr($request->getUri(), $str, true)) { $event->setResponse(new RedirectResponse($this->router->generate('buddy_system_user_homepage_index'))); } //Fix dashboard error if ($this->security_context->getToken() && $this->security_context->isGranted('IS_AUTHENTICATED_REMEMBERED') && $request->get('_route') == 'buddy_system_user_homepage_index') { $this->checkSectionAccess(); $this->activityManager->setUser($this->security_context); $this->activityManager->login(); if ($this->security_context->isGranted('ROLE_ADMIN') || $this->security_context->isGranted('ROLE_SUPER_ADMIN')) { $event->setResponse(new RedirectResponse($this->router->generate('buddy_system_sadmin_homepage'))); } else { if ($this->security_context->isGranted('ROLE_BUDDYCOORDINATOR')) { $event->setResponse(new RedirectResponse($this->router->generate('buddy_system_admin_homepage'))); } else { $event->setResponse(new RedirectResponse($this->router->generate('buddy_system_members_homepage'))); } } } if ($host == $baseHost) { if ($request->get('_route') != null && $request->get('_route') != "buddy_system_choose" && $request->get('_route') != "buddy_system_front_change_language_ajax") { $event->setResponse(new RedirectResponse($this->router->generate('buddy_system_choose'))); } } else { //Redirection when /en or /fr at the end $url = $request->getUri(); if (substr($url, -3) == "/fr" || substr($url, -3) == "/en") { $event->setResponse(new RedirectResponse(substr($url, 0, strlen($url) - 3))); } //Add Section to local if (!$this->sectionManager->getCurrentSection()) { /** @var Section $section */ $section = $this->em->getRepository('BuddySystemMainBundle:Section')->findOneBy(array('subdomain' => $subdomain)); //Fix error on www if (!$section && $subdomain == "www") { header('Location: http://buddysystem.eu'); } if (!$section) { throw new NotFoundHttpException(sprintf('Cannot find section for host "%s", subdomain "%s"', $host, $subdomain)); } if (!array_key_exists('section', $this->twig->getGlobals())) { $this->twig->addGlobal('section', $section); } $this->sectionManager->setCurrentSection($section); } } if ($this->security_context->getToken() && $this->security_context->getToken()->getUser() && $this->sectionManager->getCurrentSection()) { $this->checkSectionAccess(); } }
public function showAction(Request $request, FlattenException $exception, DebugLoggerInterface $logger = null, $format = 'html') { if ('Trez\\LogicielTrezBundle\\Exception\\LockedException' === $exception->getClass()) { $this->session->getFlashBag()->set('error', "Vous ne pouvez pas éditer un exercice/budget verrouillé ou ses fils"); return new RedirectResponse($this->request->getRequestUri(), 302); } if ('Symfony\\Component\\HttpKernel\\Exception\\AccessDeniedHttpException' === $exception->getClass()) { $this->session->getFlashBag()->set('error', "Vous n'avez pas les privilèges nécessaires pour effectuer cette action !"); if ($this->securityContext->isGranted('ROLE_USER') === true) { return new Response($this->twig->render('TrezLogicielTrezBundle:Default:index.html.twig', array())); } else { return new Response("Vous n'avez pas les privilèges nécessaires pour afficher cette page !"); } } // else default behavior return parent::showAction($exception, $logger, $format); }
/** * @param null|User|string $user * string: Email or Username * User: User instance * null: CurrentUser if auth else placeholder * * @param int $size * * @return string */ public function getGravatarImage($user = null, $size = 80) { $defaultImage = 'www.locastic.com/no-gravatar-image.jpg'; if (null === $user) { if (false === $this->securityContext->isGranted('IS_AUTHENTICATED_FULLY')) { return $defaultImage; } $user = $this->securityContext->getToken()->getUser(); } else { if (!$user instanceof User) { $user = $this->userManager->findUserByUsernameOrEmail($user); } } if (null !== $user->getGithubID()) { return $this->renderGithubGravatar($user, $size); } return $this->renderDefaultGravatar($user, $size); }
/** * */ public function onSlugSecurityEvent(SlugSecurityEvent $event) { $node = $event->getNode(); $nodeTranslation = $event->getNodeTranslation(); $request = $event->getRequest(); /* @var SecurityContextInterface $securityContext */ if (false === $this->securityContext->isGranted(PermissionMap::PERMISSION_VIEW, $node)) { throw new AccessDeniedException('You do not have sufficient rights to access this page.'); } $locale = $request->attributes->get('_locale'); $preview = $request->attributes->get('preview'); // check if the requested node is online, else throw a 404 exception (only when not previewing!) if (!$preview && !$nodeTranslation->isOnline()) { throw new NotFoundHttpException("The requested page is not online"); } $nodeMenu = new NodeMenu($this->em, $this->securityContext, $this->acl, $locale, $node, PermissionMap::PERMISSION_VIEW, $preview); $request->attributes->set('_nodeMenu', $nodeMenu); }
/** * In this method you can add children for a specific parent, but also remove and change the already created * children * * @param MenuBuilder $menu The MenuBuilder * @param MenuItem[] &$children The current children * @param MenuItem|null $parent The parent Menu item * @param Request $request The Request */ public function adaptChildren(MenuBuilder $menu, array &$children, MenuItem $parent = null, Request $request = null) { foreach ($this->menuItems as $item) { if (false === $this->parentMatches($parent, $item)) { continue; } if ($item['role'] && false === $this->securityContext->isGranted($item['role'])) { continue; } $menuItem = new TopMenuItem($menu); $menuItem->setRoute($item['route'], $item['params'])->setLabel($item['label'])->setUniqueId($item['route'])->setParent($parent); if ($request && stripos($request->attributes->get('_route'), $menuItem->getRoute()) === 0) { $menuItem->setActive(true); $parent->setActive(true); } $children[] = $menuItem; } }
/** * Do the magic. * * @param InteractiveLoginEvent $event */ public function onSecurityInteractiveLogin(InteractiveLoginEvent $event) { // var_dump("aaaaa");exit(); 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 $user = $event->getAuthenticationToken()->getUser(); // ... $this->getUserService()->markLoginInfo(); $request = $event->getRequest(); $sessionId = $request->getSession()->getId(); $request->getSession()->set('loginIp', $request->getClientIp()); $this->getUserService()->rememberLoginSessionId($user['id'], $sessionId); $this->getUserService()->markLoginSuccess($user['id'], $request->getClientIp()); }
public function hasRouteAccess($routeName) { $token = $this->securityContext->getToken(); if ($token->isAuthenticated()) { $route = $this->router->getRouteCollection()->get($routeName); $controller = $route->getDefault('_controller'); list($class, $method) = explode('::', $controller, 2); $metadata = $this->getMetadata($class); if (!isset($metadata->methodMetadata[$method])) { return false; } foreach ($metadata->methodMetadata[$method]->roles as $role) { if ($this->securityContext->isGranted($role)) { return true; } } } return false; }
/** * Get current user * * @return Newscoop\Entity\User */ public function getCurrentUser() { if ($this->currentUser === null) { if ($this->auth->hasIdentity()) { $this->currentUser = $this->getRepository()->find($this->auth->getIdentity()); } elseif ($this->security->getToken()) { if ($this->security->getToken()->getUser()) { $currentUser = $this->security->getToken()->getUser(); if ($this->security->isGranted('IS_AUTHENTICATED_FULLY') || $this->security->isGranted('IS_AUTHENTICATED_REMEMBERED')) { $this->currentUser = $currentUser; } else { throw new AuthenticationException(); } } else { throw new AuthenticationException(); } } } return $this->currentUser; }
/** * @param ItemInterface $menu * @param array $nav * @param SecurityContext $security */ private function menuCreator(ItemInterface &$menu, array $nav, SecurityContext &$security, $level = 0) { foreach ($nav as $route => $options) { $options = $this->defaultOptions($options); if (!empty($options['role'])) { $check = $options['isGrantedType'] ? $security->isGranted($options['role']) : !$security->isGranted($options['role']); } else { $check = true; } /** bool $check */ if ($check) { $route = $route[0] != '#' ? ['route' => $route] : []; $menu->addChild($options['name'], $route)->setAttribute('icon', $options['icon']); if (isset($options['child'])) { $menu[$options['name']]->setAttribute('dropdown', true)->setAttribute('icon', $options['icon'])->setAttribute('class', $level > 0 ? 'dropdown-submenu' : ''); $this->menuCreator($menu[$options['name']], $options['child'], $security, $level + 1); } } } }
public function loginAction(Request $req, Twig_Environment $twig, SecurityContext $sc, UrlGenerator $urlgen) { if ($sc->isGranted('IS_AUTHENTICATED_FULLY')) { return new RedirectResponse($urlgen->generate('home')); } else { $session = $req->getSession(); $errorConst = $sc::AUTHENTICATION_ERROR; $lastUsernameConst = $sc::LAST_USERNAME; return $twig->render('login.html.twig', array('error' => $session->has($errorConst) ? $session->get($errorConst)->getMessage() : null, 'last_username' => $session->get($lastUsernameConst))); } }
/** * Return the cache options for the current request * * @param Request $request * @return array of settings */ protected function getOptions(Request $request) { foreach ($this->map as $elements) { if (!empty($elements[1]['unless_role']) && $this->securityContext && $this->securityContext->isGranted($elements[1]['unless_role'])) { continue; } if (null === $elements[0] || $elements[0]->matches($request)) { return $elements[1]; } } return array(); }