0

I want to change roles when I login, so I have a form inside my controller to log me in and a provider for my user class, but I am really lost. I've been looking several tutoriel on symfony website but I still don't have a clue how to do it. So before I login, I am authenticated as anon on the symfony toolbar. But when I login, I am not authenticated, but I see my username on the toolbar. Can you tell me what tutoriel do I need to see? I just could not see clearly how to authenticated, and I've been searching for hours... Here is my form inside my controller :

public function indexAction(Request $request)
    {
        $player = new Player;

        $form = $this->createFormBuilder($player)
        ->add('email', TextType::class, array('label' => 'Email :'))
        ->add('password', PasswordType::class, array('label' => 'Mot de passe :'))
        ->add('login', SubmitType::class, array('label' => 'Login'))
        ->getForm();

        $form->handleRequest($request);



        if($form->isSubmitted() && $form->isValid())
        {
            $password = $form['password']->getData();
            $email = $form['email']->getData();
            $encoded_pass = sha1($form['password']->getData());
            $date = date_create();
            /*
                Recherche dans la base de données si les différents éléments entrés
                sont présents afin de connecter la personne
            */
            $player = $this->getDoctrine()
                         ->getRepository('AppBundle:Player')
                         ->findOneByEmail($email);
            $pass_check = $this->getDoctrine()
                         ->getRepository('AppBundle:Player')
                         ->findByPassword($encoded_pass);

            if(!$player)
            {
                return $this->redirectToRoute('registration');
            }
            else
            {
                $pseudo = $this->getDoctrine()
                    ->getRepository('AppBundle:Player')
                    ->findOneByEmail($email)->getPseudo();
                /* Met à jour la date de connection */
                $player->setDateLog($date);
                /* Entre les différents élements dans la base */
                $em = $this->getDoctrine()->getManager();
                $em->persist($player); // prépare l'insertion dans la BD
                $em->flush(); // insère dans la BD


                $token = new UsernamePasswordToken($player, $player->getPassword(), "main", $player->getRoles());

                $event = new InteractiveLoginEvent(new Request(), $token);

                $this->container->get("event_dispatcher")->dispatch("security.interactive_login", $event);

                $this->container->get("security.token_storage")->setToken($token);

                return $this->redirectToRoute('accueil',  array('pseudo' => $pseudo));
            }
        }

        return $this->render('Sko/menu.html.twig', array('form' => $form->createView()));
        // En plus renvoyer la balise
    }

Then I have my provider :

<?php
namespace AppBundle\Security;

use AppBundle\Entity\Player;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;

class PlayerProvider implements UserProviderInterface
{
 protected $doctrine;
 public function __construct(\Doctrine\Bundle\DoctrineBundle\Registry $doctrine){
        $this->doctrine = $doctrine;
    }

 public function loadUserByUsername($username)
    {
        // make a call to your webservice here
        $player = new Player();
        $player = $this->doctrine
                         ->getRepository('AppBundle:Player')
                         ->findOneByPseudo($username);
        // pretend it returns an array on success, false if there is no user

        if ($player) {
            $password = $player->getPassword();
            $salt = $player->getSalt();
            $roles = $player->getRoles();
            return $player;
        }

        throw new UsernameNotFoundException(
            sprintf('Username "%s" does not exist.', $username)
        );
    }

    public function refreshUser(UserInterface $user)
    {
        if (!$user instanceof Player) {
            throw new UnsupportedUserException(
                sprintf('Instances of "%s" are not supported.', get_class($user))
            );
        }

        return $this->loadUserByUsername($user->getPseudo());
    }

    public function supportsClass($class)
    {
        return Player::class === $class;
    }

}



?>

Thank for your help

EDIT : In Symfony Profiler, my roles are ['ROLE_USER'] like intended when I login

frlan
  • 6,950
  • 3
  • 31
  • 72
Zul Huky
  • 331
  • 4
  • 24
  • Roles are joined to users. So for example Alex has ROLE_USER and Jim has ROLE_USER and ROLE_ADMIN. In this case Jim has administrator privileges. If you like you can make an edit form for users that is only accessible by administrators to change the available roles for certain user. – Frank B May 01 '17 at 12:59
  • But how can I put "Authenticated" to "Yes" when I login? It is set to "No" after I login and I am not anonymous anymore – Zul Huky May 01 '17 at 13:04
  • 1
    this statck answer will help : http://stackoverflow.com/questions/13798662/when-are-user-roles-refreshed-and-how-to-force-it – Hiren Makwana May 01 '17 at 13:06
  • 1
    its probably showing you are not "Authenticated" because the url you are accessing does not need to be accessed by the authenticated user. Try to access the URL where a user must be logged in and it with then tell you that you are authenticated. – Shairyar May 01 '17 at 13:21

0 Answers0