簡體   English   中英

使用FOSRestBundle REST API設置注冊FOSUserBundle

[英]Set up registration FOSUserBundle with FOSRestBundle REST API

問題已解決,請檢查我的答案。

我正在我的Symfony2.7 rest api上建立一個注冊端點。 我正在使用FosRestBundle和FosUserBundle

這是用戶模型:

<?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
    }

}

\\ 這是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';
    }
}

而這個帖子用戶控制器:

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,
        );
    }

問題是,當我提交錯誤的信息或空信息時,服務器返回一個錯誤的格式化500錯誤,其中帶有錯誤格式化條目列表的json響應狀態中非空行的空值的doctrine / mysql詳細信息。

有關如何解決此問題的任何想法? 為什么驗證得到通過和

好好花了很多時間閱讀FOSUserBundle代碼,特別是注冊控制器和表格工廠,我想出了一個完全可行的解決方案。

在做任何事情之前,不要忘記在symfony2配置中禁用CSRF。

這是我用來注冊的控制器:

 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);
    }

現在棘手的部分是使用REST提交表單。 問題是,當我發送像這樣的JSON時:

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

API沒有提交任何內容就響應了。

解決方案是Symfony2正在等待您將表單數據封裝在表單名稱中!

問題是“我沒有創建這種形式所以我不知道它的名字是什么......”。 所以我再次使用捆綁代碼,發現表單類型為fos_user_registration,getName函數返回fos_user_registration_form。

結果我嘗試以這種方式提交我的JSON:

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

瞧! 有效。 如果你正在努力設置你的fosuserbundle與fosrestbundle和LexikJWTAuthenticationBundle只是問我,我會很樂意提供幫助。

另一種方式是沒有來自FOSUserBundle的表單進行注冊。 使用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你的方式不起作用,至少使用FOSRestBundle,FOSUserBundle和Symfony的最新版本。 我差點把自己射向腦袋試圖讓它發揮作用。 最后我找到了解決方案,而且非常簡單。 只需要解析請求。

我的控制器代碼的片段

...
$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);
}
...

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",
...

我的功能測試代碼:

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