Salut, j'ai créer une application mobile avec jquery mobile et une application web avec symfony2. Je suis entrain d'utiliser FosUserBundle et FosRestBundle. J'ai développé une api pour permettre à l'app mobile de communiqué avec celle du web. Le problème c'est que j'ai pas trouvé comment utiliser FosUserBundle(login and registration) comme service afin que l'app mobile les utilisent. Est ce que vous avez une idée comment le faire? Merci.

1 réponse


iMacode
Réponse acceptée

Salut !

Je ne sais pas si tu es encore bloqué mais j'ai trouvé une solution pour un projet similaire qui demandais une application mobile, donc une API pour pouvoir le faire.

Voici la fonction de UserController.php pour l'inscription, évidemment tu devras l'adapté avec les paramètres dont tu as besoin :

    public function registrationAction($version)
    {
        $request = $this->getRequest();
        $format = $request->getRequestFormat();

        if ($version == "1.0.0") {

            $class = $this->container->getParameter('fos_user.model.user.class');
            $form = $this->container->get('form.factory')->create(new RegistrationFormType($this->container, $class));

            /** @var $userManager \FOS\UserBundle\Model\UserManagerInterface */
            $userManager = $this->container->get('fos_user.user_manager');
            /** @var $dispatcher \Symfony\Component\EventDispatcher\EventDispatcherInterface */
            $dispatcher = $this->container->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->setData($user);

            if ('POST' === $request->getMethod()) {

                $form->bind($request);

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

                    $name = $request->get("name");
                    $firstname = $request->get("firstname");
                    $username = $request->get("username");
                    $email["first"] = $request->get("plainEmail")["first"];
                    $email["second"] = $request->get("plainEmail")["second"];
                    $password["first"] = $request->get("plainPassword")["first"];
                    $password["second"] = $request->get("plainPassword")["second"];
                    $locale = $request->get('locale');

                    $test = $this->getDoctrine()->getManager()->getRepository('ProjectApiBundle:User')->findByEmail($email["first"]);

                    if (empty($test)) {

                        if (!empty($name) && !empty($firstname) && !empty($username) && !empty($email["first"]) && !empty($email["second"]) && !empty($password["first"]) && !empty($password["second"]) && !empty($locale)) {

                            if ($email["first"] == $email["second"]) {

                                if ($password["first"] == $password["second"]) {

                                    $user->setUsername($username);
                                    $user->setName($firstname .' '. $name);
                                    $user->setEmail($email["first"]);
                                    $user->setPlainPassword($password["first"]);
                                    $user->setLocale($locale);

                                    $userManager->updateUser($user);

                                    $this->loginUser($user);

                                    $message['status'] = "ok";
                                    $message['message'] = "The user has been created.";
                                    $message['object'] = $user;

                                } else {
                                    $message['status'] = "fail";
                                    $message['message'] = "The password and the confirmation password does not match.";
                                }

                            } else {
                                $message['status'] = "fail";
                                $message['message'] = "The email and the confirmation email does not match.";
                            }

                        } else {
                            $message['status'] = "fail";
                            $message['message'] = "Missing parameters.";
                        }

                    } else {
                        $message['status'] = "fail";
                        $message['message'] = "The email " . $email['first'] . " has already registered in database.";
                    }

                } else {
                    $message['status'] = "fail";
                    $message['message'] = "Something wrong with the form.";
                }

            } else {
                $message['status'] = "fail";
                $message['message'] = "The request is not in POST Method.";
            }

        } else {
            $message['status'] = "fail";
            $message['message'] = "The version " . $version . " of this API does not exist.";
        }

        return new Response($this->get('jms_serializer')->serialize($message, $format));
    }

Pour la partie connexion il y a un peu plus de choses à faire :

    protected function getUserManager()
    {
        return $this->get('fos_user.user_manager');
    }

    protected function loginUser(User $user)
    {
        $security = $this->get('security.context');
        $providerKey = $this->container->getParameter('fos_user.firewall_name');
        $roles = $user->getRoles();
        $token = new UsernamePasswordToken($user, null, $providerKey, $roles);
        $security->setToken($token);
    }

    protected function logoutUser()
    {
        $security = $this->get('security.context');
        $token = new AnonymousToken(null, new User());
        $security->setToken($token);
        $this->get('session')->invalidate();
    }

    protected function checkUserPassword(User $user, $password)
    {
        $factory = $this->get('security.encoder_factory');
        $encoder = $factory->getEncoder($user);
        if(!$encoder){
            return false;
        }
        return $encoder->isPasswordValid($user->getPassword(), $password, $user->getSalt());
    }

    public function loginAction()
    {
        $format = $this->getRequest()->getRequestFormat();
        $request = $this->getRequest();
        $username = $request->get('_username');
        $password = $request->get('_password');

        $user = $this->getDoctrine()
                     ->getManager()
                     ->getRepository("ProjectApiBundle:User")
                     ->findByUsername($username);

        if(!$user){
            $user = $this->getDoctrine()
                         ->getManager()
                         ->getRepository("ProjectApiBundle:User")
                         ->findByEmail($username);
        }

        if(!$user instanceof User){ // User not found
            $message['status'] = 'FAIL';
            $message['error'] = 'User not found';
            return new Response($this->get('jms_serializer')->serialize($message, $format));
        }

        if(!$this->checkUserPassword($user, $password)){ // Wrong password
            $message['status'] = 'FAIL';
            $message['error'] = 'Bad password';
            return new Response($this->get('jms_serializer')->serialize($message, $format));
        }

        $this->loginUser($user);

        return new Response($this->get('jms_serializer')->serialize($user, $format));
    }

J'utilises JMSSerializerBundle pour transformer les données en JSON ou XML selon le format de l'URL demandé.

J'espère que ça te sera utile :-)