简体   繁体   English

使用FOSRestBundle REST API设置注册FOSUserBundle

[英]Set up registration FOSUserBundle with FOSRestBundle REST API

Problem fixed, check my answer. 问题已解决,请检查我的答案。

I'm building a registration endpoint on my Symfony2.7 rest api. 我正在我的Symfony2.7 rest api上建立一个注册端点。 I am using FosRestBundle and FosUserBundle 我正在使用FosRestBundle和FosUserBundle

Here is the user model : 这是用户模型:

<?php

namespace AppBundle\Entity;

use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="fos_user")
 */
class User extends BaseUser {

    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;






    public function __construct() {
        parent::__construct();
        // your own logic
    }

}

\\ Here is the UserType form : \\ \\ 这是UserType表单: \\

class UserType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('email', 'email')
            ->add('username', null)
            ->add('plainPassword', 'repeated', array(
                'type' => 'password',

                'first_options' => array('label' => 'password'),
                'second_options' => array('label' => 'password_confirmation'),

            ))
        ;
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\User',
            'csrf_protection'   => false,
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'user';
    }
}

And this the post user controller : 而这个帖子用户控制器:

public function postUserAction(\Symfony\Component\HttpFoundation\Request $request) {
        $user = new \AppBundle\Entity\User();
        $form = $this->createForm(new \AppBundle\Form\UserType(), $user);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($user);
            $em->flush();


            $view = $this->view(array('token'=>$this->get("lexik_jwt_authentication.jwt_manager")->create($user)), Codes::HTTP_CREATED);

            return $this->handleView($view);

        }

        return array(
            'form' => $form,
        );
    }

The problem is that when i submit wrong information, or empty information, the server return a bad formated 500 error with doctrine / mysql details of null value for not null row in state of a json response with the list of bad formated entries. 问题是,当我提交错误的信息或空信息时,服务器返回一个错误的格式化500错误,其中带有错误格式化条目列表的json响应状态中非空行的空值的doctrine / mysql详细信息。

Any idea on how to fix this behaviour ? 有关如何解决此问题的任何想法? How come the validation get by passed and 为什么验证得到通过和

Ok after spending a lot of time reading the FOSUserBundle code, and particularly the registration controller and the form factory, i came up with a fully working solution. 好好花了很多时间阅读FOSUserBundle代码,特别是注册控制器和表格工厂,我想出了一个完全可行的解决方案。

Before doing anything don't forget to disable CSRF in your symfony2 configuration. 在做任何事情之前,不要忘记在symfony2配置中禁用CSRF。

Here is the controller I use to register : 这是我用来注册的控制器:

 public function postUserAction(\Symfony\Component\HttpFoundation\Request $request) {


        /** @var $formFactory \FOS\UserBundle\Form\Factory\FactoryInterface */
        $formFactory = $this->get('fos_user.registration.form.factory');
        /** @var $userManager \FOS\UserBundle\Model\UserManagerInterface */
        $userManager = $this->get('fos_user.user_manager');
        /** @var $dispatcher \Symfony\Component\EventDispatcher\EventDispatcherInterface */
        $dispatcher = $this->get('event_dispatcher');

        $user = $userManager->createUser();
        $user->setEnabled(true);

        $event = new \FOS\UserBundle\Event\GetResponseUserEvent($user, $request);
        $dispatcher->dispatch(\FOS\UserBundle\FOSUserEvents::REGISTRATION_INITIALIZE, $event);

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

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

        $form->handleRequest($request);

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

            $userManager->updateUser($user);

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

            $dispatcher->dispatch(\FOS\UserBundle\FOSUserEvents::REGISTRATION_COMPLETED, new \FOS\UserBundle\Event\FilterUserResponseEvent($user, $request, $response));

            $view = $this->view(array('token' => $this->get("lexik_jwt_authentication.jwt_manager")->create($user)), Codes::HTTP_CREATED);

            return $this->handleView($view);
        }

        $view = $this->view($form, Codes::HTTP_BAD_REQUEST);
        return $this->handleView($view);
    }

Now the tricky part was submiting the form using REST. 现在棘手的部分是使用REST提交表单。 The problem was that when I sent i JSON like this one : 问题是,当我发送像这样的JSON时:

{
        "email":"xxxxx@xxxx.com",
        "username":"xxx",
        "plainPassword":{
            "first":"xxx",
            "second":"xxx"
        }
    }

The API was responding like nothing was submited. API没有提交任何内容就响应了。

The solution is that Symfony2 is waiting for you to encapsulate your form data in the form name ! 解决方案是Symfony2正在等待您将表单数据封装在表单名称中!

