]> git.immae.eu Git - github/wallabag/wallabag.git/blob - src/Wallabag/ApiBundle/Controller/UserRestController.php
becbbb9ef4c0d77f5f024fe06cef1ba81e885f47
[github/wallabag/wallabag.git] / src / Wallabag / ApiBundle / Controller / UserRestController.php
1 <?php
2
3 namespace Wallabag\ApiBundle\Controller;
4
5 use FOS\UserBundle\Event\UserEvent;
6 use FOS\UserBundle\FOSUserEvents;
7 use JMS\Serializer\SerializationContext;
8 use Nelmio\ApiDocBundle\Annotation\ApiDoc;
9 use Symfony\Component\HttpFoundation\Request;
10 use Symfony\Component\HttpFoundation\JsonResponse;
11 use Wallabag\UserBundle\Entity\User;
12 use Wallabag\ApiBundle\Entity\Client;
13
14 class UserRestController extends WallabagRestController
15 {
16 /**
17 * Retrieve current logged in user informations.
18 *
19 * @ApiDoc()
20 *
21 * @return JsonResponse
22 */
23 public function getUserAction()
24 {
25 $this->validateAuthentication();
26
27 return $this->sendUser($this->getUser());
28 }
29
30 /**
31 * Register an user.
32 *
33 * @ApiDoc(
34 * requirements={
35 * {"name"="username", "dataType"="string", "required"=true, "description"="The user's username"},
36 * {"name"="password", "dataType"="string", "required"=true, "description"="The user's password"},
37 * {"name"="email", "dataType"="string", "required"=true, "description"="The user's email"}
38 * }
39 * )
40 *
41 * @todo Make this method (or the whole API) accessible only through https
42 *
43 * @return JsonResponse
44 */
45 public function putUserAction(Request $request)
46 {
47 if (!$this->getParameter('fosuser_registration') || !$this->get('craue_config')->get('api_user_registration')) {
48 $json = $this->get('serializer')->serialize(['error' => "Server doesn't allow registrations"], 'json');
49
50 return (new JsonResponse())
51 ->setJson($json)
52 ->setStatusCode(JsonResponse::HTTP_FORBIDDEN);
53 }
54
55 $userManager = $this->get('fos_user.user_manager');
56 $user = $userManager->createUser();
57 // user will be disabled BY DEFAULT to avoid spamming account to be enabled
58 $user->setEnabled(false);
59
60 $form = $this->createForm('Wallabag\UserBundle\Form\NewUserType', $user, [
61 'csrf_protection' => false,
62 ]);
63
64 // simulate form submission
65 $form->submit([
66 'username' => $request->request->get('username'),
67 'plainPassword' => [
68 'first' => $request->request->get('password'),
69 'second' => $request->request->get('password'),
70 ],
71 'email' => $request->request->get('email'),
72 ]);
73
74 if ($form->isSubmitted() && false === $form->isValid()) {
75 $view = $this->view($form, 400);
76 $view->setFormat('json');
77
78 // handle errors in a more beautiful way than the default view
79 $data = json_decode($this->handleView($view)->getContent(), true)['children'];
80 $errors = [];
81
82 if (isset($data['username']['errors'])) {
83 $errors['username'] = $this->translateErrors($data['username']['errors']);
84 }
85
86 if (isset($data['email']['errors'])) {
87 $errors['email'] = $this->translateErrors($data['email']['errors']);
88 }
89
90 if (isset($data['plainPassword']['children']['first']['errors'])) {
91 $errors['password'] = $this->translateErrors($data['plainPassword']['children']['first']['errors']);
92 }
93
94 $json = $this->get('serializer')->serialize(['error' => $errors], 'json');
95
96 return (new JsonResponse())
97 ->setJson($json)
98 ->setStatusCode(JsonResponse::HTTP_BAD_REQUEST);
99 }
100
101 // create a default client
102 $client = new Client($user);
103 $client->setName('Default client');
104
105 $this->getDoctrine()->getManager()->persist($client);
106
107 $user->addClient($client);
108
109 $userManager->updateUser($user);
110
111 // dispatch a created event so the associated config will be created
112 $event = new UserEvent($user, $request);
113 $this->get('event_dispatcher')->dispatch(FOSUserEvents::USER_CREATED, $event);
114
115 return $this->sendUser($user, 'user_api_with_client', JsonResponse::HTTP_CREATED);
116 }
117
118 /**
119 * Send user response.
120 *
121 * @param User $user
122 * @param string $group Used to define with serialized group might be used
123 * @param int $status HTTP Status code to send
124 *
125 * @return JsonResponse
126 */
127 private function sendUser(User $user, $group = 'user_api', $status = JsonResponse::HTTP_OK)
128 {
129 $json = $this->get('serializer')->serialize(
130 $user,
131 'json',
132 SerializationContext::create()->setGroups([$group])
133 );
134
135 return (new JsonResponse())
136 ->setJson($json)
137 ->setStatusCode($status);
138 }
139
140 /**
141 * Translate errors message.
142 *
143 * @param array $errors
144 *
145 * @return array
146 */
147 private function translateErrors($errors)
148 {
149 $translatedErrors = [];
150 foreach ($errors as $error) {
151 $translatedErrors[] = $this->get('translator')->trans($error);
152 }
153
154 return $translatedErrors;
155 }
156 }