View Javadoc

1   package net.ramapuram.thomas.webapp.action;
2   
3   import com.opensymphony.xwork2.Preparable;
4   import org.apache.struts2.ServletActionContext;
5   import net.ramapuram.thomas.Constants;
6   import net.ramapuram.thomas.model.Role;
7   import net.ramapuram.thomas.model.User;
8   import net.ramapuram.thomas.service.UserExistsException;
9   import net.ramapuram.thomas.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.util.ArrayList;
22  import java.util.List;
23  
24  /**
25   * Action for facilitating User Management feature.
26   */
27  public class UserAction extends BaseAction implements Preparable {
28      private static final long serialVersionUID = 6776558938712115191L;
29      private List<User> users;
30      private User user;
31      private String id;
32      private String query;
33  
34      /**
35       * Grab the entity from the database before populating with request parameters
36       */
37      public void prepare() {
38          // prevent failures on new
39          if (getRequest().getMethod().equalsIgnoreCase("post") && (!"".equals(getRequest().getParameter("user.id")))) {
40              user = userManager.getUser(getRequest().getParameter("user.id"));
41          }
42      }
43  
44      /**
45       * Holder for users to display on list screen
46       *
47       * @return list of users
48       */
49      public List<User> getUsers() {
50          return users;
51      }
52  
53      public void setId(String id) {
54          this.id = id;
55      }
56  
57      public User getUser() {
58          return user;
59      }
60  
61      public void setUser(User user) {
62          this.user = user;
63      }
64  
65      public void setQ(String q) {
66          this.query = q;
67      }
68  
69      /**
70       * Delete the user passed in.
71       *
72       * @return success
73       */
74      public String delete() {
75          userManager.removeUser(user.getId().toString());
76          List<Object> args = new ArrayList<Object>();
77          args.add(user.getFullName());
78          saveMessage(getText("user.deleted", args));
79  
80          return SUCCESS;
81      }
82  
83      /**
84       * Grab the user from the database based on the "id" passed in.
85       *
86       * @return success if user found
87       * @throws IOException can happen when sending a "forbidden" from response.sendError()
88       */
89      public String edit() throws IOException {
90          HttpServletRequest request = getRequest();
91          boolean editProfile = (request.getRequestURI().indexOf("editProfile") > -1);
92  
93          // if URL is "editProfile" - make sure it's the current user
94          if (editProfile && ((request.getParameter("id") != null) || (request.getParameter("from") != null))) {
95              ServletActionContext.getResponse().sendError(HttpServletResponse.SC_FORBIDDEN);
96              log.warn("User '" + request.getRemoteUser() + "' is trying to edit user '" +
97                      request.getParameter("id") + "'");
98              return null;
99          }
100 
101         // if a user's id is passed in
102         if (id != null) {
103             // lookup the user using that id
104             user = userManager.getUser(id);
105         } else if (editProfile) {
106             user = userManager.getUserByUsername(request.getRemoteUser());
107         } else {
108             user = new User();
109             user.addRole(new Role(Constants.USER_ROLE));
110         }
111 
112         if (user.getUsername() != null) {
113             user.setConfirmPassword(user.getPassword());
114 
115             // if user logged in with remember me, display a warning that they can't change passwords
116             log.debug("checking for remember me login...");
117 
118             AuthenticationTrustResolver resolver = new AuthenticationTrustResolverImpl();
119             SecurityContext ctx = SecurityContextHolder.getContext();
120 
121             if (ctx != null) {
122                 Authentication auth = ctx.getAuthentication();
123 
124                 if (resolver.isRememberMe(auth)) {
125                     getSession().setAttribute("cookieLogin", "true");
126                     saveMessage(getText("userProfile.cookieLogin"));
127                 }
128             }
129         }
130 
131         return SUCCESS;
132     }
133 
134     /**
135      * Default: just returns "success"
136      *
137      * @return "success"
138      */
139     public String execute() {
140         return SUCCESS;
141     }
142 
143     /**
144      * Sends users to "mainMenu" when !from.equals("list"). Sends everyone else to "cancel"
145      *
146      * @return "mainMenu" or "cancel"
147      */
148     public String cancel() {
149         if (!"list".equals(from)) {
150             return "mainMenu";
151         }
152         return "cancel";
153     }
154 
155     /**
156      * Save user
157      *
158      * @return success if everything worked, otherwise input
159      * @throws Exception when setting "access denied" fails on response
160      */
161     public String save() throws Exception {
162 
163         Integer originalVersion = user.getVersion();
164 
165         boolean isNew = ("".equals(getRequest().getParameter("user.version")));
166         // only attempt to change roles if user is admin
167         // for other users, prepare() method will handle populating
168         if (getRequest().isUserInRole(Constants.ADMIN_ROLE)) {
169             user.getRoles().clear(); // APF-788: Removing roles from user doesn't work
170             String[] userRoles = getRequest().getParameterValues("userRoles");
171 
172             for (int i = 0; userRoles != null && i < userRoles.length; i++) {
173                 String roleName = userRoles[i];
174                 user.addRole(roleManager.getRole(roleName));
175             }
176         }
177 
178         try {
179             userManager.saveUser(user);
180         } catch (AccessDeniedException ade) {
181             // thrown by UserSecurityAdvice configured in aop:advisor userManagerSecurity
182             log.warn(ade.getMessage());
183             getResponse().sendError(HttpServletResponse.SC_FORBIDDEN);
184             return null;
185         } catch (UserExistsException e) {
186             List<Object> args = new ArrayList<Object>();
187             args.add(user.getUsername());
188             args.add(user.getEmail());
189             addActionError(getText("errors.existing.user", args));
190 
191             // reset the version # to what was passed in
192             user.setVersion(originalVersion);
193             // redisplay the unencrypted passwords
194             user.setPassword(user.getConfirmPassword());
195             return INPUT;
196         }
197 
198         if (!"list".equals(from)) {
199             // add success messages
200             saveMessage(getText("user.saved"));
201             return "mainMenu";
202         } else {
203             // add success messages
204             List<Object> args = new ArrayList<Object>();
205             args.add(user.getFullName());
206             if (isNew) {
207                 saveMessage(getText("user.added", args));
208                 // Send an account information e-mail
209                 mailMessage.setSubject(getText("signup.email.subject"));
210                 try {
211                     sendUserMessage(user, getText("newuser.email.message", args), RequestUtil.getAppURL(getRequest()));
212                 } catch (MailException me) {
213                     addActionError(me.getCause().getLocalizedMessage());
214                 }
215                 return SUCCESS;
216             } else {
217                 saveMessage(getText("user.updated.byAdmin", args));
218                 return INPUT;
219             }
220         }
221     }
222 
223     /**
224      * Fetch all users from database and put into local "users" variable for retrieval in the UI.
225      *
226      * @return "success" if no exceptions thrown
227      */
228     public String list() {
229         users = userManager.search(query);
230         return SUCCESS;
231     }
232 
233 }