View Javadoc

1   package org.appfuse.webapp.action;
2   
3   import org.appfuse.Constants;
4   import org.appfuse.model.Role;
5   import org.appfuse.model.User;
6   import org.appfuse.service.RoleManager;
7   import org.appfuse.service.UserExistsException;
8   import org.appfuse.util.ConvertUtil;
9   import org.appfuse.webapp.util.RequestUtil;
10  import org.springframework.mail.MailException;
11  import org.springframework.security.access.AccessDeniedException;
12  import org.springframework.security.authentication.AuthenticationTrustResolver;
13  import org.springframework.security.authentication.AuthenticationTrustResolverImpl;
14  import org.springframework.security.core.Authentication;
15  import org.springframework.security.core.context.SecurityContext;
16  import org.springframework.security.core.context.SecurityContextHolder;
17  
18  import javax.servlet.http.HttpServletRequest;
19  import javax.servlet.http.HttpServletResponse;
20  import java.io.IOException;
21  import java.io.Serializable;
22  import java.util.List;
23  import java.util.Map;
24  
25  /**
26   * JSF Page class to handle editing a user with a form.
27   *
28   * @author mraible
29   */
30  public class UserForm extends BasePage implements Serializable {
31      private static final long serialVersionUID = -1141119853856863204L;
32      private RoleManager roleManager;
33      private String id;
34      private User user = new User();
35      private Map<String, String> availableRoles;
36      private String[] userRoles;
37  
38      public void setId(String id) {
39          this.id = id;
40      }
41  
42      public User getUser() {
43          return user;
44      }
45  
46      public void setUser(User user) {
47          this.user = user;
48      }
49  
50      public void setRoleManager(RoleManager roleManager) {
51          this.roleManager = roleManager;
52      }
53  
54      public String add() {
55          user = new User();
56          user.setEnabled(true);
57          user.addRole(new Role(Constants.USER_ROLE));
58          return "editProfile";
59      }
60  
61      public String cancel() {
62          if (log.isDebugEnabled()) {
63              log.debug("Entering 'cancel' method");
64          }
65  
66          if (!"list".equals(getParameter("from"))) {
67              return "home";
68          } else {
69              return "cancel";
70          }
71      }
72  
73      public String edit() {
74          HttpServletRequest request = getRequest();
75  
76          // if a user's id is passed in
77          if (id != null) {
78              log.debug("Editing user, id is: " + id);
79              // lookup the user using that id
80              user = userManager.getUser(id);
81          } else {
82              user = userManager.getUserByUsername(request.getRemoteUser());
83          } 
84  
85          if (user.getUsername() != null) {
86              user.setConfirmPassword(user.getPassword());
87              if (isRememberMe()) {
88                  // if user logged in with remember me, display a warning that they can't change passwords
89                  log.debug("checking for remember me login...");
90                  log.trace("User '" + user.getUsername() + "' logged in with cookie");
91                  addMessage("userProfile.cookieLogin");
92              }
93          }
94  
95          return "editProfile";
96      }
97  
98      /**
99       * Convenience method for view templates to check if the user is logged in with RememberMe (cookies).
100      * @return true/false - false if user interactively logged in.
101      */
102     public boolean isRememberMe() {
103         if (user != null && user.getId() == null) return false; // check for add()
104         
105         AuthenticationTrustResolver resolver = new AuthenticationTrustResolverImpl();
106         SecurityContext ctx = SecurityContextHolder.getContext();
107 
108         if (ctx != null) {
109             Authentication auth = ctx.getAuthentication();
110             return resolver.isRememberMe(auth);
111         }
112         return false;
113     }
114 
115     public String save() throws IOException {
116         // workaround for plain ol' HTML input tags that don't seem to set
117         // properties on the managed bean
118         setUserRoles(getRequest().getParameterValues("userForm:userRoles"));
119 
120         for (int i = 0; (userRoles != null) && (i < userRoles.length); i++) {
121             String roleName = userRoles[i];
122             user.addRole(roleManager.getRole(roleName));
123         }
124 
125         // Check for Integers set to 0: happens in Tomcat, not in Jetty
126         if (user.getId() != null && user.getId() == 0 ||
127             user.getVersion() != null && user.getVersion() == 0) {
128             user.setId(null);
129             user.setVersion(null);
130         }
131 
132         Integer originalVersion = user.getVersion();
133 
134         try {
135             user = userManager.saveUser(user);
136         } catch (AccessDeniedException ade) {
137             // thrown by UserSecurityAdvice configured in aop:advisor userManagerSecurity
138             log.warn(ade.getMessage());
139             getResponse().sendError(HttpServletResponse.SC_FORBIDDEN);
140             return null;
141         } catch (UserExistsException e) {
142             addError("errors.existing.user", new Object[] { user.getUsername(), user.getEmail() });
143 
144             // reset the version # to what was passed in
145             user.setVersion(originalVersion);
146             return "editProfile";
147         }
148 
149         if (!"list".equals(getParameter("from"))) {
150             // add success messages
151             addMessage("user.saved");
152 
153             // return to main Menu
154             return "home";
155         } else {
156             // add success messages
157             if ("".equals(getParameter("userForm:version"))) {
158                 addMessage("user.added", user.getFullName());
159 
160                 try {
161                     sendUserMessage(user, getText("newuser.email.message",
162                                     user.getFullName()), RequestUtil.getAppURL(getRequest()));
163                 } catch (MailException me) {
164                     addError(me.getCause().getLocalizedMessage());
165                 }
166 
167                 return "list"; // return to list screen
168             } else {
169                 addMessage("user.updated.byAdmin", user.getFullName());
170                 return "editProfile"; // return to current page
171             }
172         }
173     }
174 
175     public String delete() {
176         userManager.removeUser(getUser().getId().toString());
177         addMessage("user.deleted", getUser().getFullName());
178 
179         return "list";
180     }
181 
182     /**
183      * Convenience method to determine if the user came from the list screen
184      * @return String
185      */
186     public String getFrom() {
187         if ((id != null) || (getParameter("editUser:add") != null) ||
188                 ("list".equals(getParameter("from")))) {
189             return "list";
190         }
191 
192         return "";
193     }
194 
195     // Form Controls ==========================================================
196     @SuppressWarnings("unchecked")
197     public Map<String, String> getAvailableRoles() {
198         if (availableRoles == null) {
199             List roles = (List) getServletContext().getAttribute(Constants.AVAILABLE_ROLES);
200             availableRoles = ConvertUtil.convertListToMap(roles);
201         }
202 
203         return availableRoles;
204     }
205 
206     public String[] getUserRoles() {
207         userRoles = new String[user.getRoles().size()];
208 
209         int i = 0;
210 
211         if (userRoles.length > 0) {
212             for (Role role : user.getRoles()) {
213                 userRoles[i] = role.getName();
214                 i++;
215             }
216         }
217 
218         return userRoles;
219     }
220 
221     public void setUserRoles(String[] userRoles) {
222         this.userRoles = userRoles;
223     }
224     
225     public String getCountry() {
226         return getUser().getAddress().getCountry();
227     }
228     
229     // for some reason, the country drop-down won't do 
230     // getUser().getAddress().setCountry(value)
231     public void setCountry(String country) {
232         getUser().getAddress().setCountry(country);
233     }
234 }