wallabag/src/Wallabag/ApiBundle/Controller/UserRestController.php

199 lines
6.3 KiB
PHP
Raw Normal View History

<?php
namespace Wallabag\ApiBundle\Controller;
2022-08-28 00:01:46 +00:00
use Craue\ConfigBundle\Util\Config;
use FOS\UserBundle\Event\UserEvent;
use FOS\UserBundle\FOSUserEvents;
2022-08-28 00:01:46 +00:00
use FOS\UserBundle\Model\UserManagerInterface;
use JMS\Serializer\SerializationContext;
2022-08-28 00:01:46 +00:00
use JMS\Serializer\SerializerInterface;
use Nelmio\ApiDocBundle\Annotation\Operation;
use Swagger\Annotations as SWG;
2022-08-28 00:01:46 +00:00
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
2017-07-01 07:52:38 +00:00
use Symfony\Component\HttpFoundation\Request;
2022-08-28 00:01:46 +00:00
use Symfony\Component\Translation\TranslatorInterface;
use Wallabag\ApiBundle\Entity\Client;
2017-07-01 07:52:38 +00:00
use Wallabag\UserBundle\Entity\User;
2022-09-01 18:54:56 +00:00
use Wallabag\UserBundle\Form\NewUserType;
class UserRestController extends WallabagRestController
{
/**
* Retrieve current logged in user informations.
*
* @Operation(
* tags={"User"},
* summary="Retrieve current logged in user informations.",
* @SWG\Response(
* response="200",
* description="Returned when successful"
* )
* )
*
* @return JsonResponse
*/
public function getUserAction()
{
$this->validateAuthentication();
return $this->sendUser($this->getUser());
}
/**
2017-06-08 12:25:44 +00:00
* Register an user and create a client.
*
* @Operation(
* tags={"User"},
* summary="Register an user and create a client.",
* @SWG\Parameter(
* name="username",
* in="body",
* description="The user's username",
* required=true,
* @SWG\Schema(type="string")
* ),
* @SWG\Parameter(
* name="password",
* in="body",
* description="The user's password",
* required=true,
* @SWG\Schema(type="string")
* ),
* @SWG\Parameter(
* name="email",
* in="body",
* description="The user's email",
* required=true,
* @SWG\Schema(type="string")
* ),
* @SWG\Parameter(
* name="client_name",
* in="body",
* description="The client name (to be used by your app)",
* required=true,
* @SWG\Schema(type="string")
* ),
* @SWG\Response(
* response="200",
* description="Returned when successful"
* )
* )
*
* @todo Make this method (or the whole API) accessible only through https
*
* @return JsonResponse
*/
public function putUserAction(Request $request)
{
2022-08-28 00:01:46 +00:00
if (!$this->container->getParameter('fosuser_registration') || !$this->get(Config::class)->get('api_user_registration')) {
$json = $this->get(SerializerInterface::class)->serialize(['error' => "Server doesn't allow registrations"], 'json');
2017-06-02 18:03:25 +00:00
return (new JsonResponse())
->setJson($json)
->setStatusCode(JsonResponse::HTTP_FORBIDDEN);
}
2022-08-28 00:01:46 +00:00
$userManager = $this->get(UserManagerInterface::class);
$user = $userManager->createUser();
2017-06-02 08:27:15 +00:00
// user will be disabled BY DEFAULT to avoid spamming account to be enabled
$user->setEnabled(false);
2022-09-01 18:54:56 +00:00
$form = $this->createForm(NewUserType::class, $user, [
'csrf_protection' => false,
]);
// simulate form submission
$form->submit([
'username' => $request->request->get('username'),
'plainPassword' => [
'first' => $request->request->get('password'),
'second' => $request->request->get('password'),
],
'email' => $request->request->get('email'),
]);
if ($form->isSubmitted() && false === $form->isValid()) {
$view = $this->view($form, 400);
$view->setFormat('json');
// handle errors in a more beautiful way than the default view
$data = json_decode($this->handleView($view)->getContent(), true)['errors']['children'];
$errors = [];
if (isset($data['username']['errors'])) {
$errors['username'] = $this->translateErrors($data['username']['errors']);
}
if (isset($data['email']['errors'])) {
$errors['email'] = $this->translateErrors($data['email']['errors']);
}
if (isset($data['plainPassword']['children']['first']['errors'])) {
$errors['password'] = $this->translateErrors($data['plainPassword']['children']['first']['errors']);
}
2022-08-28 00:01:46 +00:00
$json = $this->get(SerializerInterface::class)->serialize(['error' => $errors], 'json');
2017-06-02 18:03:25 +00:00
return (new JsonResponse())
->setJson($json)
->setStatusCode(JsonResponse::HTTP_BAD_REQUEST);
}
// create a default client
$client = new Client($user);
2017-06-08 12:25:44 +00:00
$client->setName($request->request->get('client_name', 'Default client'));
$this->getDoctrine()->getManager()->persist($client);
$user->addClient($client);
$userManager->updateUser($user);
// dispatch a created event so the associated config will be created
$event = new UserEvent($user, $request);
2022-08-28 00:01:46 +00:00
$this->get(EventDispatcherInterface::class)->dispatch(FOSUserEvents::USER_CREATED, $event);
return $this->sendUser($user, 'user_api_with_client', JsonResponse::HTTP_CREATED);
}
/**
* Send user response.
*
* @param string $group Used to define with serialized group might be used
* @param int $status HTTP Status code to send
*
* @return JsonResponse
*/
private function sendUser(User $user, $group = 'user_api', $status = JsonResponse::HTTP_OK)
{
2022-08-28 00:01:46 +00:00
$json = $this->get(SerializerInterface::class)->serialize(
$user,
'json',
SerializationContext::create()->setGroups([$group])
);
2017-06-02 18:03:25 +00:00
return (new JsonResponse())
->setJson($json)
->setStatusCode($status);
}
/**
* Translate errors message.
*
* @param array $errors
*
* @return array
*/
private function translateErrors($errors)
{
$translatedErrors = [];
foreach ($errors as $error) {
2022-08-28 00:01:46 +00:00
$translatedErrors[] = $this->get(TranslatorInterface::class)->trans($error);
}
return $translatedErrors;
}
}