注册FOSUser Bundle后,Symfony2自动登录

时间:2014-01-15 06:18:54

标签: security symfony fosuserbundle

我正在尝试使用symfony2和FOSUserBundle进行自动登录。 我想做像用户注册然后转到下一页(ProfileController-editAction())并填写一些用户表单然后完成。

我已经做了这个,但我们在注册后需要用户配置文件编辑的每个页面密码,我希望这没有密码我怎么能这样做?

我遇到了这个问题,因为个人资料编辑操作仅在用户登录

时有效

Security.yml

parameters:
    security.acl.permission.map.class:   Sonata\AdminBundle\Security\Acl\Permission\AdminPermissionMap
security:
    encoders:
        FOS\UserBundle\Model\UserInterface: sha512

role_hierarchy:
    ROLE_ADMIN:       ROLE_USER
    ROLE_SUPER_ADMIN: [ROLE_USER, ROLE_SONATA_ADMIN, ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH]
    ROLE_ADMIN_GUEST: [ROLE_SONATA_ADMIN_MTCATEGORY_GUEST, ROLE_SONATA_ADMIN_MTBRAND_GUEST, ROLE_SONATA_ADMIN_MTSERIES_GUEST]
    SONATA:
        - ROLE_SONATA_PAGE_ADMIN_PAGE_EDIT  # if you are not using acl then this line must be uncommented

providers:
    fos_userbundle:
        id: fos_user.user_provider.username_email

    my_fos_facebook_provider:
        id: my.facebook.user   # see "Example Custom User Provider using the FOS\UserBundle" chapter further down

firewalls:
    admin:
        pattern:      /admin(.*)
        form_login:
            provider:       fos_userbundle
            login_path:     /admin/login
            use_forward:    false
            check_path:     /admin/login_check
            failure_path:   null
        logout:
            path:           /admin/logout
        anonymous:    true

    main:
        pattern:      .*
        form_login:
            success_handler: security.authentication.customized_success_handler
            failure_handler: security.authentication.customized_success_handler
            provider:       fos_userbundle
            login_path:     /login
            use_forward:    false
            check_path:     /login_check
            failure_path:   null
        oauth:
            resource_owners:
                facebook:    /login/check-facebook
                twitter:     /login/check-twitter
                google:      /login/check-google
            login_path:        /login
            failure_path:      /login
            default_target_path: /profile
            oauth_user_provider: 
                service: my_user_provider

        fos_facebook:
            app_url: "http://apps.facebook.com/appName/"
            server_url: "http://localhost/facebookApp/"
            login_path: /login
            check_path: /login_fb_check
            default_target_path: /
            provider: my_fos_facebook_provider
        logout:
            invalidate_session: false
        anonymous:    true

access_control:
    - { path: ^/_wdt, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/_profiler, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/admin/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/admin/logout$, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/admin/login-check$, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/admin, role: [ROLE_ADMIN, ROLE_SONATA_ADMIN, ROLE_ADMIN_GUEST] }
    - { path: ^/.*, role: IS_AUTHENTICATED_ANONYMOUSLY }

acl:
    connection: default

RegisterationController.php

 <?php
 namespace XXX\UserBundle\Controller;

use Symfony\Component\DependencyInjection\ContainerAware;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Core\Exception\AccountStatusException;
use FOS\UserBundle\Model\UserInterface;

/**
 * Controller managing the registration
 *
 * @author Siddharth Singh <Siddharth.find@gmail.com>
 */
class RegistrationController extends ContainerAware
{
public function registerAction(Request $request)
{
    $form = $this->container->get('fos_user.registration.form');
    $formHandler = $this->container->get('fos_user.registration.form.handler');
    $confirmationEnabled = $this->container->getParameter('fos_user.registration.confirmation.enabled');

    $process = $formHandler->process($confirmationEnabled);
    if ($request->isXmlHttpRequest()) {
  //  echo 'test->',$process;
        if ($process) {
            $user = $form->getData();
            $authUser = false;
            if ($confirmationEnabled) {
                $this->container->get('session')->set('fos_user_send_confirmation_email/email', $user->getEmail());
                $result = array('success' => false);
            } else {
                $authUser = true;
                $result = array('success' => true);
            }
            $response = new Response(json_encode($result));
            $response->headers->set('Content-Type', 'application/json');
            //return $response;
            if ($authUser) {
                $this->authenticateUser($user, $response);
            }
            return $response;
        }
        $result = array('success' => false);
        $response = new Response(json_encode($result));
        $response->headers->set('Content-Type', 'application/json');
        return $response;
    }

    return $this->container->get('templating')->renderResponse('XXXUserBundle:Registration:register.html.'.$this->getEngine(), array(
        'form' => $form->createView(),
    ));
}

/**
 * Tell the user to check his email provider
 */
public function checkEmailAction()
{
    $email = $this->container->get('session')->get('fos_user_send_confirmation_email/email');
    $this->container->get('session')->remove('fos_user_send_confirmation_email/email');
    $user = $this->container->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->container->get('templating')->renderResponse('XXXUserBundle:Registration:checkEmail.html.'.$this->getEngine(), array(
        'user' => $user,
    ));
}

/**
 * Receive the confirmation token from user email provider, login the user
 */
public function confirmAction($token)
{
    $user = $this->container->get('fos_user.user_manager')->findUserByConfirmationToken($token);

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

    $user->setConfirmationToken(null);
    $user->setEnabled(true);
    $user->setLastLogin(new \DateTime());

    $this->container->get('fos_user.user_manager')->updateUser($user);
    $response = new RedirectResponse($this->container->get('router')->generate('fos_user_registration_confirmed'));
    $this->authenticateUser($user, $response);

    return $response;
}

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

