protected function buildUserForm(FormBuilderInterface $builder, array $options) { $otherthanstudents = ''; foreach ($this->definedRoles as $keys => $values) { if ($keys == 'ROLE_SISWA' || $keys == 'ROLE_USER') { continue; } $otherthanstudents .= "'{$keys}', "; } $otherthanstudents = preg_replace('/, $/', '', $otherthanstudents); if ($this->authorizationChecker->isGranted([new Expression("hasAnyRole({$otherthanstudents})")])) { $builder->add('username', null, ['required' => true]); } $builder->add('email', 'email', ['required' => true])->add('name', null, ['required' => true, 'label' => 'label.name.full'])->add('nomorPonsel', 'text', ['label' => 'label.nomor.ponsel', 'required' => true]); if ($this->authorizationChecker->isGranted('ROLE_SUPER_ADMIN')) { foreach ($this->definedRoles as $keys => $values) { $string = str_replace('ROLE_', ' ', $keys); $roles[$keys] = str_replace('_', ' ', $string); } $builder->add('roles', 'choice', ['choices' => $roles, 'label' => 'label.roles', 'multiple' => true, 'expanded' => true]); } elseif ($this->authorizationChecker->isGranted('ROLE_ADMIN')) { foreach ($this->definedRoles as $keys => $values) { if ($keys == 'ROLE_SUPER_ADMIN' || $keys == 'ROLE_USER' || $keys == 'ROLE_SISWA' || $keys == 'ROLE_WALI_KELAS' || $keys == 'ROLE_PANITIA_PSB' || $keys == 'ROLE_KETUA_PANITIA_PSB') { continue; } $string = str_replace('ROLE_', ' ', $keys); $roles[$keys] = str_replace('_', ' ', $string); } $builder->add('roles', 'choice', ['choices' => $roles, 'label' => 'label.roles', 'multiple' => true, 'expanded' => true]); } }
public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('username', null, ['required' => true, 'label' => 'label.username', 'attr' => ['class' => 'medium']])->add('email', 'email', ['required' => true, 'label' => 'label.email', 'attr' => ['class' => 'xlarge']])->add('plainPassword', 'repeated', ['type' => 'password', 'invalid_message' => 'fos_user.password.notequal', 'first_options' => ['label' => 'label.password', 'attr' => ['class' => 'medium']], 'second_options' => ['label' => 'label.repassword', 'attr' => ['class' => 'medium']]])->add('name', null, ['required' => true, 'label' => 'label.name.full', 'attr' => ['class' => 'xlarge']]); foreach ($options['role_hierarchy'] as $keys => $values) { if ($options['mode'] == 1) { // registration type 1, no school, only for super admin if (!($keys == 'ROLE_USER' || $keys == 'ROLE_SUPER_ADMIN')) { continue; } } else { // registration type other than 1, with school if ($keys == 'ROLE_USER' || $keys == 'ROLE_SUPER_ADMIN' || $keys == 'ROLE_SISWA' || $keys == 'ROLE_WALI_KELAS' || $keys == 'ROLE_PANITIA_PSB' || $keys == 'ROLE_KETUA_PANITIA_PSB') { continue; } } $string = str_replace('ROLE_', ' ', $keys); $roles[$keys] = str_replace('_', ' ', $string); } $builder->add('roles', 'choice', ['choices' => $roles, 'label' => 'label.roles', 'multiple' => true, 'expanded' => true])->add('nomorPonsel', 'text', ['required' => false, 'label' => 'label.nomor.ponsel']); if ($options['mode'] != 1) { if ($this->authorizationChecker->isGranted('ROLE_SUPER_ADMIN')) { $builder->add('sekolah', 'entity', ['class' => 'LanggasSisdikBundle:Sekolah', 'label' => 'label.school', 'multiple' => false, 'expanded' => false, 'property' => 'nama', 'required' => true]); } else { $sekolah = $this->getSekolah(); $builder->addEventSubscriber(new SekolahSubscriber($sekolah)); $builder->add('sekolah', 'sisdik_entityhidden', ['required' => true, 'class' => 'LanggasSisdikBundle:Sekolah', 'data' => $sekolah->getId()]); } } $builder->add('enabled', 'checkbox', ['label' => 'label.enabled', 'required' => false, 'widget_checkbox_label' => 'widget', 'horizontal_input_wrapper_class' => 'col-sm-offset-4 col-sm-8 col-md-offset-4 col-md-7 col-lg-offset-3 col-lg-9']); }
public function buildForm(FormBuilderInterface $builder, array $options) { $sekolah = $this->getSekolah(); $builder->add('sekolah', 'sisdik_entityhidden', ['required' => true, 'class' => 'LanggasSisdikBundle:Sekolah', 'data' => $sekolah->getId()])->add('tahun', 'sisdik_entityhidden', ['required' => true, 'class' => 'LanggasSisdikBundle:Tahun', 'data' => $options['tahun_aktif']]); if ($options['mode'] == 'new') { $builder->add('gelombang', 'entity', ['class' => 'LanggasSisdikBundle:Gelombang', 'label' => 'label.admissiongroup.entry', 'multiple' => false, 'expanded' => false, 'property' => 'nama', 'placeholder' => false, 'required' => true, 'query_builder' => function (EntityRepository $repository) use($sekolah) { $qb = $repository->createQueryBuilder('gelombang')->where('gelombang.sekolah = :sekolah')->orderBy('gelombang.urutan', 'ASC')->setParameter('sekolah', $sekolah); return $qb; }, 'attr' => ['class' => 'medium']])->add('namaLengkap', null, ['required' => true, 'attr' => ['class' => 'large'], 'label' => 'label.name.full'])->add('orangtuaWali', 'collection', ['type' => new OrangtuaWaliInitType(), 'by_reference' => false, 'attr' => ['class' => 'large'], 'label' => 'label.name.parent.or.guardian', 'options' => ['widget_form_group' => false, 'label_render' => false], 'label_render' => false, 'allow_add' => true])->add('adaReferensi', 'checkbox', ['label' => 'label.ada.referensi', 'required' => false, 'attr' => ['class' => 'referensi-check'], 'widget_checkbox_label' => 'widget', 'horizontal_input_wrapper_class' => 'col-sm-offset-4 col-sm-8 col-md-offset-4 col-md-7 col-lg-offset-3 col-lg-9'])->add('referensi', 'sisdik_entityhidden', ['class' => 'LanggasSisdikBundle:Referensi', 'label_render' => false, 'required' => false, 'attr' => ['class' => 'large id-referensi']])->add('namaReferensi', 'text', ['required' => false, 'attr' => ['class' => 'xlarge nama-referensi ketik-pilih-tambah', 'placeholder' => 'label.ketik-pilih.atau.ketik-tambah'], 'label' => 'label.perujuk'])->add('tentukanPenjurusan', 'checkbox', ['label' => 'label.tentukan.penjurusan.studi', 'required' => false, 'attr' => ['class' => 'penjurusan-check'], 'widget_checkbox_label' => 'widget', 'horizontal_input_wrapper_class' => 'col-sm-offset-4 col-sm-8 col-md-offset-4 col-md-7 col-lg-offset-3 col-lg-9'])->add('penjurusan', 'entity', ['class' => 'LanggasSisdikBundle:Penjurusan', 'label' => 'label.placement.study', 'multiple' => false, 'expanded' => false, 'property' => 'optionLabel', 'placeholder' => 'label.tanpa.penjurusan.studi', 'required' => false, 'query_builder' => function (EntityRepository $repository) use($sekolah) { $qb = $repository->createQueryBuilder('penjurusan')->where('penjurusan.sekolah = :sekolah')->orderBy('penjurusan.root', 'ASC')->addOrderBy('penjurusan.lft', 'ASC')->setParameter('sekolah', $sekolah); return $qb; }])->add('dibuatOleh', 'sisdik_entityhidden', ['required' => true, 'class' => 'LanggasSisdikBundle:User', 'data' => $this->getUser()->getId()]); } elseif ($options['mode'] == 'editregphoto') { $builder->add('fotoPendaftaran', 'hidden', ['attr' => ['class' => 'foto-pendaftaran']])->add('diubahOleh', 'sisdik_entityhidden', ['required' => true, 'class' => 'LanggasSisdikBundle:User', 'data' => $this->getUser()->getId()]); } else { if ($this->authorizationChecker->isGranted('ROLE_KETUA_PANITIA_PSB')) { $builder->add('gelombang', 'entity', ['class' => 'LanggasSisdikBundle:Gelombang', 'label' => 'label.admissiongroup.entry', 'multiple' => false, 'expanded' => false, 'property' => 'nama', 'placeholder' => false, 'required' => true, 'query_builder' => function (EntityRepository $repository) use($sekolah) { $qb = $repository->createQueryBuilder('gelombang')->where('gelombang.sekolah = :sekolah')->orderBy('gelombang.urutan', 'ASC')->setParameter('sekolah', $sekolah); return $qb; }, 'attr' => ['class' => 'medium']]); } $builder->add('penjurusan', 'entity', ['class' => 'LanggasSisdikBundle:Penjurusan', 'label' => 'label.placement.study', 'multiple' => false, 'expanded' => false, 'property' => 'optionLabel', 'placeholder' => 'label.tanpa.penjurusan.studi', 'required' => false, 'query_builder' => function (EntityRepository $repository) use($sekolah) { $qb = $repository->createQueryBuilder('penjurusan')->where('penjurusan.sekolah = :sekolah')->orderBy('penjurusan.root', 'ASC')->addOrderBy('penjurusan.lft', 'ASC')->setParameter('sekolah', $sekolah); return $qb; }])->add('namaLengkap', null, ['required' => true, 'attr' => ['class' => 'large'], 'label' => 'label.name.full'])->add('nisn', 'text', ['label' => 'label.nisn'])->add('referensi', 'sisdik_entityhidden', ['class' => 'LanggasSisdikBundle:Referensi', 'label_render' => false, 'required' => false, 'attr' => ['class' => 'id-referensi']])->add('namaReferensi', 'text', ['required' => false, 'attr' => ['class' => 'xlarge nama-referensi ketik-pilih-tambah', 'placeholder' => 'label.ketik-pilih.atau.ketik-tambah'], 'label' => 'label.perujuk'])->add('sekolahAsal', 'sisdik_entityhidden', ['class' => 'LanggasSisdikBundle:SekolahAsal', 'label_render' => false, 'required' => false, 'attr' => ['class' => 'id-sekolah-asal']])->add('namaSekolahAsal', 'text', ['required' => false, 'attr' => ['class' => 'xlarge nama-sekolah-asal ketik-pilih-tambah', 'placeholder' => 'label.ketik-pilih.atau.ketik-tambah'], 'label' => 'label.sekolah.asal'])->add('jenisKelamin', 'choice', ['required' => true, 'choices' => ['L' => 'Laki-laki', 'P' => 'Perempuan'], 'expanded' => true, 'multiple' => false, 'attr' => ['class' => 'medium'], 'label' => 'label.gender'])->add('agama', null, ['required' => true, 'label' => 'label.religion', 'attr' => ['class' => 'medium']])->add('alamat', 'textarea', ['label' => 'label.address', 'attr' => ['class' => 'xlarge'], 'required' => true])->add('keterangan', 'textarea', ['label' => 'label.keterangan', 'attr' => ['class' => 'xlarge'], 'required' => false])->add('file', 'file', ['required' => false, 'label' => 'label.photo'])->add('tempatLahir', null, ['label' => 'label.birthplace', 'attr' => ['class' => 'large']])->add('tanggalLahir', 'birthday', ['label' => 'label.birthday', 'widget' => 'single_text', 'format' => 'dd/MM/yyyy', 'attr' => ['class' => 'date small'], 'required' => false])->add('email', 'email', ['required' => false, 'label' => 'label.email', 'attr' => ['class' => 'large']])->add('namaPanggilan', null, ['label' => 'label.nickname', 'attr' => ['class' => 'medium']])->add('kewarganegaraan', null, ['label' => 'label.nationality', 'attr' => ['class' => 'medium']])->add('anakKe', 'number', ['label' => 'label.childno', 'required' => false, 'attr' => ['class' => 'mini']])->add('jumlahSaudarakandung', 'number', ['label' => 'label.brothers.num', 'required' => false, 'attr' => ['class' => 'mini']])->add('jumlahSaudaratiri', 'number', ['label' => 'label.brothersinlaw.num', 'required' => false, 'attr' => ['class' => 'mini']])->add('statusOrphan', null, ['label' => 'label.orphanstatus', 'attr' => ['class' => 'medium']])->add('bahasaSeharihari', null, ['label' => 'label.dailylanguage', 'attr' => ['class' => 'large']])->add('kodepos', null, ['label' => 'label.postalcode', 'attr' => ['class' => 'mini']])->add('telepon', null, ['label' => 'label.phone', 'attr' => ['class' => 'medium']])->add('ponselSiswa', null, ['label' => 'label.mobilephone.student', 'attr' => ['class' => 'medium']])->add('sekolahTinggaldi', null, ['label' => 'label.livein.whilestudy', 'attr' => ['class' => 'large']])->add('jarakTempat', null, ['label' => 'label.distance.toschool', 'attr' => ['class' => 'mini']])->add('caraKesekolah', null, ['label' => 'label.how.toschool', 'attr' => ['class' => 'large']])->add('beratbadan', null, ['label' => 'label.bodyweight', 'attr' => ['class' => 'mini']])->add('tinggibadan', null, ['label' => 'label.bodyheight', 'attr' => ['class' => 'mini']])->add('golongandarah', null, ['label' => 'label.bloodtype', 'attr' => ['class' => 'mini']])->add('diubahOleh', 'sisdik_entityhidden', ['required' => true, 'class' => 'LanggasSisdikBundle:User', 'data' => $this->getUser()->getId()]); } }
/** * @param string $className * @param int $id * @param array $data * * @return array * * @throws \Exception */ public function patch($className, $id, $data) { $entity = $this->getEntity($className, $id); if (!$this->securityService->isGranted('EDIT', $entity)) { throw new AccessDeniedException(); } return $this->entityDataManager->update($entity, $data); }
/** * @param Request $request * @param TokenInterface $token * @return RedirectResponse */ public function onAuthenticationSuccess(Request $request, TokenInterface $token) { if ($this->security->isGranted('ROLE_ADMIN')) { return new RedirectResponse($this->router->generate('admin_index')); } else { return new RedirectResponse($this->router->generate('blog_index')); } }
public function orderAction($id) { $query = new GetOrderByIdQuery($id); $this->queryBus->handle($query); if (!$this->checker->isGranted('read', $query->getResult())) { throw new AccessDeniedException(); } return new Response($this->engine->render(':order:order.html.twig', ['order' => $query->getResult()])); }
/** * Check actual status of current user return true if logged false if not. * * @return bool */ public function getLoggedStatus() { if ($this->authorizationChecker->isGranted('IS_AUTHENTICATED_FULLY')) { return true; } elseif ($this->authorizationChecker->isGranted('IS_AUTHENTICATED_REMEMBERED')) { return true; } return false; }
/** * Recursively removes all nodes this user's lacking permissions for. * * @return void * @author Marcel Eschmann **/ protected function parsePermissions(MenuNode $node) { foreach ($node->getChildren() as $key => $child) { if ($child->role === null || $child->role !== null && $this->security->isGranted($child->role)) { $this->parsePermissions($child); } else { $node->offsetUnset($key); } } }
/** * @param FormBuilderInterface $builder * @param array $options */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('firstname', null, ['label' => 'Prénom'])->add('lastname', null, ['label' => 'Nom'])->add('address', null, ['label' => 'Adresse']); if ($this->checker->isGranted('ROLE_ENTREPRISE')) { $builder->add('company', null, ['label' => 'Entreprise']); } if ($this->checker->isGranted('ROLE_MECENE')) { $builder->add('username', null, ['label' => 'Pseudo (facultatif)']); } $builder->add('email')->add('submit', SubmitType::class, ['label' => 'Valider']); }
/** * BuildForm * * @param FormBuilderInterface $builder * @param array $options * * @return null */ public function buildForm(FormBuilderInterface $builder, array $options) { $langs = array_keys($this->languages); $langChoices = array_combine($langs, $langs); $builder->add('username')->add('email', TextType::class, array('attr' => array('class' => 'width-100')))->add('fullName')->add('locale', ChoiceType::class, array('choices' => $langChoices)); if ($this->authorizationChecker->isGranted('ROLE_ADMIN')) { $builder->add('enabled', CheckboxType::class, array('required' => false))->add('formRoles', EntityType::class, array('class' => 'BigfootUserBundle:Role', 'multiple' => true)); } $builder->add('plainPassword', RepeatedType::class, array('type' => PasswordType::class, 'required' => false)); $this->eventDispatcher->dispatch(UserEvent::CREATE_FORM, new GenericEvent($builder)); }
public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('plainPassword', 'repeated', array('type' => 'password', 'options' => array('translation_domain' => 'FOSUserBundle'), 'first_options' => array('label' => 'form.new_password'), 'second_options' => array('label' => 'form.new_password_confirmation'), 'invalid_message' => 'fos_user.password.mismatch')); $builder->remove('current_password'); if ($this->auth->isGranted('ROLE_ADMIN')) { $builder->add('publisher', 'entity', array('class' => 'KingdomHall\\DataBundle\\Entity\\Publisher', 'label' => 'jwkh.entity.publisher.entity', 'expanded' => false, 'multiple' => false, 'property' => 'fullName', 'query_builder' => function (EntityRepository $er) { return $er->createQueryBuilder('p')->where('p.deleted = false'); })); $builder->add('roles', 'collection', array('label' => 'Role', 'type' => 'choice', 'options' => array('choices' => User::$ROLES))); } }
/** * Called when authentication succeeds * * @param Request $request * @param TokenInterface $token * * @return Response never null */ public function onAuthenticationSuccess(Request $request, TokenInterface $token) { if ($this->authorizationChecker->isGranted('ROLE_SUPER_ADMIN')) { $response = new RedirectResponse($this->router->generate('dashboard')); } elseif ($this->authorizationChecker->isGranted('ROLE_ADMIN')) { $response = new RedirectResponse($this->router->generate('dashboard')); } elseif ($this->authorizationChecker->isGranted('ROLE_USER')) { $response = new RedirectResponse($this->router->generate('fos_user_profile_show')); } return $response; }
/** * @param string $className * @param int $id * @param array $data * * @return array * * @throws AccessDeniedException */ public function patch($className, $id, $data) { $entity = $this->entityRoutingHelper->getEntity($className, $id); if (!$this->securityService->isGranted('EDIT', $entity)) { throw new AccessDeniedException(); } try { return $this->entityDataManager->update($entity, $data); } catch (FieldUpdateAccessException $e) { throw new AccessDeniedException($e->getMessage(), $e); } }
public function getRedirectResponse(User $user) { if ($user->isStudent()) { $response = new RedirectResponse($this->router->generate('student_homepage')); } elseif ($this->authChecker->isGranted(User::ROLE_ADMIN)) { $response = new RedirectResponse($this->router->generate('sonata_admin_dashboard')); } elseif ($this->authChecker->isGranted(User::ROLE_GS1_MEMBER)) { $response = new RedirectResponse($this->router->generate('member_homepage')); } else { $response = new RedirectResponse($this->router->generate('fos_user_security_logout')); } return $response; }
/** * @param ItemInterface $parent * @param null|string $role * @param null|string $title * @param null|string $route * @param null|string $uri * @param null|string $iconClass * @param \SimpleXMLElement $params * * @return ItemInterface|null */ protected function menuItem(ItemInterface $parent, $title, $role = null, $route = null, $uri = null, $iconClass = null, \SimpleXMLElement $params) { $item = null; if (is_null($role) || $this->authorizationChecker->isGranted($role)) { $options = ['label' => $this->translator->trans($title, [], $this->translationDomain())]; $name = uniqid(); $hidden = isset($params['hidden']) && (string) $params['hidden'] === 'true'; if ($hidden) { $options['attributes'] = ['style' => 'display: none;', 'aria-hidden' => 'true']; } if ($route) { $options['route'] = $route; $name = $route . '_' . $name; $this->addRouteParameters($route, $params, $hidden, $options); } if (is_null($route) && $uri) { $options['uri'] = $uri; $name = $uri . '_' . $name; } $item = $parent->addChild($name, $options); $item->setExtra('hidden', $hidden); if ($iconClass) { $item->setExtra('icon_class', $iconClass); } } return $item; }
public function __construct(AkismetInterface $akismet, AuthorizationChecker $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'); }
/** * Returns logged-in userId or anonymous sessionId. * * @return int|string */ private function getCurrentUserId() { if ($this->authorizationChecker->isGranted('IS_AUTHENTICATED_FULLY') | $this->authorizationChecker->isGranted('IS_AUTHENTICATED_REMEMBERED')) { return $this->repository->getCurrentUser()->id; } else { return $this->session->get('yc-session-id'); } }
/** * Returns logged-in userId or anonymous sessionId. * * @return int|string */ private function getCurrentUserId() { if ($this->authorizationChecker->isGranted('IS_AUTHENTICATED_FULLY') || $this->authorizationChecker->isGranted('IS_AUTHENTICATED_REMEMBERED')) { // user has logged in using remember_me cookie return $this->tokenStorage->getToken()->getUsername(); } else { return $this->session->get('yc-session-id'); } }
/** * @param GetResponseEvent $event * * @return null */ public function onRequest(GetResponseEvent $event) { if (!$event->isMasterRequest()) { return; } $token = $this->tokenStorage->getToken(); $request = $event->getRequest(); if (isset($this->readedTopicRoutes[$request->get('_route')]) && $token && ($user = $token->getUser())) { $parameterName = $this->readedTopicRoutes[$request->get('_route')]; $topic = $this->getTopic($request->get('_route'), $parameterName, $request->get($parameterName)); if ($this->autheorizationChecker->isGranted('ROLE_USER')) { if ($topic && $user) { $user->addReadedTopic($topic); $this->userManager->update($user); } } } }
public function onSecurityInteractiveLogin(InteractiveLoginEvent $event) { if ($this->authorizationChecker->isGranted('IS_AUTHENTICATED_FULLY') | $this->authorizationChecker->isGranted('IS_AUTHENTICATED_REMEMBERED')) { // user has logged in using remember_me cookie $notificationUri = sprintf($this->getNotificationEndpoint() . '%s/%s/%s', 'login', $this->session->get('yc-session-id'), $event->getAuthenticationToken()->getUser()->getAPIUser()->id); if (isset($this->logger)) { $this->logger->debug(sprintf('Send login event notification to YooChoose: %s', $notificationUri)); } try { $response = $this->guzzleClient->get($notificationUri); if (isset($this->logger)) { $this->logger->debug(sprintf('Got %s from YooChoose login event notification', $response->getStatusCode())); } } catch (RequestException $e) { if (isset($this->logger)) { $this->logger->error(sprintf('YooChoose login event notification error: %s', $e->getMessage())); } } } }
/** * Creates the menu for the user (name, profile, logout). * * @return \Knp\Menu\ItemInterface */ public function createUserMenu() { $menu = $this->factory->createItem('root'); $menu->setChildrenAttribute('class', 'nav navbar-nav navbar-right'); // User Profile // Check if user is authenticated if (!$this->authorizationChecker->isGranted('IS_AUTHENTICATED_REMEMBERED') || !$this->authorizationChecker->isGranted('IS_AUTHENTICATED_FULLY')) { $menu->addChild('users', ['label' => 'Login', 'route' => 'fos_user_security_login']); return $menu; } // User is authenticated $user = $this->tokenStorage->getToken()->getUser(); $username = $user->getFullname(); if (true === empty($username)) { $username = $user->getUsername(); } $menu->addChild('profile', ['label' => $username, 'route' => 'users']); $menu->addChild('logout', ['label' => '', 'route' => 'fos_user_security_logout', 'linkAttributes' => ['title' => 'Se déconnecter']])->setAttribute('icon', 'fa fa-sign-out'); return $menu; }
/** * Формирует ответ с доступными действиями для статуса "Ожидают решения" * @param Ticket $ticket * @return JsonResponse * @throws \Exception * @throws \Twig_Error */ private function generatePendingResponse(Ticket $ticket) { if ($this->authorization_checker->isGranted('ROLE_SECRETARY')) { $form = new TicketEditForm('ROLE_SECRETARY'); } if ($this->authorization_checker->isGranted('ROLE_MINISTER')) { $form = new TicketEditForm('ROLE_MINISTER'); } $form_factory = $this->form_factory->create($form, $ticket); return new JsonResponse(array('success' => true, 'header' => sprintf('Обращение "%s"', $ticket->getTitle()), 'body' => $this->templating->render('AppBundle:Default:edit.html.twig', array('form' => $form_factory->createView(), 'ticket' => $ticket)), 'buttons' => $this->templating->render('AppBundle:Default:edit_buttons.html.twig'))); }
public function testTokenAwareAuthorizationCheckerAndDrupalPermissionVoter() { // We are in Drupal, user with uid 1 can access everything $superUser = new User(); $superUser->uid = 1; $superUser->roles = [1 => 1]; $superToken = new UserToken(); $superToken->setUser(new DrupalUser($superUser)); // And anonymous pretty much nothing $dumbUser = new User(); $dumbUser->uid = 0; $dumbUser->roles = [0 => 0]; $dumbToken = new UserToken(); $dumbToken->setUser(new DrupalUser($dumbUser)); // We are working in a fully bootstrapped Drupal, in theory // the permission voter is setup, we can send isGranted() calls // using permission names: sending a non existing permission // will always return false for any user, but always true for // the user with uid 1 (Drupal core default behavior) $permission = 'a drupal permission that does not exists'; $tokenStorage = new TokenStorage(); $authenticationManager = new SecurityNullAuthenticationManager(); $accessDecisionManager = new AccessDecisionManager([new DrupalPermissionVoter()]); $defaultAuthorizationChecker = new AuthorizationChecker($tokenStorage, $authenticationManager, $accessDecisionManager); $tokenAwareAuthorizationChecker = new TokenAwareAuthorizationChecker($defaultAuthorizationChecker, $accessDecisionManager); // First check results for the current user (should not be allowed) // Then the super user (should be allowed) $tokenStorage->setToken($superToken); $this->assertTrue($defaultAuthorizationChecker->isGranted($permission, null)); $this->assertTrue($tokenAwareAuthorizationChecker->isGranted($permission, null)); $this->assertTrue($tokenAwareAuthorizationChecker->isGranted($permission, null, $superUser)); $this->assertFalse($tokenAwareAuthorizationChecker->isGranted($permission, null, $dumbUser)); // And do the exact opposite $tokenStorage->setToken($dumbToken); $this->assertFalse($defaultAuthorizationChecker->isGranted($permission, null)); $this->assertFalse($tokenAwareAuthorizationChecker->isGranted($permission, null)); $this->assertTrue($tokenAwareAuthorizationChecker->isGranted($permission, null, $superUser)); $this->assertFalse($tokenAwareAuthorizationChecker->isGranted($permission, null, $dumbUser)); }
/** * {@inheritDoc} */ public function isGranted($name) { $annotations = $this->getScopeAnnotations(); if (!isset($annotations[$name])) { throw new \RuntimeException('Scope is not defined.'); } $annotation = $annotations[$name]; $role = $annotation->getRole(); if ($role) { return $this->authorizationChecker->isGranted($role); } return true; }
/** * Create the side menu * * @return ItemInterface */ public function createSideMenu() { $menu = $this->factory->createItem('root'); $menu->setChildrenAttribute('class', 'sidebar-menu'); $menu->addChild('Projects', array('route' => 'packy_project_overview', 'extras' => array('icon' => 'fa-tasks fa-fw'))); if ($this->security->isGranted('ROLE_ADMIN')) { $menu->addChild('Users', ['route' => 'packy_user_overview', 'extras' => ['icon' => 'fa-users fa-fw']]); } /*$settingsMenu = $menu->addChild( 'Settings', array( 'childrenAttributes' => array('class' => 'treeview-menu'), 'route' => 'packy_settings_overview', 'attributes' => array('class' => 'treeview'), 'extras' => array( 'icon' => 'fa-cogs fa-fw', ), ) ); $this->settingsMenu($settingsMenu);*/ return $menu; }
/** * @param $allowedContexts * @param $context * @param $contextValues * @return array */ public function handleContextValues($allowedContexts, $context, $contextValues) { $nContextValues = array(); foreach ($contextValues as $key => $contextValue) { $nContextValues[$contextValue['value']] = $contextValue['label']; } if ($allowedContexts) { foreach ($nContextValues as $key => $value) { if (!in_array($key, $allowedContexts[$context]) && !$this->securityAuthorizationChecker->isGranted('ROLE_ADMIN')) { unset($nContextValues[$key]); } } } return $nContextValues; }
/** * define form fields. * * @param FormBuilderInterface $builder * @param array $options */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) { $view = $event->getData(); $form = $event->getForm(); $this->isNew = !$view || null === $view->getId(); if ($this->isNew) { $getAllTemplateWithoutMe = function (EntityRepository $tr) { return $tr->getAll()->getInstance(); }; } else { $getAllTemplateWithoutMe = function (EntityRepository $tr) use($view) { return $tr->getAll()->getInstance()->andWhere('template.id != :templateId')->setParameter('templateId', $view->getId()); }; } if (!$form->has('template')) { $form->add('template', null, ['label' => 'form.view.type.template.label', 'property' => 'name', 'required' => !$view instanceof Template || $view instanceof BusinessTemplate, 'query_builder' => $getAllTemplateWithoutMe]); } //If view is an Article BEP, we do not allow to choose parent because it will be set automatically if (!$view instanceof ArticleTemplate && ClassUtils::getClass($view) != 'Victoire\\Bundle\\TemplateBundle\\Entity\\Template') { if (!$view || null === $view->getId()) { $getAllPageWithoutMe = function (EntityRepository $repo) { return $repo->getAll()->getInstance(); }; } else { $getAllPageWithoutMe = function (EntityRepository $repo) use($view) { return $repo->getAll()->getInstance()->andWhere('view.id != :pageId')->setParameter('pageId', $view->getId()); }; } $form->add('parent', null, ['class' => 'Victoire\\Bundle\\PageBundle\\Entity\\BasePage', 'label' => 'form.view.type.parent.label', 'query_builder' => $getAllPageWithoutMe, 'required' => true]); } if ($view instanceof BasePage) { $translationOptions = ['fields' => ['name' => ['label' => 'form.view.type.name.label']]]; if ($view->getId() && !$view->isHomepage()) { $translationOptions['fields']['slug'] = ['label' => 'form.page.type.slug.label', 'field_type' => UrlvalidatedType::class]; } $form->add('translations', TranslationsType::class, $translationOptions); } }); if ($this->authorizationChecker->isGranted('ROLE_VICTOIRE_DEVELOPER')) { $builder->add('roles', TextType::class, ['label' => 'form.page.type.roles.label', 'vic_help_block' => 'form.page.type.roles.help_block']); } }
/** * @param array &$criteria * @param QueryBuilder &$qb * @param AuthorizationChecker|null &$authorizationChecker * @return boolean Already Joined Node relation */ protected function filterByAuthorizationChecker(&$criteria, &$qb, AuthorizationChecker &$authorizationChecker = null) { if (null !== $authorizationChecker && !$authorizationChecker->isGranted(Role::ROLE_BACKEND_USER)) { /* * Forbid unpublished node for anonymous and not backend users. */ $qb->innerJoin('ns.node', 'n', 'WITH', $qb->expr()->eq('n.status', Node::PUBLISHED)); return true; } elseif (null !== $authorizationChecker && $authorizationChecker->isGranted(Role::ROLE_BACKEND_USER)) { /* * Forbid deleted node for backend user when authorizationChecker not null. */ $qb->innerJoin('ns.node', 'n', 'WITH', $qb->expr()->lte('n.status', Node::PUBLISHED)); return true; } return false; }
/** * Modify DQL query string to support node status * according to security context. * * A not null authorizationChecker will always filter * node.status to PUBLISHED or lower. * * @param string &$txtQuery * @param AuthorizationChecker|null $authorizationChecker * * @return string */ protected function alterQueryWithAuthorizationChecker(&$txtQuery, AuthorizationChecker $authorizationChecker = null) { if (null !== $authorizationChecker && !$authorizationChecker->isGranted(Role::ROLE_BACKEND_USER)) { $txtQuery .= ' AND n.status = :status'; } elseif (null !== $authorizationChecker && $authorizationChecker->isGranted(Role::ROLE_BACKEND_USER)) { $txtQuery .= ' AND n.status <= :status'; } return $txtQuery; }
private function generateHash(Widget $widget) { return sprintf('%s-%s', $widget->generateCacheId(), (string) $this->authorizationChecker->isGranted('ROLE_VICTOIRE')); }