Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FosUserBundle integration with FosRestBundle

Does anyone have an example or any idea how one would implement the FOSRestBundle together along with the FOSUserBundle. I have a Web app already developed with Symfony 2 and the FOSUserBundle, but I would like to add the FOSRestBundle for an api layer. I want to be able to pass it a username and password and receive some type of token from the FOSUserBundle that represents the logged in user that I can then pass and forth between other api calls. Does anyone know of a good way to do this?

like image 307
jini Avatar asked May 15 '12 18:05

jini


1 Answers

FOSUserBundle should be natively "restful" meaning that it may follow the REST recommandations.

However, it is not designed to work natively with FOSRestBundle, the simplest way to do that is to override the UsersController in your Bundle and adapt your actions.

For example, to allow RESTFul registration, you may write the following action:

    public function postUsersAction()
    {
        $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 ($process) {
            $user = $form->getData();
            $authUser = false;

            if ($confirmationEnabled) {
            } else {
                $authUser = true;
            }

            $response = new Response();

            if ($authUser) {
                /* @todo Implement authentication */
                //$this->authenticateUser($user, $response);
            }

            $response->setStatusCode(Codes::HTTP_CREATED);
            $response->headers->set(
                'Location',
                $this->generateUrl(
                    'api_users_get_user',
                    array('user' => $user->getId()),
                    true
                )
            );

            return $response;
        }

        return RestView::create($form, Codes::HTTP_BAD_REQUEST);
    }
like image 153
Boris Guéry Avatar answered Oct 07 '22 11:10

Boris Guéry