如何在fosuserbundle中保护Symfony项目的URL?

时间:2014-12-05 06:01:33

标签: php forms symfony

我是Symfony2的新手并使用fosuserbundle
我使用fosuserbundle创建了一个小项目,其中包含注册,登录,2个表单,包括单选按钮,用于在登录或注册后选择和提交以及注销
问题是after a person logs outif he/she types in the url of the form say (link for the first form of the project)(link for the second form of the project) then the forms display !!!!
我想保护这些链接并仅在用户登录时显示这些链接。

    routing.yml

  InstituteProjectevents_student_homepage:
 path:     /hello/{name}
 defaults: { _controller: InstituteProject:Default:index }

 InstituteProjectevents_student_formpage:
 path: /form
 defaults: { _controller: InstituteProject:Default:form } 

 InstituteProjectevents_student_form:
 path: /forms
 defaults: { _controller: InstituteProject:Default:billboard }     

 InstituteProjectevents_student_eventsdayonedisplay:
 path: /eventsdayonedisplay
 defaults: { _controller: InstituteProject:Default:eventsdayonedisplay } 

 InstituteProjectevents_student_eventsdaytwodisplay:
 path: /eventsdaytwodisplay
 defaults: { _controller: InstituteProject:Default:eventsdaytwodisplay }  

 InstituteProjectevents_student_eventsregistered:
 path: /eventsregistered
 defaults: { _controller: InstituteProject:Default:eventsregistered }    

 fos_user_security_login:
 path: /login
 defaults: { _controller: InstituteProject:Security:login }

 fos_user_security_check:
 path: /login_check
 defaults: { _controller: InstituteProject:Security:check }

 fos_user_security_logout:
 path: /logout
 defaults: { _controller: InstituteProject:Security:logout } 

 fos_user_profile_show:
 path: /
 defaults: { _controller: InstituteProject:Profile:show }

 fos_user_profile_edit:
 path: /edit
 defaults: { _controller: InstituteProject:Profile:edit } 

 fos_user_registration_register:
 path: /
 defaults: { _controller: InstituteProject:Registration:register }

fos_user_registration_check_email:
path: /check-email
defaults: { _controller: InstituteProject:Registration:checkEmail }

fos_user_registration_confirm:
path: /confirm/{token}
defaults: { _controller: InstituteProject:Registration:confirm }

fos_user_registration_confirmed:
path: /confirmed
defaults: { _controller: InstituteProject:Registration:confirmed }

  Security.yml

# app/config/security.yml
security:
encoders:
    FOS\UserBundle\Model\UserInterface: sha512

role_hierarchy:
    ROLE_ADMIN:       ROLE_USER
    ROLE_SUPER_ADMIN: ROLE_ADMIN

providers:
    fos_userbundle:
        id: fos_user.user_provider.username

firewalls:
    main:
        pattern: ^/
        form_login:
            provider: fos_userbundle
            csrf_provider: form.csrf_provider
            default_target_path: /forms
        logout:       
          path: fos_user_security_logout
          target: fos_user_security_login
        anonymous:    true

access_control:
    - { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/admin/, role: ROLE_ADMIN }

   RegistrationController.php

 <?php

/*
 * This file is part of the FOSUserBundle package.
 *
 * (c) FriendsOfSymfony <http://friendsofsymfony.github.com/>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace InstituteProjecteventsBundle\Controller;

use FOS\UserBundle\FOSUserEvents;
use FOS\UserBundle\Event\FormEvent;
use FOS\UserBundle\Event\GetResponseUserEvent;
use FOS\UserBundle\Event\FilterUserResponseEvent;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use FOS\UserBundle\Model\UserInterface;

/**
 * Controller managing the registration
 *
 * @author Thibault Duplessis <thibault.duplessis@gmail.com>
 * @author Christophe Coevoet <stof@notk.org>
 */

