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