The question was "I didnt create this form so i dont know what is its name..". 问题是“我没有创建这种形式所以我不知道它的名字是什么......”。 So i went again in the bundle code and found out that the form type was fos_user_registration and the getName function was returning fos_user_registration_form. 所以我再次使用捆绑代码,发现表单类型为fos_user_registration,getName函数返回fos_user_registration_form。

As a result i tried to submit my JSON this way : 结果我尝试以这种方式提交我的JSON:

{"fos_user_registration_form":{
        "email":"xxxxxx@xxxxxxx.com",
        "username":"xxxxxx",
        "plainPassword":{
            "first":"xxxxx",
            "second":"xxxxx"
        }
    }}

And voila! 瞧! it worked. 有效。 If you are struggling setting up your fosuserbundle with fosrestbundle and LexikJWTAuthenticationBundle just ask me i'll be glad to help. 如果你正在努力设置你的fosuserbundle与fosrestbundle和LexikJWTAuthenticationBundle只是问我,我会很乐意提供帮助。

Another way is this registration without the forms from FOSUserBundle. 另一种方式是没有来自FOSUserBundle的表单进行注册。 Make a POST Request with params: email, user, password. 使用params发出POST请求:电子邮件,用户,密码。

public function postUserAction(Request $request)
{    
    $userManager = $this->get('fos_user.user_manager');

    $email = $request->request->get('email');
    $username = $request->request->get('user');
    $password = $request->request->get('password');


    $email_exist = $userManager->findUserByEmail($email);
    $username_exist = $userManager->findUserByUsername($username);

    if($email_exist || $username_exist){
        $response = new JsonResponse();
        $response->setData("Username/Email ".$username."/".$email." existiert bereits");
        return $response;
    }

    $user = $userManager->createUser();
    $user->setUsername($username);
    $user->setEmail($email);
    $user->setLocked(false); 
    $user->setEnabled(true); 
    $user->setPlainPassword($password);
    $userManager->updateUser($user, true);

    $response = new JsonResponse();
    $response->setData("User: ".$user->getUsername()." wurde erstellt");
    return $response;
}

@Adel 'Sean' Helal your way doesn't work, at least with last versions of FOSRestBundle, FOSUserBundle and Symfony with Flex. @Adel'Sean'Helal你的方式不起作用,至少使用FOSRestBundle,FOSUserBundle和Symfony的最新版本。 I almost shoot myself in the head trying to make it work. 我差点把自己射向脑袋试图让它发挥作用。 At the end I found the solution and it's pretty simple. 最后我找到了解决方案,而且非常简单。 Only parse the request is required. 只需要解析请求。

Fragment of my controller code 我的控制器代码的片段

...
$form->setData($user);
// THIS LINE DO THE MAGIC
$data = json_decode($request->getContent(), true);

if ($data === null) {
    throw new BadRequestHttpException();
}

$form->submit($data);

if ( ! $form->isValid()) {
    $event = new FormEvent($form, $request);
    $dispatcher->dispatch(FOSUserEvents::REGISTRATION_FAILURE, $event);
    if (null !== $response = $event->getResponse()) {
        return $response;
    }

    return new JsonResponse($this->getFormErrors($form), Response::HTTP_BAD_REQUEST);
}
...

The composer.json dependencies: composer.json依赖项:

...
"symfony/lts": "^3",
"symfony/flex": "^1.0",
"friendsofsymfony/rest-bundle": "^2.3",
"friendsofsymfony/user-bundle": "^2.0",
"lexik/jwt-authentication-bundle": "^2.4",
...

My functional test code: 我的功能测试代码:

namespace App\Tests\Controller;


use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\DependencyInjection\Container;

class ApiUserControllerTest extends WebTestCase
{
    /**
     * @var Container
     */
    private $container;

    public function setUp()
    {
        self::bootKernel();

        $this->container = self::$kernel->getContainer();
    }

    public function testRegistration()
    {
        $userData = [
            'username' => 'test',
            'email' => 'test@email.com',
            'plainPassword' => [
                'first' => 'test123', 'second' => 'test123'
            ]
        ];

        $client = $this->container->get('eight_points_guzzle.client.rest');
        $response = $client->post(
            'api/registration',
            ['json' => $userData]
        );
        $bodyResponse = \GuzzleHttp\json_decode($response->getBody(), true);

        $this->assertEquals(201, $response->getStatusCode());
        $this->assertArrayHasKey('token', $bodyResponse);
        $this->assertNotEmpty($bodyResponse['token']);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM