]> Raphaƫl G. Git Repositories - userbundle/blob - Controller/DefaultController.php
Change alphabet generation
[userbundle] / Controller / DefaultController.php
1 <?php
2
3 namespace Rapsys\UserBundle\Controller;
4
5 use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
6 use Symfony\Component\DependencyInjection\ContainerInterface;
7 use Symfony\Bundle\FrameworkBundle\Translation\Translator;
8 use Symfony\Component\HttpFoundation\Request;
9 use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
10 use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
11 use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
12 use Symfony\Component\Form\FormError;
13 use Rapsys\UserBundle\Utils\Slugger;
14
15 class DefaultController extends AbstractController {
16 //Config array
17 protected $config;
18
19 //Translator instance
20 protected $translator;
21
22 public function __construct(ContainerInterface $container, Translator $translator) {
23 //Retrieve config
24 $this->config = $container->getParameter($this->getAlias());
25
26 //Set the translator
27 $this->translator = $translator;
28 }
29
30 //FIXME: we need to change the $this->container->getParameter($alias.'.xyz') to $this->container->getParameter($alias)['xyz']
31 public function loginAction(Request $request, AuthenticationUtils $authenticationUtils) {
32 //Get template
33 $template = $this->config['login']['template'];
34 //Get context
35 $context = $this->config['login']['context'];
36
37 //Create the form according to the FormType created previously.
38 //And give the proper parameters
39 $form = $this->createForm('Rapsys\UserBundle\Form\LoginType', null, array(
40 // To set the action use $this->generateUrl('route_identifier')
41 'action' => $this->generateUrl('rapsys_user_login'),
42 'method' => 'POST'
43 ));
44
45 //Get the login error if there is one
46 if ($error = $authenticationUtils->getLastAuthenticationError()) {
47 //Get translated error
48 $error = $this->translator->trans($error->getMessageKey());
49
50 //Add error message to mail field
51 $form->get('mail')->addError(new FormError($error));
52 }
53
54 //Last username entered by the user
55 if ($lastUsername = $authenticationUtils->getLastUsername()) {
56 $form->get('mail')->setData($lastUsername);
57 }
58
59 //Render view
60 return $this->render($template, $context+array('form' => $form->createView(), 'error' => $error));
61 }
62
63 public function registerAction(Request $request, UserPasswordEncoderInterface $encoder) {
64 //Get mail template
65 $mailTemplate = $this->config['register']['mail_template'];
66 //Get mail context
67 $mailContext = $this->config['register']['mail_context'];
68 //Get template
69 $template = $this->config['register']['template'];
70 //Get context
71 $context = $this->config['register']['context'];
72 //Get home name
73 $homeName = $this->config['contact']['home_name'];
74 //Get home args
75 $homeArgs = $this->config['contact']['home_args'];
76 //Get contact name
77 $contactName = $this->config['contact']['name'];
78 //Get contact mail
79 $contactMail = $this->config['contact']['mail'];
80 //TODO: check if doctrine orm replacement is enough with default classes here
81 //Get class user
82 $classUser = $this->config['class']['user'];
83 //Get class group
84 $classGroup = $this->config['class']['group'];
85 //Get class title
86 $classTitle = $this->config['class']['title'];
87
88 //Create the form according to the FormType created previously.
89 //And give the proper parameters
90 $form = $this->createForm('Rapsys\UserBundle\Form\RegisterType', null, array(
91 // To set the action use $this->generateUrl('route_identifier')
92 'class_title' => $classTitle,
93 'action' => $this->generateUrl('rapsys_user_register'),
94 'method' => 'POST'
95 ));
96
97 if ($request->isMethod('POST')) {
98 // Refill the fields in case the form is not valid.
99 $form->handleRequest($request);
100
101 if ($form->isValid()) {
102 //Set data
103 $data = $form->getData();
104
105 //Translate title
106 $mailContext['title'] = $this->translator->trans($mailContext['title']);
107
108 //Translate title
109 $mailContext['subtitle'] = $this->translator->trans($mailContext['subtitle'], array('%name%' => $data['forename'].' '.$data['surname'].' ('.$data['pseudonym'].')'));
110
111 //Translate subject
112 $mailContext['subject'] = $this->translator->trans($mailContext['subject'], array('%title%' => $mailContext['title']));
113
114 //Translate message
115 $mailContext['message'] = $this->translator->trans($mailContext['message'], array('%title%' => $mailContext['title']));
116
117 //Create message
118 $message = \Swift_Message::newInstance()
119 ->setSubject($mailContext['subject'])
120 ->setFrom(array($contactMail => $contactName))
121 ->setTo(array($data['mail'] => $data['forename'].' '.$data['surname']))
122 ->setBody($mailContext['message'])
123 ->addPart(
124 $this->renderView(
125 $mailTemplate,
126 $mailContext+array(
127 'home' => $this->get('router')->generate($homeName, $homeArgs, UrlGeneratorInterface::ABSOLUTE_URL)
128 )
129 ),
130 'text/html'
131 );
132
133 //Get doctrine
134 $doctrine = $this->getDoctrine();
135
136 //Get manager
137 $manager = $doctrine->getManager();
138
139 //Init reflection
140 $reflection = new \ReflectionClass($classUser);
141
142 //Create new user
143 $user = $reflection->newInstance();
144
145 $user->setMail($data['mail']);
146 $user->setPseudonym($data['pseudonym']);
147 $user->setForename($data['forename']);
148 $user->setSurname($data['surname']);
149 $user->setPassword($encoder->encodePassword($user, $data['password']));
150 $user->setActive(true);
151 $user->setTitle($data['title']);
152 //TODO: see if we can't modify group constructor to set role directly from args
153 //XXX: see vendor/symfony/symfony/src/Symfony/Component/Security/Core/Role/Role.php
154 $user->addGroup($doctrine->getRepository($classGroup)->findOneByRole('ROLE_USER'));
155 $user->setCreated(new \DateTime('now'));
156 $user->setUpdated(new \DateTime('now'));
157
158 //Persist user
159 $manager->persist($user);
160
161 try {
162 //Send to database
163 $manager->flush();
164
165 //Send message
166 if ($this->get('mailer')->send($message)) {
167 //Redirect to cleanup the form
168 return $this->redirectToRoute('rapsys_user_register', array('sent' => 1));
169 }
170 } catch (\Doctrine\DBAL\Exception\UniqueConstraintViolationException $e) {
171 //Add error message mail already exists
172 $form->get('mail')->addError(new FormError($this->translator->trans('Account already exists: %mail%', array('%mail%' => $data['mail']))));
173 }
174 }
175 }
176
177 //Render view
178 return $this->render($template, $context+array('form' => $form->createView(), 'sent' => $request->query->get('sent', 0)));
179 }
180
181 public function recoverAction(Request $request, Slugger $slugger) {
182 //Get mail template
183 $mailTemplate = $this->config['recover']['mail_template'];
184 //Get mail context
185 $mailContext = $this->config['recover']['mail_context'];
186 //Get template
187 $template = $this->config['recover']['template'];
188 //Get context
189 $context = $this->config['recover']['context'];
190 //Get url name
191 $urlName = $this->config['recover']['url_name'];
192 //Get url args
193 $urlArgs = $this->config['recover']['url_args'];
194 //Get home name
195 $homeName = $this->config['contact']['home_name'];
196 //Get home args
197 $homeArgs = $this->config['contact']['home_args'];
198 //Get contact name
199 $contactName = $this->config['contact']['name'];
200 //Get contact mail
201 $contactMail = $this->config['contact']['mail'];
202 //Get class user
203 $classUser = $this->config['class']['user'];
204
205 //Create the form according to the FormType created previously.
206 //And give the proper parameters
207 $form = $this->createForm('Rapsys\UserBundle\Form\RecoverType', null, array(
208 // To set the action use $this->generateUrl('route_identifier')
209 'action' => $this->generateUrl('rapsys_user_recover'),
210 'method' => 'POST'
211 ));
212
213 if ($request->isMethod('POST')) {
214 // Refill the fields in case the form is not valid.
215 $form->handleRequest($request);
216
217 if ($form->isValid()) {
218 //Get doctrine
219 $doctrine = $this->getDoctrine();
220
221 //Set data
222 $data = $form->getData();
223
224 //Translate title
225 $mailContext['title'] = $this->translator->trans($mailContext['title']);
226
227 //Try to find user
228 if ($user = $doctrine->getRepository($classUser)->findOneByMail($data['mail'])) {
229 //Translate title
230 $mailContext['subtitle'] = $this->translator->trans($mailContext['subtitle'], array('%name%' => $user->getForename().' '.$user->getSurname().' ('.$user->getPseudonym().')'));
231
232 //Translate subject
233 $mailContext['subject'] = $this->translator->trans($mailContext['subject'], array('%title%' => $mailContext['title']));
234
235 //Translate message
236 $mailContext['raw'] = $this->translator->trans($mailContext['raw'], array('%title%' => $mailContext['title'], '%url%' => $this->get('router')->generate($urlName, $urlArgs+array('mail' => $slugger->short($user->getMail()), 'hash' => $slugger->hash($user->getPassword())), UrlGeneratorInterface::ABSOLUTE_URL)));
237
238 //Create message
239 $message = \Swift_Message::newInstance()
240 ->setSubject($mailContext['subject'])
241 ->setFrom(array($contactMail => $contactName))
242 ->setTo(array($user->getMail() => $user->getForename().' '.$user->getSurname()))
243 ->setBody(strip_tags($mailContext['raw']))
244 ->addPart(
245 $this->renderView(
246 $mailTemplate,
247 $mailContext+array(
248 'home' => $this->get('router')->generate($homeName, $homeArgs, UrlGeneratorInterface::ABSOLUTE_URL)
249 )
250 ),
251 'text/html'
252 );
253
254 //Send message
255 if ($this->get('mailer')->send($message)) {
256 //Redirect to cleanup the form
257 return $this->redirectToRoute('rapsys_user_recover', array('sent' => 1));
258 }
259 //Accout not found
260 } else {
261 //Add error message to mail field
262 $form->get('mail')->addError(new FormError($this->translator->trans('Unable to find account: %mail%', array('%mail%' => $data['mail']))));
263 }
264 }
265 }
266
267 //Render view
268 return $this->render($template, $context+array('form' => $form->createView(), 'sent' => $request->query->get('sent', 0)));
269 }
270
271 public function recoverMailAction(Request $request, UserPasswordEncoderInterface $encoder, Slugger $slugger, $mail, $hash) {
272 //Get mail template
273 $mailTemplate = $this->config['recover_mail']['mail_template'];
274 //Get mail context
275 $mailContext = $this->config['recover_mail']['mail_context'];
276 //Get template
277 $template = $this->config['recover_mail']['template'];
278 //Get context
279 $context = $this->config['recover_mail']['context'];
280 //Get url name
281 $urlName = $this->config['recover_mail']['url_name'];
282 //Get url args
283 $urlArgs = $this->config['recover_mail']['url_args'];
284 //Get home name
285 $homeName = $this->config['contact']['home_name'];
286 //Get home args
287 $homeArgs = $this->config['contact']['home_args'];
288 //Get contact name
289 $contactName = $this->config['contact']['name'];
290 //Get contact mail
291 $contactMail = $this->config['contact']['mail'];
292 //Get class user
293 $classUser = $this->config['class']['user'];
294
295 //Create the form according to the FormType created previously.
296 //And give the proper parameters
297 $form = $this->createForm('Rapsys\UserBundle\Form\RecoverMailType', null, array(
298 // To set the action use $this->generateUrl('route_identifier')
299 'action' => $this->generateUrl('rapsys_user_recover_mail', array('mail' => $mail, 'hash' => $hash)),
300 'method' => 'POST'
301 ));
302
303 //Get doctrine
304 $doctrine = $this->getDoctrine();
305
306 //Init not found
307 $notfound = 1;
308
309 //Retrieve user
310 if (($user = $doctrine->getRepository($classUser)->findOneByMail($slugger->unshort($mail))) && $hash == $slugger->hash($user->getPassword())) {
311 //User was found
312 $notfound = 0;
313
314 if ($request->isMethod('POST')) {
315 // Refill the fields in case the form is not valid.
316 $form->handleRequest($request);
317
318 if ($form->isValid()) {
319 //Set data
320 $data = $form->getData();
321
322 //Translate title
323 $mailContext['title'] = $this->translator->trans($mailContext['title']);
324
325 //Translate title
326 $mailContext['subtitle'] = $this->translator->trans($mailContext['subtitle'], array('%name%' => $user->getForename().' '.$user->getSurname().' ('.$user->getPseudonym().')'));
327
328 //Translate subject
329 $mailContext['subject'] = $this->translator->trans($mailContext['subject'], array('%title%' => $mailContext['title']));
330
331 //Set user password
332 $user->setPassword($encoder->encodePassword($user, $data['password']));
333
334 //Translate message
335 $mailContext['raw'] = $this->translator->trans($mailContext['raw'], array('%title%' => $mailContext['title'], '%url%' => $this->get('router')->generate($urlName, $urlArgs+array('mail' => $slugger->short($user->getMail()), 'hash' => $slugger->hash($user->getPassword())), UrlGeneratorInterface::ABSOLUTE_URL)));
336
337 //Get manager
338 $manager = $doctrine->getManager();
339
340 //Persist user
341 $manager->persist($user);
342
343 //Send to database
344 $manager->flush();
345
346 //Create message
347 $message = \Swift_Message::newInstance()
348 ->setSubject($mailContext['subject'])
349 ->setFrom(array($contactMail => $contactName))
350 ->setTo(array($user->getMail() => $user->getForename().' '.$user->getSurname()))
351 ->setBody(strip_tags($mailContext['raw']))
352 ->addPart(
353 $this->renderView(
354 $mailTemplate,
355 $mailContext+array(
356 'home' => $this->get('router')->generate($homeName, $homeArgs, UrlGeneratorInterface::ABSOLUTE_URL)
357 )
358 ),
359 'text/html'
360 );
361
362 //Send message
363 if ($this->get('mailer')->send($message)) {
364 //Redirect to cleanup the form
365 return $this->redirectToRoute('rapsys_user_recover_mail', array('mail' => $mail, 'hash' => $hash, 'sent' => 1));
366 }
367 }
368 }
369 }
370
371 //Render view
372 return $this->render($template, $context+array('form' => $form->createView(), 'sent' => $request->query->get('sent', 0), 'notfound' => $notfound));
373 }
374
375 /**
376 * {@inheritdoc}
377 */
378 public function getAlias() {
379 return 'rapsys_user';
380 }
381 }