I have a symfony 3.4 application and i'm using the fosuser bundle.I did the login and register to my application.I have two issues i want the newly registred user to be automatically logged and in the process of authentification depending on the role of the user (ROLE_ADMIN or ROLE_USER) to be directed to a desired route (backoffice and frontoffice routes) this is my config.yml code(the fosuser part):

fos_user:
db_driver: orm # other valid values are 'mongodb' and 'couchdb'
firewall_name: main
user_class: AppBundle\Entity\User
service:
  mailer: fos_user.mailer.twig_swift
from_email:
  address: "[email protected]"
  sender_name: "youssef"

this is my file security.yml code.

security:
encoders:
    FOS\UserBundle\Model\UserInterface: bcrypt

role_hierarchy:
    ROLE_CLIENT:       ROLE_USER
    ROLE_FOURNISSEUR:  ROLE_ADMIN
    ROLE_SUPER_ADMIN: ROLE_ADMIN

providers:
    fos_userbundle:
        id: fos_user.user_provider.username

firewalls:
    main:
        pattern: ^/
        form_login:
            provider: fos_userbundle
            csrf_token_generator: security.csrf.token_manager
            # if you are using Symfony < 2.8, use the following config instead:
            # csrf_provider: form.csrf_provider

        logout:       true
        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 }
    - { path: ^/, role: ROLE_USER }

this is my register function:

public function registerAction(Request $request)
{
    $user = $this->userManager->createUser();
    $user->setEnabled(true);

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

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

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

    $form->handleRequest($request);

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

            $this->userManager->updateUser($user);

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

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

            return $response;
        }

        $event = new FormEvent($form, $request);
        $this->eventDispatcher->dispatch(FOSUserEvents::REGISTRATION_FAILURE, $event);

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

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

and finally this is my login function:

public function loginAction(Request $request)
{
    if ($this->container->get('security.authorization_checker')->isGranted('ROLE_USER')) {
        return new RedirectResponse('event/index');
    }
    /** @var $session Session */
    $session = $request->getSession();

    $authErrorKey = Security::AUTHENTICATION_ERROR;
    $lastUsernameKey = Security::LAST_USERNAME;

    // get the error if any (works with forward and redirect -- see below)
    if ($request->attributes->has($authErrorKey)) {
        $error = $request->attributes->get($authErrorKey);
    } elseif (null !== $session && $session->has($authErrorKey)) {
        $error = $session->get($authErrorKey);
        $session->remove($authErrorKey);
    } else {
        $error = null;
    }

    if (!$error instanceof AuthenticationException) {
        $error = null; // The value does not come from the security component.
    }

    // last username entered by the user
    $lastUsername = (null === $session) ? '' : $session->get($lastUsernameKey);

    $csrfToken = $this->tokenManager
        ? $this->tokenManager->getToken('authenticate')->getValue()
        : null;

    return $this->renderLogin(array(
        'last_username' => $lastUsername,
        'error' => $error,
        'csrf_token' => $csrfToken,
    ));
}

I already tested the login and register functions and they work perfectly.

1 Answers

0
meet vasava On

Refer following document:

https://symfonycasts.com/screencast/symfony3-security/automatic-login-handling

Where you can read useful information.