    return $this->container->get('templating')->renderResponse('XXXUserBundle:Registration:confirmed.html.'.$this->getEngine(), array(
        'user' => $user,
    ));
}

/**
 * Authenticate a user with Symfony Security
 *
 * @param \FOS\UserBundle\Model\UserInterface        $user
 * @param \Symfony\Component\HttpFoundation\Response $response
 */
protected function authenticateUser(UserInterface $user, Response $response)
{
    try {
        $this->container->get('fos_user.security.login_manager')->loginUser(
            $this->container->getParameter('fos_user.firewall_name'),
            $user,
            $response);
    } catch (AccountStatusException $ex) {
        // We simply do not authenticate users which do not pass the user
        // checker (not enabled, expired, etc.).
    }
}

/**
 * @param string $action
 * @param string $value
 */
protected function setFlash($action, $value)
{
    $this->container->get('session')->getFlashBag()->set($action, $value);
}

protected function getEngine()
{
    return $this->container->getParameter('fos_user.template.engine');
}
}

ProfileController.php

<?php
namespace XXX\UserBundle\Controller;

use Symfony\Component\DependencyInjection\ContainerAware;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use FOS\UserBundle\Model\UserInterface;
use Hip\MandrillBundle\Message;
use Hip\MandrillBundle\Dispatcher;

/**
 * Controller managing the user profile
 *
 * @author Siddharth Singh <siddharth.find@gmail.com>
 */
class ProfileController extends ContainerAware
{
/**
 * Show the user
 */
public function showAction()
{
    $user = $this->container->get('security.context')->getToken()->getUser();
    if (!is_object($user) || !$user instanceof UserInterface) {
        throw new AccessDeniedException('This user does not have access to this section.');
    }

    return $this->container->get('templating')->renderResponse('XXXUserBundle:Profile:show.html.'.$this->container->getParameter('fos_user.template.engine'), array('user' => $user));
}

/**
 * Edit the user
 */
public function editAction()
{
    $user = $this->container->get('security.context')->getToken()->getUser();
    if (!is_object($user) || !$user instanceof UserInterface) {
        throw new AccessDeniedException('This user does not have access to this section.');
    }

    $form = $this->container->get('fos_user.profile.form');
    $formHandler = $this->container->get('fos_user.profile.form.handler');

    $process = $formHandler->process($user);
    if ($process) {
        $this->setFlash('fos_user_success', 'profile.flash.updated');
        $route = 'fos_user_profile_pro';
        $url = $this->container->get('router')->generate($route);
        $response = new RedirectResponse($url);
        return $response;
    }

    return $this->container->get('templating')->renderResponse(
        'XXXUserBundle:Profile:edit.html.'.$this->container->getParameter('fos_user.template.engine'),
        array('form' => $form->createView())
    );
}

/**
 * Complete the user profile
 */
public function proAction()
{
    $user = $this->container->get('security.context')->getToken()->getUser();
    if (!is_object($user) || !$user instanceof UserInterface) {
        throw new AccessDeniedException('This user does not have access to this section.');
    }

    $form = $this->container->get('fos_user.profile.form');
    $formHandler = $this->container->get('fos_user.profile.form.handler');

    $process = $formHandler->process($user);
    if ($process) {
        $this->setFlash('fos_user_success', 'profile.flash.updated');

        return new RedirectResponse($this->getRedirectionUrl($user));
    }

    return $this->container->get('templating')->renderResponse(
        'XXXUserBundle:Profile:profile.html.'.$this->container->getParameter('fos_user.template.engine'),
        array('form' => $form->createView())
    );
}

/**
 * Generate the redirection url when editing is completed.
 *
 * @param \FOS\UserBundle\Model\UserInterface $user
 *
 * @return string
 */
protected function getRedirectionUrl(UserInterface $user)
{
    return $this->container->get('router')->generate('fos_user_profile_show');
}

/**
 * @param string $action
 * @param string $value
 */
protected function setFlash($action, $value)
{
    $this->container->get('session')->getFlashBag()->set($action, $value);
}
}

0 个答案:

没有答案