class RegistrationController extends Controller
{
public function registerAction(Request $request)
{
    /** @var $formFactory \FOS\UserBundle\Form\Factory\FactoryInterface */
    $formFactory = $this->get('fos_user.registration.form.factory');
    /** @var $userManager \FOS\UserBundle\Model\UserManagerInterface */
    $userManager = $this->get('fos_user.user_manager');
    /** @var $dispatcher \Symfony\Component\EventDispatcher\EventDispatcherInterface */
    $dispatcher = $this->get('event_dispatcher');

    $user = $userManager->createUser();
    $user->setEnabled(true);

    $event = new GetResponseUserEvent($user, $request);
    $dispatcher->dispatch(FOSUserEvents::REGISTRATION_INITIALIZE, $event);

    if (null !== $event->getResponse()) {
        return $event->getResponse();
    }

    $form = $formFactory->createForm();
    $form->setData($user);

    $form->handleRequest($request);

    if ($form->isValid()) {
        $event = new FormEvent($form, $request);
        $dispatcher->dispatch(FOSUserEvents::REGISTRATION_SUCCESS, $event);

        $userManager->updateUser($user);

        if (null === $response = $event->getResponse()) {
            $url = $this->generateUrl('fos_user_registration_confirmed');
            $response = new RedirectResponse($url);
        }

        $dispatcher->dispatch(FOSUserEvents::REGISTRATION_COMPLETED, new FilterUserResponseEvent($user, $request, $response));

        return $response;
    }

    return $this->render('FOSUserBundle:Registration:register.html.twig', array(
        'form' => $form->createView(),
    ));
}

/**
 * Tell the user to check his email provider
 */
public function checkEmailAction()
{
    $email = $this->get('session')->get('fos_user_send_confirmation_email/email');
    $this->get('session')->remove('fos_user_send_confirmation_email/email');
    $user = $this->get('fos_user.user_manager')->findUserByEmail($email);

    if (null === $user) {
        throw new NotFoundHttpException(sprintf('The user with email "%s" does not exist', $email));
    }

    return $this->render('FOSUserBundle:Registration:checkEmail.html.twig', array(
        'user' => $user,
    ));
}

/**
 * Receive the confirmation token from user email provider, login the user
 */
public function confirmAction(Request $request, $token)
{
    /** @var $userManager \FOS\UserBundle\Model\UserManagerInterface */
    $userManager = $this->get('fos_user.user_manager');

    $user = $userManager->findUserByConfirmationToken($token);

    if (null === $user) {
        throw new NotFoundHttpException(sprintf('The user with confirmation token "%s" does not exist', $token));
    }

    /** @var $dispatcher \Symfony\Component\EventDispatcher\EventDispatcherInterface */
    $dispatcher = $this->get('event_dispatcher');

    $user->setConfirmationToken(null);
    $user->setEnabled(true);

    $event = new GetResponseUserEvent($user, $request);
    $dispatcher->dispatch(FOSUserEvents::REGISTRATION_CONFIRM, $event);

    $userManager->updateUser($user);

    if (null === $response = $event->getResponse()) {
        $url = $this->generateUrl('fos_user_registration_confirmed');
        $response = new RedirectResponse($url);
    }

    $dispatcher->dispatch(FOSUserEvents::REGISTRATION_CONFIRMED, new FilterUserResponseEvent($user, $request, $response));

    return $response;
}

/**
 * Tell the user his account is now confirmed
 */
public function confirmedAction()
{
    $user = $this->getUser();
    if (!is_object($user) || !$user instanceof UserInterface) {
        throw new AccessDeniedException('This user does not have access to this section.');
    }

    //Get current time and date

    date_default_timezone_set('Europe/Paris');
    $current_date = date('Y/m/d h:i:s a', time());

    //Set expiration date

    $deadline1 = $this->container->getParameter('deadline_day1');
    $date = date_create($deadline1, timezone_open("Europe/Paris"));

    if ($current_date > date_format($date, "Y/m/d h:i:s a")) {
        return $this->render('InstituteProject:Default:registrationsclosed.html.twig');
    }
    return $this->render('InstituteProject:Default:confirmed.html.twig', array(
        'user' => $user,
    ));
}
}

1 个答案:

答案 0 :(得分:2)

您需要在security.yml个文件access_control部分添加这两个路径,如下所示,

浏览This Documentation,详细了解它在Symfony2中的工作原理

ACL中的

ROLE_ADMINROLE_USER表示您需要登录才能访问该路径。

access_control:
    - { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/admin/, role: ROLE_ADMIN }
    - { path: ^/eventsdayonedisplay, role: ROLE_ADMIN }  # you can change user role to ROLE_USER as per your requirement
    - { path: ^/eventsdaytwodisplay, role: ROLE_ADMIN }

我还建议您添加路由/events/day1/events/day2

这样您只需在access_control中添加一个条目,

- { path: ^/events/, role: ROLE_ADMIN }