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