View Javadoc

1   package com.panogenesis.webapp.action;
2   
3   import java.util.Locale;
4   
5   import javax.servlet.http.HttpServletRequest;
6   import javax.servlet.http.HttpServletResponse;
7   import javax.servlet.http.HttpSession;
8   
9   import org.apache.commons.lang.StringUtils;
10  import com.panogenesis.Constants;
11  import com.panogenesis.model.Role;
12  import com.panogenesis.model.User;
13  import com.panogenesis.service.RoleManager;
14  import com.panogenesis.service.UserManager;
15  import com.panogenesis.service.UserExistsException;
16  import com.panogenesis.util.StringUtil;
17  import com.panogenesis.webapp.util.RequestUtil;
18  import org.springframework.validation.BindException;
19  import org.springframework.web.servlet.ModelAndView;
20  import org.springframework.web.servlet.view.RedirectView;
21  
22  /***
23   * Implementation of <strong>SimpleFormController</strong> that interacts with
24   * the {@link UserManager} to retrieve/persist values to the database.
25   *
26   * <p><a href="UserFormController.java.html"><i>View Source</i></a></p>
27   *
28   * @author <a href="mailto:matt@raibledesigns.com">Matt Raible</a>
29   */
30  public class UserFormController extends BaseFormController {
31      private RoleManager roleManager;
32  
33      /***
34       * @param roleManager The roleManager to set.
35       */
36      public void setRoleManager(RoleManager roleManager) {
37          this.roleManager = roleManager;
38      }
39  
40      public ModelAndView processFormSubmission(HttpServletRequest request,
41                                                HttpServletResponse response,
42                                                Object command,
43                                                BindException errors)
44      throws Exception {
45          if (request.getParameter("cancel") != null) {
46              if (!StringUtils.equals(request.getParameter("from"), "list")) {
47                  return new ModelAndView(new RedirectView("mainMenu.html"));
48              } else {
49                  return new ModelAndView(new RedirectView("users.html"));
50              }
51          }
52  
53          return super.processFormSubmission(request, response, command, errors);
54      }
55  
56      public ModelAndView onSubmit(HttpServletRequest request,
57                                   HttpServletResponse response, Object command,
58                                   BindException errors)
59      throws Exception {
60          if (log.isDebugEnabled()) {
61              log.debug("entering 'onSubmit' method...");
62          }
63  
64          User user = (User) command;
65          Locale locale = request.getLocale();
66  
67          if (request.getParameter("delete") != null) {
68              mgr.removeUser(user.getUsername());
69              saveMessage(request, getText("user.deleted", user.getFullName(), locale));
70  
71              return new ModelAndView(new RedirectView("users.html"));
72          } else {
73              if ("true".equals(request.getParameter("encryptPass"))) {
74                  String algorithm =
75                      (String) getConfiguration().get(Constants.ENC_ALGORITHM);
76  
77                  if (algorithm == null) { // should only happen for test case
78  
79                      if (log.isDebugEnabled()) {
80                          log.debug("assuming testcase, setting algorithm to 'SHA'");
81                      }
82  
83                      algorithm = "SHA";
84                  }
85  
86                  user.setPassword(StringUtil.encodePassword(user.getPassword(),
87                                                             algorithm));
88              }
89  
90              String[] userRoles = request.getParameterValues("userRoles");
91  
92              if (userRoles != null) {
93                  // for some reason, Spring seems to hang on to the roles in
94                  // the User object, even though isSessionForm() == false
95                  user.getRoles().clear();
96                  for (int i = 0; i < userRoles.length; i++) {
97                      String roleName = userRoles[i];
98                      user.addRole(roleManager.getRole(roleName));
99                  }
100             }
101 
102             try {
103                 mgr.saveUser(user);
104             } catch (UserExistsException e) {
105                 log.warn(e.getMessage());
106 
107                 errors.rejectValue("username", "errors.existing.user",
108                                    new Object[] {
109                                        user.getUsername(), user.getEmail()
110                                    }, "duplicate user");
111 
112                 // redisplay the unencrypted passwords
113                 user.setPassword(user.getConfirmPassword());
114 
115                 return showForm(request, response, errors);
116             }
117 
118             if (!StringUtils.equals(request.getParameter("from"), "list")) {
119                 HttpSession session = request.getSession();
120                 session.setAttribute(Constants.USER_KEY, user);
121 
122                 // update the user's remember me cookie if they didn't login
123                 // with a cookie
124                 if ((RequestUtil.getCookie(request, Constants.LOGIN_COOKIE) != null) &&
125                         (session.getAttribute("cookieLogin") == null)) {
126                     // delete all user cookies and add a new one
127                     mgr.removeLoginCookies(user.getUsername());
128 
129                     String autoLogin =
130                         mgr.createLoginCookie(user.getUsername());
131                     RequestUtil.setCookie(response, Constants.LOGIN_COOKIE,
132                                           autoLogin, request.getContextPath());
133                 }
134 
135                 saveMessage(request, getText("user.saved", user.getFullName(), locale));
136 
137                 // return to main Menu
138                 return new ModelAndView(new RedirectView("mainMenu.html"));
139             } else {
140                 if (StringUtils.isBlank(request.getParameter("version"))) {
141                     saveMessage(request,
142                                 getText("user.added", user.getFullName(), locale));
143 
144                     // Send an account information e-mail
145                     message.setSubject(getText("signup.email.subject", locale));
146                     sendUserMessage(user,
147                                     getText("newuser.email.message",
148                                             user.getFullName(), locale),
149                                     RequestUtil.getAppURL(request));
150 
151                     return showNewForm(request, response);
152                 } else {
153                     saveMessage(request,
154                                 getText("user.updated.byAdmin",
155                                         user.getFullName(), locale));
156                 }
157             }
158         }
159 
160         return showForm(request, response, errors);
161     }
162 
163     protected ModelAndView showForm(HttpServletRequest request,
164                                     HttpServletResponse response,
165                                     BindException errors)
166     throws Exception {
167         if (request.getRequestURI().indexOf("editProfile") > -1) {
168             // if URL is "editProfile" - make sure it's the current user
169             // reject if username passed in or "list" parameter passed in
170             // someone that is trying this probably knows the AppFuse code
171             // but it's a legitimate bug, so I'll fix it. ;-)
172             if ((request.getParameter("username") != null) ||
173                     (request.getParameter("from") != null)) {
174                 response.sendError(HttpServletResponse.SC_FORBIDDEN);
175                 log.warn("User '" + request.getRemoteUser() +
176                          "' is trying to edit user '" +
177                          request.getParameter("username") + "'");
178 
179                 return null;
180             }
181         }
182 
183         // prevent ordinary users from calling a GET on editUser.html
184         // unless a bind error exists.
185         if ((request.getRequestURI().indexOf("editUser") > -1) &&
186                 (!request.isUserInRole(Constants.ADMIN_ROLE) &&
187                 (errors.getErrorCount() == 0) && // be nice to server-side validation for editProfile
188                 (request.getRemoteUser() != null))) { // be nice to unit tests
189             response.sendError(HttpServletResponse.SC_FORBIDDEN);
190 
191             return null;
192         }
193 
194         return super.showForm(request, response, errors);
195     }
196 
197     protected Object formBackingObject(HttpServletRequest request)
198     throws Exception {
199         String username = request.getParameter("username");
200 
201         if (request.getSession().getAttribute("cookieLogin") != null) {
202             saveMessage(request, getText("userProfile.cookieLogin", request.getLocale()));
203         }
204 
205         User user = null;
206 
207         if (request.getRequestURI().indexOf("editProfile") > -1) {
208             user = mgr.getUser(getUser(request).getUsername());
209         } else if (!StringUtils.isBlank(username) &&
210                        !"".equals(request.getParameter("version"))) {
211             user = mgr.getUser(username);
212         } else {
213             user = new User();
214             user.addRole(new Role(Constants.USER_ROLE));
215         }
216 
217         user.setConfirmPassword(user.getPassword());
218 
219         return user;
220     }
221 
222     protected void onBind(HttpServletRequest request, Object command)
223     throws Exception {
224         // if the user is being deleted, turn off validation
225         if (request.getParameter("delete") != null) {
226             super.setValidateOnBinding(false);
227         } else {
228             super.setValidateOnBinding(true);
229         }
230     }
231 }