PageRenderTime 61ms CodeModel.GetById 32ms RepoModel.GetById 0ms app.codeStats 0ms

/codigo/src/main/java/com/roo/esperanza/web/SignUpController.java

https://gitlab.com/darioegb/esperanza
Java | 429 lines | 278 code | 30 blank | 121 comment | 10 complexity | 4218fddef94b22a32ade9326f9375d02 MD5 | raw file
  1. package com.roo.esperanza.web;
  2. import java.io.IOException;
  3. import java.io.UnsupportedEncodingException;
  4. import java.util.Arrays;
  5. import java.util.Date;
  6. import java.util.List;
  7. import java.util.Random;
  8. import javax.persistence.TypedQuery;
  9. import javax.servlet.http.HttpServletRequest;
  10. import javax.servlet.http.HttpSession;
  11. import javax.validation.Valid;
  12. import org.springframework.beans.factory.annotation.Autowired;
  13. import org.springframework.mail.MailSender;
  14. import org.springframework.mail.SimpleMailMessage;
  15. import org.springframework.security.authentication.encoding.MessageDigestPasswordEncoder;
  16. import org.springframework.stereotype.Controller;
  17. import org.springframework.transaction.annotation.Transactional;
  18. import org.springframework.ui.Model;
  19. import org.springframework.validation.BindingResult;
  20. import org.springframework.web.bind.annotation.ModelAttribute;
  21. import org.springframework.web.bind.annotation.RequestMapping;
  22. import org.springframework.web.bind.annotation.RequestMethod;
  23. import org.springframework.web.bind.annotation.RequestParam;
  24. import org.springframework.web.servlet.mvc.support.RedirectAttributes;
  25. import org.springframework.web.util.UriUtils;
  26. import org.springframework.web.util.WebUtils;
  27. import com.roo.esperanza.domain.Address;
  28. import com.roo.esperanza.domain.Category;
  29. import com.roo.esperanza.domain.ConfigNotification;
  30. import com.roo.esperanza.domain.Country;
  31. import com.roo.esperanza.domain.Institution;
  32. import com.roo.esperanza.domain.InstitutionRegistrationForm;
  33. import com.roo.esperanza.domain.Person;
  34. import com.roo.esperanza.domain.PersonRegistrationForm;
  35. import com.roo.esperanza.domain.Role;
  36. import com.roo.esperanza.domain.User;
  37. import com.roo.esperanza.domain.UserRegistrationForm;
  38. import com.roo.esperanza.provider.ImageService;
  39. import com.roo.esperanza.provider.ScriptAddService;
  40. import com.roo.esperanza.provider.SignUpValidator;
  41. import com.roo.esperanza.provider.UtilityService;
  42. import com.roo.esperanza.reference.GenreTypeEnum;
  43. import com.roo.esperanza.reference.RoleTypeEnum;
  44. // TODO: Auto-generated Javadoc
  45. /**
  46. * The Class SignUpController.
  47. */
  48. @RequestMapping({"/signup/**", "/completeregister/**"})
  49. @Controller
  50. public class SignUpController {
  51. /** The u service. */
  52. @Autowired
  53. UtilityService uService;
  54. /** The validator. */
  55. @Autowired
  56. private SignUpValidator validator;
  57. /** The mail sender. */
  58. @Autowired
  59. private transient MailSender mailSender;
  60. /** The message digest password encoder. */
  61. @Autowired
  62. private MessageDigestPasswordEncoder messageDigestPasswordEncoder;
  63. /** The sa service. */
  64. @Autowired
  65. ScriptAddService saService;
  66. /** The i service. */
  67. @Autowired
  68. ImageService iService;
  69. /**
  70. * Creates the form.
  71. *
  72. * @param model the model
  73. * @return the string
  74. */
  75. @RequestMapping(value= "signup", params = "form", method = RequestMethod.GET, produces = "text/html")
  76. public String createForm(Model model) {
  77. populateEditForm(model, new UserRegistrationForm());
  78. return "signup/index";
  79. }
  80. /**
  81. * Activate user.
  82. *
  83. * @param activationKey the activation key
  84. * @param emailAddress the email address
  85. * @param model the model
  86. * @param request the request
  87. * @return the string
  88. */
  89. @RequestMapping(value= "signup", params = "activate", method = RequestMethod.GET, produces = "text/html")
  90. public String activateUser(@RequestParam(value = "activate", required = true) String activationKey,@RequestParam(value = "emailAddress", required = true) String emailAddress,Model model, HttpServletRequest request) {
  91. TypedQuery<User> query = User.findUsersByActivationKeyAndEmailAddress(activationKey, emailAddress);
  92. User user=query.getSingleResult();
  93. if(null!=user){
  94. user.setActivationDate(new Date());
  95. user.setEnabled(true);
  96. user.merge();
  97. if(user.getRol().getId() > 1){
  98. HttpSession sessionObj = request.getSession();
  99. sessionObj.setAttribute("emailAddress" , user.getEmailAddress());
  100. sessionObj.setAttribute("roleId" , user.getRol().getId().toString());
  101. return "redirect:/completeregister?form";
  102. }
  103. return "login";
  104. }
  105. else{
  106. return "signup/error";
  107. }
  108. }
  109. /**
  110. * Creates the.
  111. *
  112. * @param userRegistration the user registration
  113. * @param result the result
  114. * @param model the model
  115. * @param request the request
  116. * @return the string
  117. */
  118. @RequestMapping(value= "signup", method = RequestMethod.POST, produces = "text/html")
  119. public String create(@Valid @ModelAttribute("User") UserRegistrationForm userRegistration, BindingResult result, Model model, HttpServletRequest request) {
  120. validator.validate(userRegistration, result);
  121. if (result.hasErrors()) {
  122. System.out.println(result);
  123. populateEditForm(model, userRegistration);
  124. return "signup/index";
  125. } else {
  126. model.asMap().clear();
  127. Random random = new Random(System.currentTimeMillis());
  128. String activationKey = "activationKey:" + random.nextInt();
  129. User user = new User();
  130. user.setActivationDate(null);
  131. user.setEmailAddress(userRegistration.getEmailAddress());
  132. user.setPassword(messageDigestPasswordEncoder.encodePassword(userRegistration.getPassword(), null));
  133. user.setActivationKey(activationKey);
  134. user.setEnabled(false);
  135. user.setLocked(false);
  136. user.setRol(Role.findRolesByRoleType(userRegistration.getRoleType()).getSingleResult());
  137. user.persist();
  138. try {
  139. Boolean status = uService.checkInternetConnexion();
  140. if(status){
  141. SimpleMailMessage mail = new SimpleMailMessage();
  142. mail.setTo(user.getEmailAddress());
  143. mail.setSubject("Activación de usuario - Esperanza");
  144. mail.setText("Hola "+user.getEmailAddress()+",\n. Usted ha registrado con nosotros. Por favor, haga clic en este enlace para activar tu cuenta - <a href=\"http://localhost:8080/Esperanza/signup?emailAddress="+user.getEmailAddress()+"&activate="+activationKey+"\">Enlace de activación</a>. \n Muchas Gracias Administración de Esperanza");
  145. mailSender.send(mail);
  146. }
  147. } catch (IOException e) {
  148. e.printStackTrace();
  149. }
  150. return "signup/thanks";
  151. }
  152. }
  153. /**
  154. * Creates the pacticipant form.
  155. *
  156. * @param model the model
  157. * @param request the request
  158. * @return the string
  159. */
  160. @RequestMapping(value= "completeregister", params = "form", method = RequestMethod.GET, produces = "text/html")
  161. public String createPacticipantForm(Model model, HttpServletRequest request) {
  162. HttpSession sessionObj = request.getSession();
  163. populateEditForm(model, sessionObj);
  164. saService.agregarJS("general/ajax.js");
  165. saService.publicarJsCss(model);
  166. if(sessionObj.getAttribute("roleId").equals("2")){
  167. model.addAttribute("personForm", new PersonRegistrationForm());
  168. model.addAttribute("isPerson", true);
  169. return "completeregister/index";
  170. }
  171. List<Category> categorys = Category.findAllCategorys("name", "ASC");
  172. model.addAttribute("categorys", categorys);
  173. model.addAttribute("institutionForm", new InstitutionRegistrationForm());
  174. return "completeregister/index";
  175. }
  176. /**
  177. * Complete register person.
  178. *
  179. * @param personForm the person form
  180. * @param bindingResult the binding result
  181. * @param model the model
  182. * @param request the request
  183. * @param redirectAttrs the redirect attrs
  184. * @return the string
  185. */
  186. @RequestMapping(value = "completeregister/person", method = RequestMethod.POST, produces = "text/html")
  187. public String completeRegisterPerson(@Valid @ModelAttribute("personForm") PersonRegistrationForm personForm,
  188. BindingResult bindingResult, Model model, HttpServletRequest request, final RedirectAttributes redirectAttrs) {
  189. TypedQuery<User> query = User.findUsersByEmailAddress(personForm.getEmailAddress());
  190. User user = query.getSingleResult();
  191. HttpSession sessionObj = request.getSession();
  192. if (bindingResult.hasErrors()) {
  193. populateEditForm(model, sessionObj);
  194. model.addAttribute("personForm", personForm);
  195. model.addAttribute("isPerson", true);
  196. return "completeregister/index";
  197. }
  198. sessionObj.removeAttribute("emailAddress");
  199. sessionObj.removeAttribute("roleId");
  200. model.asMap().clear();
  201. Person person = new Person();
  202. Address address = new Address();
  203. ConfigNotification configNotifications = new ConfigNotification();
  204. setPerson(person, personForm, address, user, configNotifications);
  205. persistPerson(person, address, configNotifications);
  206. redirectAttrs.addFlashAttribute("registerSuccess", "true");
  207. return "redirect:/login";
  208. }
  209. /**
  210. * Complete register institution.
  211. *
  212. * @param institutionForm the institution form
  213. * @param bindingResult the binding result
  214. * @param model the model
  215. * @param request the request
  216. * @return the string
  217. */
  218. @RequestMapping(value = "completeregister/institution", method = RequestMethod.POST, produces = "text/html")
  219. public String completeRegisterInstitution(@Valid @ModelAttribute("institutionForm") InstitutionRegistrationForm institutionForm,
  220. BindingResult bindingResult, Model model, HttpServletRequest request) {
  221. TypedQuery<User> query = User.findUsersByEmailAddress(institutionForm.getEmailAddress());
  222. User user = query.getSingleResult();
  223. HttpSession sessionObj = request.getSession();
  224. if (bindingResult.hasErrors()) {
  225. System.out.println(bindingResult);
  226. populateEditForm(model, sessionObj);
  227. model.addAttribute("institutionForm", institutionForm);
  228. return "completeregister/index";
  229. }
  230. sessionObj.removeAttribute("emailAddress");
  231. sessionObj.removeAttribute("roleId");
  232. model.asMap().clear();
  233. Institution institution = new Institution();
  234. Address address = new Address();
  235. ConfigNotification configNotifications = new ConfigNotification();
  236. setInstitution(institution, institutionForm, address, user, configNotifications);
  237. persistIstitution(institution, address, configNotifications);
  238. return "redirect:/login";
  239. }
  240. /**
  241. * Encode url path segment.
  242. *
  243. * @param pathSegment the path segment
  244. * @param httpServletRequest the http servlet request
  245. * @return the string
  246. */
  247. String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) {
  248. String enc = httpServletRequest.getCharacterEncoding();
  249. if (enc == null) {
  250. enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
  251. }
  252. try {
  253. pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
  254. } catch (UnsupportedEncodingException uee) {}
  255. return pathSegment;
  256. }
  257. /**
  258. * Populate edit form.
  259. *
  260. * @param model the model
  261. * @param userForm the user form
  262. */
  263. void populateEditForm(Model model, UserRegistrationForm userForm) {
  264. model.addAttribute("roletypeenums", Arrays.asList(RoleTypeEnum.values()).subList(1, 3));
  265. model.addAttribute("User", userForm);
  266. model.addAttribute("captcha_form",userForm.getReCaptchaHtml());
  267. }
  268. /**
  269. * Populate edit form.
  270. *
  271. * @param model the model
  272. * @param sessionObj the session obj
  273. */
  274. void populateEditForm(Model model, HttpSession sessionObj){
  275. List<Country> countries = Country.findAllCountrys();
  276. model.addAttribute("countries", countries);
  277. model.addAttribute("genretypeenums", Arrays.asList(GenreTypeEnum.values()));
  278. model.addAttribute("emailAddress", sessionObj.getAttribute("emailAddress"));
  279. }
  280. /**
  281. * Thanks.
  282. *
  283. * @return the string
  284. */
  285. @RequestMapping(value = "/thanks", produces = "text/html")
  286. public String thanks() {
  287. return "signup/thanks";
  288. }
  289. /**
  290. * Error.
  291. *
  292. * @return the string
  293. */
  294. @RequestMapping(value = "/error", produces = "text/html")
  295. public String error() {
  296. return "signup/error";
  297. }
  298. /**
  299. * Sets the person.
  300. *
  301. * @param person the person
  302. * @param personForm the person form
  303. * @param address the address
  304. * @param user the user
  305. * @param configNotifications the config notifications
  306. */
  307. void setPerson(Person person, PersonRegistrationForm personForm, Address address, User user, ConfigNotification configNotifications){
  308. address.setAddress(personForm.getAddress());
  309. address.setCity(personForm.getCity());
  310. address.setProvince(personForm.getProvince());
  311. address.setCountry(personForm.getCountry());
  312. address.setPostalCode(personForm.getPostalCode());
  313. configNotifications.setClaimDonation(true);
  314. configNotifications.setComplaintReceived(true);
  315. configNotifications.setDonationGoods(true);
  316. configNotifications.setDonationReceived(true);
  317. configNotifications.setNeeds(true);
  318. configNotifications.setPublicactionStatus(true);
  319. configNotifications.setReceiveMails(true);
  320. configNotifications.setDonationRequest(true);
  321. configNotifications.setStateComplaintFiled(true);
  322. configNotifications.setStatistics(true);
  323. configNotifications.setThanksToDonation(true);
  324. user.setConfigNotification(configNotifications);
  325. person.setUser(user);
  326. person.setAddress(address);
  327. person.setFirstName(personForm.getFirstName());
  328. person.setLastName(personForm.getLastName());
  329. person.setPersonalDescription(personForm.getPersonalDescription());
  330. person.setGenreType(personForm.getGenreType());
  331. person.setDate(personForm.getDate());
  332. person.setIdentification(personForm.getIdentification());
  333. person.setProfilePicture(iService.getDefaultPersonImage());
  334. person.setPhone(personForm.getPhone());
  335. person.setCellPhone(personForm.getCellPhone());
  336. }
  337. /**
  338. * Sets the institution.
  339. *
  340. * @param institution the institution
  341. * @param institutionForm the institution form
  342. * @param address the address
  343. * @param user the user
  344. * @param configNotifications the config notifications
  345. */
  346. void setInstitution(Institution institution, InstitutionRegistrationForm institutionForm, Address address, User user, ConfigNotification configNotifications){
  347. address.setAddress(institutionForm.getAddress());
  348. address.setCity(institutionForm.getCity());
  349. address.setProvince(institutionForm.getProvince());
  350. address.setCountry(institutionForm.getCountry());
  351. address.setPostalCode(institutionForm.getPostalCode());
  352. configNotifications.setComplaintReceived(true);
  353. configNotifications.setDonationGoods(true);
  354. configNotifications.setDonationReceived(true);
  355. configNotifications.setPublicactionStatus(true);
  356. configNotifications.setReceiveMails(true);
  357. configNotifications.setStateComplaintFiled(true);
  358. configNotifications.setStatistics(true);
  359. configNotifications.setSuscriptions(true);
  360. user.setConfigNotification(configNotifications);
  361. institution.setUser(user);
  362. institution.setAddress(address);
  363. institution.setSocialReason(institutionForm.getSocialReason());
  364. institution.setDate(institutionForm.getDate());
  365. institution.setProfilePicture(iService.getDefaultInstitutionImage());
  366. institution.setPhone(institutionForm.getPhone());
  367. institution.setCellPhone(institutionForm.getCellPhone());
  368. institution.setCbu(institutionForm.getCbu());
  369. institution.setShortDescription(institutionForm.getShortDescription());
  370. institution.setLongDescription(institutionForm.getLongDescription());
  371. institution.setCategory(institutionForm.getCategory());
  372. }
  373. /**
  374. * Persist person.
  375. *
  376. * @param person the person
  377. * @param address the address
  378. * @param configNotifications the config notifications
  379. */
  380. @Transactional
  381. private void persistPerson(Person person, Address address, ConfigNotification configNotifications){
  382. address.persist();
  383. configNotifications.persist();
  384. person.persist();
  385. }
  386. /**
  387. * Persist istitution.
  388. *
  389. * @param institution the institution
  390. * @param address the address
  391. * @param configNotifications the config notifications
  392. */
  393. @Transactional
  394. private void persistIstitution(Institution institution, Address address, ConfigNotification configNotifications){
  395. address.persist();
  396. configNotifications.persist();
  397. institution.persist();
  398. }
  399. }