Guest User

sdf

a guest
Apr 12th, 2012
30
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.93 KB | None | 0 0
  1. /**
  2. * The contents of this file are subject to the OpenMRS Public License
  3. * Version 1.0 (the "License"); you may not use this file except in
  4. * compliance with the License. You may obtain a copy of the License at
  5. * http://license.openmrs.org
  6. *
  7. * Software distributed under the License is distributed on an "AS IS"
  8. * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
  9. * License for the specific language governing rights and limitations
  10. * under the License.
  11. *
  12. * Copyright (C) OpenMRS, LLC. All Rights Reserved.
  13. */
  14. package org.openmrs.web.controller;
  15.  
  16. import java.util.Date;
  17. import java.util.HashMap;
  18. import java.util.Locale;
  19. import java.util.Map;
  20. import java.util.regex.Matcher;
  21. import java.util.regex.Pattern;
  22.  
  23. import javax.servlet.ServletException;
  24. import javax.servlet.http.HttpServletRequest;
  25. import javax.servlet.http.HttpServletResponse;
  26. import javax.servlet.http.HttpSession;
  27.  
  28. import org.apache.commons.logging.Log;
  29. import org.apache.commons.logging.LogFactory;
  30. import org.openmrs.PersonName;
  31. import org.openmrs.User;
  32. import org.openmrs.api.APIException;
  33. import org.openmrs.api.LocationService;
  34. import org.openmrs.api.PasswordException;
  35. import org.openmrs.api.UserService;
  36. import org.openmrs.api.context.Context;
  37. import org.openmrs.util.OpenmrsConstants;
  38. import org.openmrs.util.OpenmrsUtil;
  39. import org.openmrs.util.PrivilegeConstants;
  40. import org.openmrs.web.OptionsForm;
  41. import org.openmrs.web.WebConstants;
  42. import org.openmrs.web.WebUtil;
  43. import org.openmrs.web.user.UserProperties;
  44. import org.springframework.validation.BindException;
  45. import org.springframework.web.servlet.ModelAndView;
  46. import org.springframework.web.servlet.mvc.SimpleFormController;
  47. import org.springframework.web.servlet.view.RedirectView;
  48.  
  49. /**
  50. * This is the controller for the "My Profile" page. This lets logged in users set personal
  51. * preferences, update their own information, etc.
  52. *
  53. * @see OptionsForm
  54. */
  55. public class OptionsFormController extends SimpleFormController {
  56.  
  57. /** Logger for this class and subclasses */
  58. protected final Log log = LogFactory.getLog(getClass());
  59.  
  60. /**
  61. * @see org.springframework.web.servlet.mvc.AbstractFormController#processFormSubmission(javax.servlet.http.HttpServletRequest,
  62. * javax.servlet.http.HttpServletResponse, java.lang.Object,
  63. * org.springframework.validation.BindException)
  64. */
  65. protected ModelAndView processFormSubmission(HttpServletRequest request, HttpServletResponse response, Object object,
  66. BindException errors) throws Exception {
  67. OptionsForm opts = (OptionsForm) object;
  68.  
  69. if (opts.getUsername().length() > 0) {
  70. if (opts.getUsername().length() < 3) {
  71. errors.rejectValue("username", "error.username.weak");
  72. }
  73. if (opts.getUsername().charAt(0) < 'A' || opts.getUsername().charAt(0) > 'z') {
  74. errors.rejectValue("username", "error.username.invalid");
  75. }
  76.  
  77. }
  78. if (opts.getUsername().length() > 0)
  79.  
  80. if (!opts.getOldPassword().equals("")) {
  81. if (opts.getNewPassword().equals(""))
  82. errors.rejectValue("newPassword", "error.password.weak");
  83. else if (!opts.getNewPassword().equals(opts.getConfirmPassword())) {
  84. errors.rejectValue("newPassword", "error.password.match");
  85. errors.rejectValue("confirmPassword", "error.password.match");
  86. }
  87. }
  88.  
  89. if (!opts.getSecretQuestionPassword().equals("")) {
  90. if (!opts.getSecretAnswerConfirm().equals(opts.getSecretAnswerNew())) {
  91. errors.rejectValue("secretAnswerNew", "error.options.secretAnswer.match");
  92. errors.rejectValue("secretAnswerConfirm", "error.options.secretAnswer.match");
  93. }
  94. if (opts.getSecretAnswerNew().isEmpty()) {
  95. errors.rejectValue("secretAnswerNew", "error.options.secretAnswer.empty");
  96. }
  97. if (opts.getSecretQuestionNew().isEmpty()) {
  98. errors.rejectValue("secretQuestionNew", "error.options.secretQuestion.empty");
  99. }
  100. }
  101.  
  102. return super.processFormSubmission(request, response, object, errors);
  103. }
  104.  
  105. /**
  106. * The onSubmit function receives the form/command object that was modified by the input form
  107. * and saves it to the db
  108. *
  109. * @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest,
  110. * javax.servlet.http.HttpServletResponse, java.lang.Object,
  111. * org.springframework.validation.BindException)
  112. */
  113. protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object obj,
  114. BindException errors) throws Exception {
  115.  
  116. HttpSession httpSession = request.getSession();
  117.  
  118. String view = getFormView();
  119.  
  120. if (!errors.hasErrors()) {
  121. User loginUser = Context.getAuthenticatedUser();
  122. UserService us = Context.getUserService();
  123. User user = null;
  124. try {
  125. Context.addProxyPrivilege(PrivilegeConstants.VIEW_USERS);
  126. user = us.getUser(loginUser.getUserId());
  127. }
  128. finally {
  129. Context.removeProxyPrivilege(PrivilegeConstants.VIEW_USERS);
  130. }
  131.  
  132. OptionsForm opts = (OptionsForm) obj;
  133.  
  134. Map<String, String> properties = user.getUserProperties();
  135.  
  136. properties.put(OpenmrsConstants.USER_PROPERTY_DEFAULT_LOCATION, opts.getDefaultLocation());
  137.  
  138. Locale locale = WebUtil.normalizeLocale(opts.getDefaultLocale());
  139. if (locale != null)
  140. properties.put(OpenmrsConstants.USER_PROPERTY_DEFAULT_LOCALE, locale.toString());
  141.  
  142. properties.put(OpenmrsConstants.USER_PROPERTY_PROFICIENT_LOCALES, WebUtil.sanitizeLocales(opts
  143. .getProficientLocales()));
  144. properties.put(OpenmrsConstants.USER_PROPERTY_SHOW_RETIRED, opts.getShowRetiredMessage().toString());
  145. properties.put(OpenmrsConstants.USER_PROPERTY_SHOW_VERBOSE, opts.getVerbose().toString());
  146. properties.put(OpenmrsConstants.USER_PROPERTY_NOTIFICATION, opts.getNotification() == null ? "" : opts
  147. .getNotification().toString());
  148. properties.put(OpenmrsConstants.USER_PROPERTY_NOTIFICATION_ADDRESS, opts.getNotificationAddress() == null ? ""
  149. : opts.getNotificationAddress().toString());
  150.  
  151. if (!opts.getOldPassword().equals("")) {
  152. try {
  153. String password = opts.getNewPassword();
  154.  
  155. // check password strength
  156. if (password.length() > 0) {
  157. try {
  158. OpenmrsUtil.validatePassword(user.getUsername(), password, String.valueOf(user.getUserId()));
  159. }
  160. catch (PasswordException e) {
  161. errors.reject(e.getMessage());
  162. }
  163. if (password.equals(opts.getOldPassword()) && !errors.hasErrors())
  164. errors.reject("error.password.different");
  165. }
  166.  
  167. if (!errors.hasErrors()) {
  168. us.changePassword(opts.getOldPassword(), password);
  169. opts.setSecretQuestionPassword(password);
  170. new UserProperties(user.getUserProperties()).setSupposedToChangePassword(false);
  171. }
  172. }
  173. catch (APIException e) {
  174. errors.rejectValue("oldPassword", "error.password.match");
  175. }
  176. } else {
  177. // if they left the old password blank but filled in new
  178. // password
  179. if (!opts.getNewPassword().equals("")) {
  180. errors.rejectValue("oldPassword", "error.password.incorrect");
  181. }
  182. }
  183.  
  184. if (!opts.getSecretQuestionPassword().equals("")) {
  185. if (!errors.hasErrors()) {
  186. try {
  187. user.setSecretQuestion(opts.getSecretQuestionNew());
  188. us.changeQuestionAnswer(opts.getSecretQuestionPassword(), opts.getSecretQuestionNew(), opts
  189. .getSecretAnswerNew());
  190. }
  191. catch (APIException e) {
  192. errors.rejectValue("secretQuestionPassword", "error.password.match");
  193. }
  194. }
  195. } else if (!opts.getSecretAnswerNew().equals("")) {
  196. // if they left the old password blank but filled in new
  197. // password
  198. errors.rejectValue("secretQuestionPassword", "error.password.incorrect");
  199. }
  200.  
  201. if (opts.getUsername().length() > 0 && !errors.hasErrors()) {
  202. try {
  203. Context.addProxyPrivilege(PrivilegeConstants.VIEW_USERS);
  204. if (us.hasDuplicateUsername(user)) {
  205. errors.rejectValue("username", "error.username.taken");
  206. }
  207. }
  208. finally {
  209. Context.removeProxyPrivilege(PrivilegeConstants.VIEW_USERS);
  210. }
  211. }
  212.  
  213. String notifyType = opts.getNotification();
  214. if (notifyType != null) {
  215. if (notifyType.equals("internal") || notifyType.equals("internalProtected") || notifyType.equals("email")) {
  216. if (opts.getNotificationAddress().isEmpty()) {
  217. errors.reject("error.options.notificationAddress.empty");
  218. } else {
  219. String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
  220. Pattern pattern = Pattern.compile(EMAIL_PATTERN);
  221. Matcher matcher = pattern.matcher(opts.getNotificationAddress());
  222. if (matcher.matches() == false) {
  223. errors.reject("error.options.notificationAddress.invalid");
  224. }
  225. }
  226. }
  227. }
  228.  
  229. if (!errors.hasErrors()) {
  230.  
  231. user.setUsername(opts.getUsername());
  232. user.setUserProperties(properties);
  233.  
  234. // new name
  235. PersonName newPersonName = opts.getPersonName();
  236.  
  237. // existing name
  238. PersonName existingPersonName = user.getPersonName();
  239.  
  240. // if two are not equal then make the new one the preferred,
  241. // make the old one voided
  242. if (!existingPersonName.equalsContent(newPersonName)) {
  243. existingPersonName.setPreferred(false);
  244. existingPersonName.setVoided(true);
  245. existingPersonName.setVoidedBy(user);
  246. existingPersonName.setDateVoided(new Date());
  247. existingPersonName.setVoidReason("Changed name on own options form");
  248.  
  249. newPersonName.setPreferred(true);
  250. user.addName(newPersonName);
  251. }
  252.  
  253. try {
  254. Context.addProxyPrivilege(PrivilegeConstants.EDIT_USERS);
  255. Context.addProxyPrivilege(PrivilegeConstants.VIEW_USERS);
  256. us.saveUser(user, null);
  257. //trigger updating of the javascript file cache
  258. PseudoStaticContentController.invalidateCachedResources(properties);
  259. // update login user object so that the new name is visible
  260. // in the webapp
  261. Context.refreshAuthenticatedUser();
  262. }
  263. finally {
  264. Context.removeProxyPrivilege(PrivilegeConstants.EDIT_USERS);
  265. Context.removeProxyPrivilege(PrivilegeConstants.VIEW_USERS);
  266. }
  267.  
  268. httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "options.saved");
  269. } else {
  270. return super.processFormSubmission(request, response, opts, errors);
  271. }
  272.  
  273. view = getSuccessView();
  274. }
  275. return new ModelAndView(new RedirectView(view));
  276. }
  277.  
  278. /**
  279. * This is called prior to displaying a form for the first time. It tells Spring the
  280. * form/command object to load into the request
  281. *
  282. * @see org.springframework.web.servlet.mvc.AbstractFormController#formBackingObject(javax.servlet.http.HttpServletRequest)
  283. */
  284. protected Object formBackingObject(HttpServletRequest request) throws ServletException {
  285.  
  286. OptionsForm opts = new OptionsForm();
  287.  
  288. if (Context.isAuthenticated()) {
  289. User user = Context.getAuthenticatedUser();
  290.  
  291. Map<String, String> props = user.getUserProperties();
  292. opts.setDefaultLocation(props.get(OpenmrsConstants.USER_PROPERTY_DEFAULT_LOCATION));
  293. opts.setDefaultLocale(props.get(OpenmrsConstants.USER_PROPERTY_DEFAULT_LOCALE));
  294. opts.setProficientLocales(props.get(OpenmrsConstants.USER_PROPERTY_PROFICIENT_LOCALES));
  295. opts.setShowRetiredMessage(new Boolean(props.get(OpenmrsConstants.USER_PROPERTY_SHOW_RETIRED)));
  296. opts.setVerbose(new Boolean(props.get(OpenmrsConstants.USER_PROPERTY_SHOW_VERBOSE)));
  297. opts.setUsername(user.getUsername());
  298. opts.setSecretQuestionNew(user.getSecretQuestion());
  299. // Get a copy of the current person name and clear the id so that
  300. // they are separate objects
  301. PersonName personName = PersonName.newInstance(user.getPersonName());
  302. personName.setPersonNameId(null);
  303. opts.setPersonName(personName);
  304. opts.setNotification(props.get(OpenmrsConstants.USER_PROPERTY_NOTIFICATION));
  305. opts.setNotificationAddress(props.get(OpenmrsConstants.USER_PROPERTY_NOTIFICATION_ADDRESS));
  306. }
  307.  
  308. return opts;
  309. }
  310.  
  311. /**
  312. * Called prior to form display. Allows for data to be put in the request to be used in the view
  313. *
  314. * @see org.springframework.web.servlet.mvc.SimpleFormController#referenceData(javax.servlet.http.HttpServletRequest)
  315. */
  316. protected Map<String, Object> referenceData(HttpServletRequest request) throws Exception {
  317.  
  318. HttpSession httpSession = request.getSession();
  319.  
  320. Map<String, Object> map = new HashMap<String, Object>();
  321.  
  322. if (Context.isAuthenticated()) {
  323.  
  324. LocationService ls = Context.getLocationService();
  325.  
  326. // set location options
  327. map.put("locations", ls.getAllLocations());
  328.  
  329. // set language/locale options
  330. map.put("languages", Context.getAdministrationService().getPresentationLocales());
  331.  
  332. String resetPassword = (String) httpSession.getAttribute("resetPassword");
  333. if (resetPassword == null)
  334. resetPassword = "";
  335. else
  336. httpSession.removeAttribute("resetPassword");
  337. map.put("resetPassword", resetPassword);
  338.  
  339. }
  340.  
  341. return map;
  342. }
  343. }
Advertisement
Add Comment
Please, Sign In to add comment