Index: build.xml =================================================================== RCS file: /cvs/appfuse/build.xml,v retrieving revision 1.98 diff -u -r1.98 build.xml --- build.xml 19 Aug 2005 10:58:40 -0000 1.98 +++ build.xml 28 Aug 2005 21:32:50 -0000 @@ -324,8 +324,6 @@ servletspec="2.3" sessiontimeout="10" destdir="${webapp.target}/WEB-INF" distributable="false" displayname="${ant.project.name}"> - - - - - - - - - - + Index: extras/ibatis/src/dao/org/appfuse/dao/ibatis/UserDAOiBatis.java =================================================================== RCS file: /cvs/appfuse/extras/ibatis/src/dao/org/appfuse/dao/ibatis/UserDAOiBatis.java,v retrieving revision 1.6 diff -u -r1.6 UserDAOiBatis.java --- extras/ibatis/src/dao/org/appfuse/dao/ibatis/UserDAOiBatis.java 6 Oct 2004 08:09:14 -0000 1.6 +++ extras/ibatis/src/dao/org/appfuse/dao/ibatis/UserDAOiBatis.java 28 Aug 2005 22:47:00 -0000 @@ -9,7 +9,6 @@ import org.appfuse.dao.UserDAO; import org.appfuse.model.Role; import org.appfuse.model.User; -import org.appfuse.model.UserCookie; import org.springframework.orm.ObjectRetrievalFailureException; import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport; @@ -29,15 +28,13 @@ * @return a populated user object */ public User getUser(String username) { - User user = - (User) getSqlMapClientTemplate().queryForObject("getUser", username); + User user = (User) getSqlMapClientTemplate().queryForObject("getUser", username); if (user == null) { logger.warn("uh oh, user not found..."); throw new ObjectRetrievalFailureException(User.class, username); } else { - List roles = - getSqlMapClientTemplate().queryForList("getUserRoles", user); + List roles = getSqlMapClientTemplate().queryForList("getUserRoles", user); user.setRoles(new HashSet(roles)); } @@ -54,8 +51,7 @@ for (int i = 0; i < users.size(); i++) { user = (User) users.get(i); - List roles = - getSqlMapClientTemplate().queryForList("getUserRoles", user); + List roles = getSqlMapClientTemplate().queryForList("getUserRoles", user); user.setRoles(new HashSet(roles)); users.set(i, user); } @@ -79,9 +75,7 @@ newRole.put("username", user.getUsername()); newRole.put("roleName", role.getName()); - List userRoles = - getSqlMapClientTemplate().queryForList("getUserRoles", - user.getUsername()); + List userRoles = getSqlMapClientTemplate().queryForList("getUserRoles", user.getUsername()); if (userRoles.isEmpty()) { getSqlMapClientTemplate().update("addUserRole", newRole); @@ -111,53 +105,7 @@ */ public void removeUser(String username) { User user = getUser(username); - removeUserCookies(user.getUsername()); deleteUserRoles(user); getSqlMapClientTemplate().update("deleteUser", user); - } - - /** - * @see org.appfuse.dao.UserDAO#getUserCookie(java.lang.String) - */ - public UserCookie getUserCookie(UserCookie userCookie) { - List cookies = - getSqlMapClientTemplate().queryForList("getUserCookies", userCookie); - - if (cookies.size() == 0) { - return null; - } - - return (UserCookie) cookies.get(0); - } - - /** - * @see org.appfuse.dao.UserDAO#removeUserCookies(java.lang.String) - */ - public void removeUserCookies(String username) { - // delete any cookies associated with this user - UserCookie c = new UserCookie(); - c.setUsername(username); - - getSqlMapClientTemplate().update("deleteUserCookies", c); - } - - /** - * @see org.appfuse.dao.UserDAO#saveUserCookie(org.appfuse.model.UserCookie) - */ - public void saveUserCookie(UserCookie cookie) { - if (cookie.getId() == null) { - Long pk = - (Long) getSqlMapClientTemplate().queryForObject("getUserCookieId", - null); - - if (pk == null) { - pk = new Long(0); - } - - cookie.setId(new Long(pk.longValue() + 1)); - getSqlMapClientTemplate().update("addUserCookie", cookie); - } else { - getSqlMapClientTemplate().update("updateUserCookie", cookie); - } } } Index: extras/ibatis/src/dao/org/appfuse/dao/ibatis/sql/UserSQL.xml =================================================================== RCS file: /cvs/appfuse/extras/ibatis/src/dao/org/appfuse/dao/ibatis/sql/UserSQL.xml,v retrieving revision 1.8 diff -u -r1.8 UserSQL.xml --- extras/ibatis/src/dao/org/appfuse/dao/ibatis/sql/UserSQL.xml 7 Jan 2005 20:59:48 -0000 1.8 +++ extras/ibatis/src/dao/org/appfuse/dao/ibatis/sql/UserSQL.xml 28 Aug 2005 22:47:36 -0000 @@ -99,41 +99,4 @@ delete from user_role where username = #username#; ]]> - - - - - - - - - - - - - - - - Index: extras/jsf/build.xml =================================================================== RCS file: /cvs/appfuse/extras/jsf/build.xml,v retrieving revision 1.18 diff -u -r1.18 build.xml --- extras/jsf/build.xml 10 Aug 2005 15:21:44 -0000 1.18 +++ extras/jsf/build.xml 29 Aug 2005 00:02:07 -0000 @@ -376,8 +376,6 @@ servletspec="2.3" sessiontimeout="10" destdir="${webapp.target}/WEB-INF" distributable="false" displayname="${ant.project.name}"> - - - - 0) { - for (Iterator it = user.getRoles().iterator(); it.hasNext();) { - Role role = (Role) it.next(); - - userRoles[i] = role.getName(); - i++; - } - } - - return userRoles; - } - - public void setUserRoles(String[] userRoles) { - this.userRoles = userRoles; - } - - public String getCountry() { - return getUser().getAddress().getCountry(); - } - - // for some reason, the country drop-down won't do - // getUser().getAddress().setCountry(value) - public void setCountry(String country) { - getUser().getAddress().setCountry(country); - } -} +package org.appfuse.webapp.action; + +import java.io.Serializable; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; + +import net.sf.acegisecurity.Authentication; +import net.sf.acegisecurity.AuthenticationTrustResolver; +import net.sf.acegisecurity.AuthenticationTrustResolverImpl; +import net.sf.acegisecurity.context.ContextHolder; +import net.sf.acegisecurity.context.security.SecureContext; + +import org.apache.commons.lang.StringUtils; +import org.appfuse.Constants; +import org.appfuse.model.Role; +import org.appfuse.model.User; +import org.appfuse.service.RoleManager; +import org.appfuse.service.UserExistsException; +import org.appfuse.util.ConvertUtil; +import org.appfuse.util.StringUtil; +import org.appfuse.webapp.util.RequestUtil; + +/** + * JSF Page class to handle editing a user with a form. + * + * @author mraible + */ +public class UserForm extends BasePage implements Serializable { + private RoleManager roleManager; + private String from; + private String username; + private User user = new User(); + private Map availableRoles; + private String[] userRoles; + + public void setUsername(String username) { + this.username = username; + } + + public String getUsername() { + return username; + } + + public User getUser() { + return user; + } + + public void setUser(User user) { + this.user = user; + } + + public void setRoleManager(RoleManager roleManager) { + this.roleManager = roleManager; + } + + public String cancel() { + if (log.isDebugEnabled()) { + log.debug("Entering 'cancel' method"); + } + + if (!StringUtils.equals(getParameter("from"), "list")) { + return "mainMenu"; + } else { + return "cancel"; + } + } + + public String edit() { + HttpServletRequest request = getRequest(); + + // if a user's username is passed in + if (username != null) { + // lookup the user using that id + user = userManager.getUser(username); + } else if (username == null) { + user = userManager.getUser(request.getRemoteUser()); + } else { + user = new User(); + user.addRole(new Role(Constants.USER_ROLE)); + } + + if (user.getUsername() != null) { + user.setConfirmPassword(user.getPassword()); + + // if user logged in with remember me, display a warning that they can't change passwords + log.debug("checking for remember me login..."); + + AuthenticationTrustResolver resolver = new AuthenticationTrustResolverImpl(); + SecureContext ctx = (SecureContext) ContextHolder.getContext(); + + if (ctx != null) { + Authentication auth = ctx.getAuthentication(); + + if (resolver.isRememberMe(auth)) { + getSession().setAttribute("cookieLogin", "true"); + log.trace("User '" + user.getUsername() + "' logged in with cookie"); + addMessage("userProfile.cookieLogin"); + } + } + } + + return "editProfile"; + } + + public String save() { + String password = user.getPassword(); + String originalPassword = getParameter("userForm:originalPassword"); + + Boolean encrypt = (Boolean) getConfiguration().get(Constants.ENCRYPT_PASSWORD); + boolean doEncrypt = (encrypt != null) ? encrypt.booleanValue() : false; + + if (doEncrypt && (StringUtils.equals(getParameter("encryptPass"), "true") || + !StringUtils.equals(password, originalPassword))) { + String algorithm = (String) getConfiguration().get(Constants.ENC_ALGORITHM); + + if (algorithm == null) { // should only happen for test case + log.debug("assuming testcase, setting algorigthm to 'SHA'"); + algorithm = "SHA"; + } + + user.setPassword(StringUtil.encodePassword(password, algorithm)); + } + + // workaround for plain ol' HTML input tags that don't seem to set + // properties on the managed bean + setUserRoles(getRequest().getParameterValues("userForm:userRoles")); + + for (int i = 0; (userRoles != null) && (i < userRoles.length); i++) { + String roleName = userRoles[i]; + user.addRole(roleManager.getRole(roleName)); + } + + try { + userManager.saveUser(user); + } catch (UserExistsException e) { + log.warn(e.getMessage()); + addError("errors.existing.user", + new Object[] { user.getUsername(), user.getEmail() }); + + return "editProfile"; + } + + if (!StringUtils.equals(getParameter("from"), "list")) { + HttpSession session = getSession(); + HttpServletRequest request = getRequest(); + + session.setAttribute(Constants.USER_KEY, user); + + // add success messages + addMessage("user.saved"); + + // return a forward to main Menu + return "mainMenu"; + } else { + // add success messages + if ("".equals(getParameter("userForm:version"))) { + addMessage("user.added", user.getFullName()); + + sendUserMessage(user, + getText("newuser.email.message", + user.getFullName()), + RequestUtil.getAppURL(getRequest())); + + return "list"; // return to list screen + } else { + addMessage("user.updated.byAdmin", user.getFullName()); + + return "editProfile"; // return to current page + } + } + } + + public String delete() { + userManager.removeUser(getUser().getUsername()); + addMessage("user.deleted", getUser().getFullName()); + + return "list"; + } + + /** + * Convenience method to determine if the user came from the list screen + * @return String + */ + public String getFrom() { + if ((username != null) || (getParameter("editUser:add") != null) || + ("list".equals(getParameter("from")))) { + return "list"; + } + + return ""; + } + + // Form Controls ========================================================== + public Map getAvailableRoles() { + if (availableRoles == null) { + List roles = + (List) getServletContext().getAttribute(Constants.AVAILABLE_ROLES); + availableRoles = ConvertUtil.convertListToMap(roles); + } + + return availableRoles; + } + + public String[] getUserRoles() { + userRoles = new String[user.getRoles().size()]; + + int i = 0; + + if (userRoles.length > 0) { + for (Iterator it = user.getRoles().iterator(); it.hasNext();) { + Role role = (Role) it.next(); + + userRoles[i] = role.getName(); + i++; + } + } + + return userRoles; + } + + public void setUserRoles(String[] userRoles) { + this.userRoles = userRoles; + } + + public String getCountry() { + return getUser().getAddress().getCountry(); + } + + // for some reason, the country drop-down won't do + // getUser().getAddress().setCountry(value) + public void setCountry(String country) { + getUser().getAddress().setCountry(country); + } +} Index: extras/jsf/test/web/web-tests.xml =================================================================== RCS file: /cvs/appfuse/extras/jsf/test/web/web-tests.xml,v retrieving revision 1.6 diff -u -r1.6 web-tests.xml --- extras/jsf/test/web/web-tests.xml 28 Aug 2005 21:15:52 -0000 1.6 +++ extras/jsf/test/web/web-tests.xml 29 Aug 2005 00:34:38 -0000 @@ -1,237 +1,237 @@ - - - - - -]> - - - - - - - - - - - Successfully ran all User JSP tests! - - - - - - &config; - - &login; - - - - - - - - &config; - - &login; - - - - - - - - - - &config; - - - - - - - - - - - - - &config; - - &login; - - - - - - - - - - &config; - - &login; - - - - - - - - - - &config; - - &login; - - - - - - - - - - - - - - &config; - - &login; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - &config; - - - - - - - - - - - - - - - - - - - - - - - - - - - - &config; - - &login; - - - - - - - - - - &config; - - &login; - - - - - - - - - - &config; - - &login; - - - - - - - + + + + + +]> + + + + + + + + + + + Successfully ran all User JSP tests! + + + + + + &config; + + &login; + + + + + + + + &config; + + &login; + + + + + + + + + + &config; + + + + + + + + + + + + + &config; + + &login; + + + + + + + + + + &config; + + &login; + + + + + + + + + + &config; + + &login; + + + + + + + + + + + + + + &config; + + &login; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + &config; + + + + + + + + + + + + + + + + + + + + + + + + + + + + &config; + + &login; + + + + + + + + + + &config; + + &login; + + + + + + + + + + &config; + + &login; + + + + + + + Index: extras/jsf/web/loginForm.jsp =================================================================== RCS file: /cvs/appfuse/extras/jsf/web/loginForm.jsp,v retrieving revision 1.2 diff -u -r1.2 loginForm.jsp --- extras/jsf/web/loginForm.jsp 18 Mar 2005 23:13:01 -0000 1.2 +++ extras/jsf/web/loginForm.jsp 29 Aug 2005 00:07:42 -0000 @@ -1,73 +1,68 @@ -<%@ include file="/common/taglibs.jsp"%> - -
-<%-- If you don't want to encrypt passwords programmatically, or you don't - care about using SSL for the login, you can change this form's action - to "j_security_check" --%> -
" - onsubmit="saveUsername(this);return validateForm(this)"> - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -
- " - alt="" class="icon" /> - -
-
-
- - - -
- - - -
- - -
- - - " tabindex="4" /> - " tabindex="5" - onclick="document.getElementById('j_username').focus()" /> -

- - - -
-
-
- -<%@ include file="/scripts/login.js"%> +<%@ include file="/common/taglibs.jsp"%> + +
+
" + onsubmit="saveUsername(this);return validateForm(this)"> + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ " + alt="" class="icon" /> + +
+
+
+ + + +
+ + + +
+ + +
+ " tabindex="4" /> + " tabindex="5" + onclick="document.getElementById('j_username').focus()" /> +

+ + + +
+
+
+ +<%@ include file="/scripts/login.js"%> Index: extras/spring/build.xml =================================================================== RCS file: /cvs/appfuse/extras/spring/build.xml,v retrieving revision 1.59 diff -u -r1.59 build.xml --- extras/spring/build.xml 10 Aug 2005 15:21:44 -0000 1.59 +++ extras/spring/build.xml 29 Aug 2005 00:02:07 -0000 @@ -271,8 +271,6 @@ servletspec="2.3" sessiontimeout="10" destdir="${webapp.target}/WEB-INF" distributable="false" displayname="${ant.project.name}"> - - - - - * View Source - *

- * - * @author Matt Raible - */ -public class SignupController extends BaseFormController { - private RoleManager roleManager; - - /** - * @param roleManager The roleManager to set. - */ - public void setRoleManager(RoleManager roleManager) { - this.roleManager = roleManager; - } - - public ModelAndView onSubmit(HttpServletRequest request, - HttpServletResponse response, Object command, - BindException errors) - throws Exception { - if (log.isDebugEnabled()) { - log.debug("entering 'onSubmit' method..."); - } - - User user = (User) command; - Locale locale = request.getLocale(); - - String algorithm = - (String) getConfiguration().get(Constants.ENC_ALGORITHM); - - if (algorithm == null) { // should only happen for test case - if (log.isDebugEnabled()) { - log.debug("assuming testcase, setting algorithm to 'SHA'"); - } - algorithm = "SHA"; - } - - user.setPassword(StringUtil.encodePassword(user.getPassword(), algorithm)); - user.setEnabled(Boolean.TRUE); - - // Set the default user role on this new user - user.addRole(roleManager.getRole(Constants.USER_ROLE)); - - try { - this.getUserManager().saveUser(user); - } catch (UserExistsException e) { - log.warn(e.getMessage()); - - errors.rejectValue("username", "errors.existing.user", - new Object[] { - user.getUsername(), user.getEmail() - }, "duplicate user"); - - // redisplay the unencrypted passwords - user.setPassword(user.getConfirmPassword()); - return showForm(request, response, errors); - } - - // Set cookies for auto-magical login ;-) - String loginCookie = this.getUserManager().createLoginCookie(user.getUsername()); - RequestUtil.setCookie(response, Constants.LOGIN_COOKIE, loginCookie, - request.getContextPath()); - - saveMessage(request, getText("user.registered", user.getUsername(), locale)); - - request.getSession().setAttribute(Constants.REGISTERED, Boolean.TRUE); - - // Send user an e-mail - if (log.isDebugEnabled()) { - log.debug("Sending user '" + user.getUsername() - + "' an account information e-mail"); - } - - // Send an account information e-mail - message.setSubject(getText("signup.email.subject", locale)); - sendUserMessage(user, getText("signup.email.message", locale), - RequestUtil.getAppURL(request)); - - return new ModelAndView(getSuccessView()); - } - - protected Object formBackingObject(HttpServletRequest request) - throws Exception { - return new User(); - } -} +package org.appfuse.webapp.action; + +import java.util.Locale; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.appfuse.Constants; +import org.appfuse.model.User; +import org.appfuse.service.RoleManager; +import org.appfuse.service.UserExistsException; +import org.appfuse.util.StringUtil; +import org.appfuse.webapp.util.RequestUtil; +import org.springframework.validation.BindException; +import org.springframework.web.servlet.ModelAndView; + + +/** + * Controller to signup new users. + * + *

+ * View Source + *

+ * + * @author Matt Raible + */ +public class SignupController extends BaseFormController { + private RoleManager roleManager; + + /** + * @param roleManager The roleManager to set. + */ + public void setRoleManager(RoleManager roleManager) { + this.roleManager = roleManager; + } + + public ModelAndView onSubmit(HttpServletRequest request, + HttpServletResponse response, Object command, + BindException errors) + throws Exception { + if (log.isDebugEnabled()) { + log.debug("entering 'onSubmit' method..."); + } + + User user = (User) command; + Locale locale = request.getLocale(); + + Boolean encrypt = (Boolean) getConfiguration().get(Constants.ENCRYPT_PASSWORD); + + if (encrypt != null && encrypt.booleanValue()) { + String algorithm = (String) getConfiguration().get(Constants.ENC_ALGORITHM); + + if (algorithm == null) { // should only happen for test case + log.debug("assuming testcase, setting algorithm to 'SHA'"); + algorithm = "SHA"; + } + + user.setPassword(StringUtil.encodePassword(user.getPassword(), algorithm)); + } + + user.setEnabled(Boolean.TRUE); + + // Set the default user role on this new user + user.addRole(roleManager.getRole(Constants.USER_ROLE)); + + try { + this.getUserManager().saveUser(user); + } catch (UserExistsException e) { + log.warn(e.getMessage()); + + errors.rejectValue("username", "errors.existing.user", + new Object[] { + user.getUsername(), user.getEmail() + }, "duplicate user"); + + // redisplay the unencrypted passwords + user.setPassword(user.getConfirmPassword()); + return showForm(request, response, errors); + } + + saveMessage(request, getText("user.registered", user.getUsername(), locale)); + request.getSession().setAttribute(Constants.REGISTERED, Boolean.TRUE); + + // Send user an e-mail + if (log.isDebugEnabled()) { + log.debug("Sending user '" + user.getUsername() + "' an account information e-mail"); + } + + // Send an account information e-mail + message.setSubject(getText("signup.email.subject", locale)); + sendUserMessage(user, getText("signup.email.message", locale), + RequestUtil.getAppURL(request)); + + return new ModelAndView(getSuccessView()); + } + + protected Object formBackingObject(HttpServletRequest request) + throws Exception { + return new User(); + } +} Index: extras/spring/src/web/org/appfuse/webapp/action/UserFormController.java =================================================================== RCS file: /cvs/appfuse/extras/spring/src/web/org/appfuse/webapp/action/UserFormController.java,v retrieving revision 1.24 diff -u -r1.24 UserFormController.java --- extras/spring/src/web/org/appfuse/webapp/action/UserFormController.java 21 Apr 2005 05:13:26 -0000 1.24 +++ extras/spring/src/web/org/appfuse/webapp/action/UserFormController.java 29 Aug 2005 02:33:44 -0000 @@ -1,231 +1,231 @@ -package org.appfuse.webapp.action; - -import java.util.Locale; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - -import org.apache.commons.lang.StringUtils; -import org.appfuse.Constants; -import org.appfuse.model.Role; -import org.appfuse.model.User; -import org.appfuse.service.RoleManager; -import org.appfuse.service.UserManager; -import org.appfuse.service.UserExistsException; -import org.appfuse.util.StringUtil; -import org.appfuse.webapp.util.RequestUtil; -import org.springframework.validation.BindException; -import org.springframework.web.servlet.ModelAndView; -import org.springframework.web.servlet.view.RedirectView; - -/** - * Implementation of SimpleFormController that interacts with - * the {@link UserManager} to retrieve/persist values to the database. - * - *

View Source

- * - * @author Matt Raible - */ -public class UserFormController extends BaseFormController { - private RoleManager roleManager; - - /** - * @param roleManager The roleManager to set. - */ - public void setRoleManager(RoleManager roleManager) { - this.roleManager = roleManager; - } - - public ModelAndView processFormSubmission(HttpServletRequest request, - HttpServletResponse response, - Object command, - BindException errors) - throws Exception { - if (request.getParameter("cancel") != null) { - if (!StringUtils.equals(request.getParameter("from"), "list")) { - return new ModelAndView(getCancelView()); - } else { - return new ModelAndView(getSuccessView()); - } - } - - return super.processFormSubmission(request, response, command, errors); - } - - public ModelAndView onSubmit(HttpServletRequest request, - HttpServletResponse response, Object command, - BindException errors) - throws Exception { - if (log.isDebugEnabled()) { - log.debug("entering 'onSubmit' method..."); - } - - User user = (User) command; - Locale locale = request.getLocale(); - - if (request.getParameter("delete") != null) { - this.getUserManager().removeUser(user.getUsername()); - saveMessage(request, getText("user.deleted", user.getFullName(), locale)); - - return new ModelAndView(getSuccessView()); - } else { - if ("true".equals(request.getParameter("encryptPass"))) { - String algorithm = - (String) getConfiguration().get(Constants.ENC_ALGORITHM); - - if (algorithm == null) { // should only happen for test case - - if (log.isDebugEnabled()) { - log.debug("assuming testcase, setting algorithm to 'SHA'"); - } - - algorithm = "SHA"; - } - - user.setPassword(StringUtil.encodePassword(user.getPassword(), - algorithm)); - } - - String[] userRoles = request.getParameterValues("userRoles"); - - if (userRoles != null) { - // for some reason, Spring seems to hang on to the roles in - // the User object, even though isSessionForm() == false - user.getRoles().clear(); - for (int i = 0; i < userRoles.length; i++) { - String roleName = userRoles[i]; - user.addRole(roleManager.getRole(roleName)); - } - } - - try { - this.getUserManager().saveUser(user); - } catch (UserExistsException e) { - log.warn(e.getMessage()); - - errors.rejectValue("username", "errors.existing.user", - new Object[] { - user.getUsername(), user.getEmail() - }, "duplicate user"); - - // redisplay the unencrypted passwords - user.setPassword(user.getConfirmPassword()); - - return showForm(request, response, errors); - } - - if (!StringUtils.equals(request.getParameter("from"), "list")) { - HttpSession session = request.getSession(); - session.setAttribute(Constants.USER_KEY, user); - - // update the user's remember me cookie if they didn't login - // with a cookie - if ((RequestUtil.getCookie(request, Constants.LOGIN_COOKIE) != null) && - (session.getAttribute("cookieLogin") == null)) { - // delete all user cookies and add a new one - this.getUserManager().removeLoginCookies(user.getUsername()); - - String autoLogin = - this.getUserManager().createLoginCookie(user.getUsername()); - RequestUtil.setCookie(response, Constants.LOGIN_COOKIE, - autoLogin, request.getContextPath()); - } - - saveMessage(request, getText("user.saved", user.getFullName(), locale)); - - // return to main Menu - return new ModelAndView(new RedirectView("mainMenu.html")); - } else { - if (StringUtils.isBlank(request.getParameter("version"))) { - saveMessage(request, - getText("user.added", user.getFullName(), locale)); - - // Send an account information e-mail - message.setSubject(getText("signup.email.subject", locale)); - sendUserMessage(user, - getText("newuser.email.message", - user.getFullName(), locale), - RequestUtil.getAppURL(request)); - - return showNewForm(request, response); - } else { - saveMessage(request, - getText("user.updated.byAdmin", - user.getFullName(), locale)); - } - } - } - - return showForm(request, response, errors); - } - - protected ModelAndView showForm(HttpServletRequest request, - HttpServletResponse response, - BindException errors) - throws Exception { - if (request.getRequestURI().indexOf("editProfile") > -1) { - // if URL is "editProfile" - make sure it's the current user - // reject if username passed in or "list" parameter passed in - // someone that is trying this probably knows the AppFuse code - // but it's a legitimate bug, so I'll fix it. ;-) - if ((request.getParameter("username") != null) || - (request.getParameter("from") != null)) { - response.sendError(HttpServletResponse.SC_FORBIDDEN); - log.warn("User '" + request.getRemoteUser() + - "' is trying to edit user '" + - request.getParameter("username") + "'"); - - return null; - } - } - - // prevent ordinary users from calling a GET on editUser.html - // unless a bind error exists. - if ((request.getRequestURI().indexOf("editUser") > -1) && - (!request.isUserInRole(Constants.ADMIN_ROLE) && - (errors.getErrorCount() == 0) && // be nice to server-side validation for editProfile - (request.getRemoteUser() != null))) { // be nice to unit tests - response.sendError(HttpServletResponse.SC_FORBIDDEN); - - return null; - } - - return super.showForm(request, response, errors); - } - - protected Object formBackingObject(HttpServletRequest request) - throws Exception { - String username = request.getParameter("username"); - - if (request.getSession().getAttribute("cookieLogin") != null) { - saveMessage(request, getText("userProfile.cookieLogin", request.getLocale())); - } - - User user = null; - - if (request.getRequestURI().indexOf("editProfile") > -1) { - user = this.getUserManager().getUser(getUser(request).getUsername()); - } else if (!StringUtils.isBlank(username) && - !"".equals(request.getParameter("version"))) { - user = this.getUserManager().getUser(username); - } else { - user = new User(); - user.addRole(new Role(Constants.USER_ROLE)); - } - - user.setConfirmPassword(user.getPassword()); - - return user; - } - - protected void onBind(HttpServletRequest request, Object command) - throws Exception { - // if the user is being deleted, turn off validation - if (request.getParameter("delete") != null) { - super.setValidateOnBinding(false); - } else { - super.setValidateOnBinding(true); - } - } -} +package org.appfuse.webapp.action; + +import java.util.Locale; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import net.sf.acegisecurity.Authentication; +import net.sf.acegisecurity.AuthenticationTrustResolver; +import net.sf.acegisecurity.AuthenticationTrustResolverImpl; +import net.sf.acegisecurity.context.ContextHolder; +import net.sf.acegisecurity.context.security.SecureContext; + +import org.apache.commons.lang.StringUtils; +import org.appfuse.Constants; +import org.appfuse.model.Role; +import org.appfuse.model.User; +import org.appfuse.service.RoleManager; +import org.appfuse.service.UserManager; +import org.appfuse.service.UserExistsException; +import org.appfuse.util.StringUtil; +import org.appfuse.webapp.util.RequestUtil; +import org.springframework.validation.BindException; +import org.springframework.web.servlet.ModelAndView; +import org.springframework.web.servlet.view.RedirectView; + +/** + * Implementation of SimpleFormController that interacts with + * the {@link UserManager} to retrieve/persist values to the database. + * + *

View Source

+ * + * @author Matt Raible + */ +public class UserFormController extends BaseFormController { + private RoleManager roleManager; + + /** + * @param roleManager The roleManager to set. + */ + public void setRoleManager(RoleManager roleManager) { + this.roleManager = roleManager; + } + + public ModelAndView processFormSubmission(HttpServletRequest request, + HttpServletResponse response, + Object command, + BindException errors) + throws Exception { + if (request.getParameter("cancel") != null) { + if (!StringUtils.equals(request.getParameter("from"), "list")) { + return new ModelAndView(getCancelView()); + } else { + return new ModelAndView(getSuccessView()); + } + } + + return super.processFormSubmission(request, response, command, errors); + } + + public ModelAndView onSubmit(HttpServletRequest request, + HttpServletResponse response, Object command, + BindException errors) + throws Exception { + if (log.isDebugEnabled()) { + log.debug("entering 'onSubmit' method..."); + } + + User user = (User) command; + Locale locale = request.getLocale(); + + if (request.getParameter("delete") != null) { + this.getUserManager().removeUser(user.getUsername()); + saveMessage(request, getText("user.deleted", user.getFullName(), locale)); + + return new ModelAndView(getSuccessView()); + } else { + Boolean encrypt = (Boolean) getConfiguration().get(Constants.ENCRYPT_PASSWORD); + + if (StringUtils.equals(request.getParameter("encryptPass"), "true") + && (encrypt != null && encrypt.booleanValue())) { + + String algorithm = (String) getConfiguration().get(Constants.ENC_ALGORITHM); + + if (algorithm == null) { // should only happen for test case + + if (log.isDebugEnabled()) { + log.debug("assuming testcase, setting algorithm to 'SHA'"); + } + + algorithm = "SHA"; + } + + user.setPassword(StringUtil.encodePassword(user.getPassword(), algorithm)); + } + + String[] userRoles = request.getParameterValues("userRoles"); + + if (userRoles != null) { + // for some reason, Spring seems to hang on to the roles in + // the User object, even though isSessionForm() == false + user.getRoles().clear(); + for (int i = 0; i < userRoles.length; i++) { + String roleName = userRoles[i]; + user.addRole(roleManager.getRole(roleName)); + } + } + + try { + this.getUserManager().saveUser(user); + } catch (UserExistsException e) { + log.warn(e.getMessage()); + + errors.rejectValue("username", "errors.existing.user", + new Object[] { + user.getUsername(), user.getEmail() + }, "duplicate user"); + + // redisplay the unencrypted passwords + user.setPassword(user.getConfirmPassword()); + + return showForm(request, response, errors); + } + + if (!StringUtils.equals(request.getParameter("from"), "list")) { + HttpSession session = request.getSession(); + session.setAttribute(Constants.USER_KEY, user); + + saveMessage(request, getText("user.saved", user.getFullName(), locale)); + + // return to main Menu + return new ModelAndView(new RedirectView("mainMenu.html")); + } else { + if (StringUtils.isBlank(request.getParameter("version"))) { + saveMessage(request, + getText("user.added", user.getFullName(), locale)); + + // Send an account information e-mail + message.setSubject(getText("signup.email.subject", locale)); + sendUserMessage(user, getText("newuser.email.message", user.getFullName(), locale), + RequestUtil.getAppURL(request)); + + return showNewForm(request, response); + } else { + saveMessage(request, getText("user.updated.byAdmin", user.getFullName(), locale)); + } + } + } + + return showForm(request, response, errors); + } + + protected ModelAndView showForm(HttpServletRequest request, + HttpServletResponse response, + BindException errors) + throws Exception { + if (request.getRequestURI().indexOf("editProfile") > -1) { + // if URL is "editProfile" - make sure it's the current user + // reject if username passed in or "list" parameter passed in + // someone that is trying this probably knows the AppFuse code + // but it's a legitimate bug, so I'll fix it. ;-) + if ((request.getParameter("username") != null) || (request.getParameter("from") != null)) { + response.sendError(HttpServletResponse.SC_FORBIDDEN); + log.warn("User '" + request.getRemoteUser() + "' is trying to edit user '" + + request.getParameter("username") + "'"); + + return null; + } + } + + // prevent ordinary users from calling a GET on editUser.html + // unless a bind error exists. + if ((request.getRequestURI().indexOf("editUser") > -1) && (!request.isUserInRole(Constants.ADMIN_ROLE) && + (errors.getErrorCount() == 0) && // be nice to server-side validation for editProfile + (request.getRemoteUser() != null))) { // be nice to unit tests + response.sendError(HttpServletResponse.SC_FORBIDDEN); + + return null; + } + + return super.showForm(request, response, errors); + } + + protected Object formBackingObject(HttpServletRequest request) + throws Exception { + String username = request.getParameter("username"); + + // if user logged in with remember me, display a warning that they can't change passwords + log.debug("checking for remember me login..."); + + AuthenticationTrustResolver resolver = new AuthenticationTrustResolverImpl(); + SecureContext ctx = (SecureContext) ContextHolder.getContext(); + + if (ctx != null) { + Authentication auth = ctx.getAuthentication(); + + if (resolver.isRememberMe(auth)) { + request.getSession().setAttribute("cookieLogin", "true"); + + // add warning message + saveMessage(request, getText("userProfile.cookieLogin", request.getLocale())); + } + } + + User user = null; + + if (request.getRequestURI().indexOf("editProfile") > -1) { + user = this.getUserManager().getUser(getUser(request).getUsername()); + } else if (!StringUtils.isBlank(username) && !"".equals(request.getParameter("version"))) { + user = this.getUserManager().getUser(username); + } else { + user = new User(); + user.addRole(new Role(Constants.USER_ROLE)); + } + + user.setConfirmPassword(user.getPassword()); + + return user; + } + + protected void onBind(HttpServletRequest request, Object command) + throws Exception { + // if the user is being deleted, turn off validation + if (request.getParameter("delete") != null) { + super.setValidateOnBinding(false); + } else { + super.setValidateOnBinding(true); + } + } +} Index: extras/spring/test/web/web-tests.xml =================================================================== RCS file: /cvs/appfuse/extras/spring/test/web/web-tests.xml,v retrieving revision 1.15 diff -u -r1.15 web-tests.xml --- extras/spring/test/web/web-tests.xml 28 Aug 2005 21:15:53 -0000 1.15 +++ extras/spring/test/web/web-tests.xml 29 Aug 2005 02:33:16 -0000 @@ -1,236 +1,234 @@ - - - - - -]> - - - - - - - - - - Successfully ran all User JSP tests! - - - - - - &config; - - &login; - - - - - - - - &config; - - &login; - - - - - - - - - - &config; - - - - - - - - - - - - - &config; - - &login; - - - - - - - - - - &config; - - &login; - - - - - - - - - - &config; - - &login; - - - - - - - - - - - - - - &config; - - &login; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - &config; - - - - - - - - - - - - - - - - - - - - - - - - - - - - &config; - - &login; - - - - - - - - - - &config; - - &login; - - - - - - - - - - &config; - - &login; - - - - - - - + + + + + +]> + + + + + + + + + + Successfully ran all User JSP tests! + + + + + + &config; + + &login; + + + + + + + + &config; + + &login; + + + + + + + + + + &config; + + + + + + + + + + + + + &config; + + &login; + + + + + + + + + + &config; + + &login; + + + + + + + + + + &config; + + &login; + + + + + + + + + + + + + + &config; + + &login; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + &config; + + + + + + + + + + + + + + + + + + + + + + + + + + + + &config; + + &login; + + + + + + + + + + &config; + + &login; + + + + + + + + + + &config; + + &login; + + + + + + + Index: extras/tapestry/build.xml =================================================================== RCS file: /cvs/appfuse/extras/tapestry/build.xml,v retrieving revision 1.12 diff -u -r1.12 build.xml --- extras/tapestry/build.xml 10 Aug 2005 15:21:45 -0000 1.12 +++ extras/tapestry/build.xml 29 Aug 2005 00:02:08 -0000 @@ -386,8 +386,6 @@ servletspec="2.3" sessiontimeout="10" destdir="${webapp.target}/WEB-INF" distributable="false" displayname="${ant.project.name}"> - - - - "); - - StringBuffer msg = new StringBuffer(); - msg.append(getMessage("signup.email.message")); - msg.append("\n\n" + getMessage("user.username")); - msg.append(": " + user.getUsername() + "\n"); - msg.append(getMessage("user.password") + ": "); - msg.append(user.getPassword()); - msg.append("\n\nLogin at: " + RequestUtil.getAppURL(getRequest())); - message.setText(msg.toString()); - - message.setSubject(getMessage("signup.email.subject")); - - MailEngine engine = (MailEngine) ctx.getBean("mailEngine"); - engine.send(message); - - MainMenu nextPage = (MainMenu) cycle.getPage("mainMenu"); - nextPage.setMessage(getMessage("user.registered")); - cycle.activate(nextPage); - } -} - +package org.appfuse.webapp.action; + +import java.io.IOException; +import java.util.Map; + +import org.apache.commons.lang.StringUtils; +import org.apache.tapestry.IRequestCycle; +import org.apache.tapestry.event.PageEvent; +import org.apache.tapestry.event.PageRenderListener; +import org.apache.tapestry.form.IPropertySelectionModel; +import org.apache.tapestry.valid.IValidationDelegate; +import org.apache.tapestry.valid.ValidationConstraint; +import org.appfuse.Constants; +import org.appfuse.model.User; +import org.appfuse.service.MailEngine; +import org.appfuse.service.RoleManager; +import org.appfuse.service.UserExistsException; +import org.appfuse.service.UserManager; +import org.appfuse.util.StringUtil; +import org.appfuse.webapp.util.RequestUtil; +import org.springframework.context.ApplicationContext; +import org.springframework.mail.SimpleMailMessage; + +public abstract class SignupForm extends BasePage implements PageRenderListener { + private IPropertySelectionModel countries; + + public abstract UserManager getUserManager(); + public abstract void setUserManager(UserManager manager); + public abstract RoleManager getRoleManager(); + public abstract void setRoleManager(RoleManager manager); + public abstract void setUser(User user); + public abstract User getUser(); + + public IPropertySelectionModel getCountries() { + if (countries == null) { + countries = new CountryModel(getLocale()); + } + return countries; + } + + public void pageBeginRender(PageEvent event) { + if (getUser() == null && !event.getRequestCycle().isRewinding()) { + setUser(new User()); + } else if (event.getRequestCycle().isRewinding()) { + setUser(new User()); + } + } + + public void cancel(IRequestCycle cycle) throws IOException { + if (log.isDebugEnabled()) { + log.debug("entered cancel method"); + } + getResponse().sendRedirect(getRequest().getContextPath()); + } + + public void save(IRequestCycle cycle) throws UserExistsException, IOException { + if (log.isDebugEnabled()) { + log.debug("entered save method"); + } + + // make sure the password fields match + IValidationDelegate delegate = getValidationDelegate(); + if (!StringUtils.equals(getUser().getPassword(), getUser().getConfirmPassword())) { + addError(delegate, "confirmPasswordField", + format("errors.twofields", getMessage("user.confirmPassword"), + getMessage("user.password")), + ValidationConstraint.CONSISTENCY); + } + + if (delegate.getHasErrors()) { + return; + } + + User user = getUser(); + + Boolean encrypt = (Boolean) getConfiguration().get(Constants.ENCRYPT_PASSWORD); + + if (encrypt != null && encrypt.booleanValue()) { + String algorithm = (String) getConfiguration().get(Constants.ENC_ALGORITHM); + + if (algorithm == null) { // should only happen for test case + if (log.isDebugEnabled()) { + log.debug("assuming testcase, setting algorithm to 'SHA'"); + } + algorithm = "SHA"; + } + user.setPassword(StringUtil.encodePassword(user.getPassword(), algorithm)); + } + + user.setEnabled(Boolean.TRUE); + + // Set the default user role on this new user + user.addRole(getRoleManager().getRole(Constants.USER_ROLE)); + + getUserManager().saveUser(getUser()); + + try { + getUserManager().saveUser(user); + } catch (UserExistsException e) { + log.warn(e.getMessage()); + addError(delegate, "usernameField", + format("errors.existing.user", user.getUsername(), + user.getEmail()), ValidationConstraint.CONSISTENCY); + // redisplay the unencrypted passwords + user.setPassword(user.getConfirmPassword()); + return; + } + + getSession().setAttribute(Constants.REGISTERED, Boolean.TRUE); + + // Send user an e-mail + if (log.isDebugEnabled()) { + log.debug("Sending user '" + user.getUsername() + "' an account information e-mail"); + } + + Map global = (Map) getGlobal(); + ApplicationContext ctx = (ApplicationContext) global.get(BaseEngine.APPLICATION_CONTEXT_KEY); + + SimpleMailMessage message = (SimpleMailMessage) ctx.getBean("mailMessage"); + message.setTo(user.getFullName() + "<" + user.getEmail() + ">"); + + StringBuffer msg = new StringBuffer(); + msg.append(getMessage("signup.email.message")); + msg.append("\n\n" + getMessage("user.username")); + msg.append(": " + user.getUsername() + "\n"); + msg.append(getMessage("user.password") + ": "); + msg.append(user.getPassword()); + msg.append("\n\nLogin at: " + RequestUtil.getAppURL(getRequest())); + message.setText(msg.toString()); + + message.setSubject(getMessage("signup.email.subject")); + + MailEngine engine = (MailEngine) ctx.getBean("mailEngine"); + engine.send(message); + + getSession().setAttribute("message", getMessage("user.registered")); + getResponse().sendRedirect(getRequest().getContextPath()); + } +} + Index: extras/tapestry/src/web/org/appfuse/webapp/action/UserForm.java =================================================================== RCS file: /cvs/appfuse/extras/tapestry/src/web/org/appfuse/webapp/action/UserForm.java,v retrieving revision 1.5 diff -u -r1.5 UserForm.java --- extras/tapestry/src/web/org/appfuse/webapp/action/UserForm.java 18 Mar 2005 23:13:13 -0000 1.5 +++ extras/tapestry/src/web/org/appfuse/webapp/action/UserForm.java 29 Aug 2005 04:00:09 -0000 @@ -1,251 +1,249 @@ -package org.appfuse.webapp.action; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; - -import org.apache.commons.lang.StringUtils; -import org.apache.tapestry.IRequestCycle; -import org.apache.tapestry.event.PageEvent; -import org.apache.tapestry.event.PageRenderListener; -import org.apache.tapestry.form.IPropertySelectionModel; -import org.apache.tapestry.valid.IValidationDelegate; -import org.apache.tapestry.valid.ValidationConstraint; -import org.appfuse.Constants; -import org.appfuse.model.Role; -import org.appfuse.model.User; -import org.appfuse.service.MailEngine; -import org.appfuse.service.RoleManager; -import org.appfuse.service.UserExistsException; -import org.appfuse.service.UserManager; -import org.appfuse.util.StringUtil; -import org.appfuse.webapp.util.RequestUtil; -import org.springframework.context.ApplicationContext; -import org.springframework.mail.SimpleMailMessage; - -public abstract class UserForm extends BasePage implements PageRenderListener { - private IPropertySelectionModel countries; - private IPropertySelectionModel availableRoles; - public abstract UserManager getUserManager(); - public abstract void setUserManager(UserManager mgr); - public abstract RoleManager getRoleManager(); - public abstract void setRoleManager(RoleManager mgr); - public abstract void setUser(User user); - public abstract User getUser(); - public abstract void setFrom(String from); - public abstract String getFrom(); - - public IPropertySelectionModel getAvailableRoles() { - if (availableRoles == null) { - List roles = - (List) getServletContext().getAttribute(Constants.AVAILABLE_ROLES); - availableRoles = new RoleModel(roles); - } - - return availableRoles; - } - - public IPropertySelectionModel getCountries() { - if (countries == null) { - countries = new CountryModel(getLocale()); - } - - return countries; - } - - public void pageBeginRender(PageEvent event) { - // if user doing an add, create an empty user with default settings - if ((getUser() == null) && !event.getRequestCycle().isRewinding()) { - setUser(new User()); - setFrom("list"); // shows role selection - getUser().addRole(new Role(Constants.USER_ROLE)); - } else if (event.getRequestCycle().isRewinding()) { // before population - setUser(new User()); - } - - // if user logged in with a cookie, display a warning that they - // can't change passwords - if (log.isDebugEnabled()) { - log.debug("checking for cookieLogin..."); - } - - if (getSession().getAttribute("cookieLogin") != null) { - setMessage(getMessage("userProfile.cookieLogin")); - } - } - - public void cancel(IRequestCycle cycle) { - if (log.isDebugEnabled()) { - log.debug("Entering 'cancel' method"); - } - - if (!StringUtils.equals(getRequest().getParameter("from"), "Slist")) { - cycle.activate("mainMenu"); - } else { - cycle.activate("users"); - } - } - - public void save(IRequestCycle cycle) throws UserExistsException { - if (log.isDebugEnabled()) { - log.debug("entered save method"); - } - - // make sure the password fields match - IValidationDelegate delegate = getValidationDelegate(); - - if (!StringUtils.equals(getUser().getPassword(), - getUser().getConfirmPassword())) { - addError(delegate, "confirmPasswordField", - format("errors.twofields", - getMessage("user.confirmPassword"), - getMessage("user.password")), - ValidationConstraint.CONSISTENCY); - } - - if (delegate.getHasErrors()) { - return; - } - - String password = getUser().getPassword(); - String originalPassword = getRequest().getParameter("originalPassword"); - - if (StringUtils.equals(getRequest().getParameter("encryptPass"), "true") || - !StringUtils.equals("S"+password, originalPassword)) { - String algorithm = - (String) getConfiguration().get(Constants.ENC_ALGORITHM); - - if (algorithm == null) { // should only happen for test case - log.debug("assuming testcase, setting algorigthm to 'SHA'"); - algorithm = "SHA"; - } - - getUser().setPassword(StringUtil.encodePassword(password, algorithm)); - } - - // workaround for input tags that don't aren't set by Tapestry (who knows why) - boolean fromList = - StringUtils.equals(getRequest().getParameter("from"), "Slist"); - String[] userRoles = null; - - if (fromList) { - userRoles = getRequest().getParameterValues("userRoles"); - } else { - userRoles = getRequest().getParameterValues("hiddenUserRoles"); - } - - User user = getUser(); - UserManager userManager = getUserManager(); - - user.getRoles().clear(); - for (int i = 0; (userRoles != null) && (i < userRoles.length); i++) { - String roleName = userRoles[i]; - user.addRole(getRoleManager().getRole(roleName)); - } - - try { - userManager.saveUser(user); - } catch (UserExistsException e) { - log.warn(e.getMessage()); - addError(delegate, "emailField", - format("errors.existing.user", user.getUsername(), - user.getEmail()), ValidationConstraint.CONSISTENCY); - return; - } - - HttpSession session = getSession(); - HttpServletRequest request = getRequest(); - - if (!fromList && user.getUsername().equals(getRequest().getRemoteUser())) { - session.setAttribute(Constants.USER_KEY, user); - - // update the user's remember me cookie if they didn't login - // with a cookie - if ((RequestUtil.getCookie(request, Constants.LOGIN_COOKIE) != null) && - (session.getAttribute("cookieLogin") == null)) { - // delete all user cookies and add a new one - userManager.removeLoginCookies(user.getUsername()); - - String autoLogin = - userManager.createLoginCookie(user.getUsername()); - RequestUtil.setCookie(getResponse(), Constants.LOGIN_COOKIE, - autoLogin, request.getContextPath()); - } - - // add success messages - MainMenu nextPage = (MainMenu) cycle.getPage("mainMenu"); - nextPage.setMessage(format("user.saved", user.getFullName())); - cycle.activate(nextPage); - } else { - // add success messages - if ("X".equals(request.getParameter(("version")))) { - sendNewUserEmail(request, user); - UserList nextPage = (UserList) cycle.getPage("users"); - nextPage.setMessage(format("user.added", user.getFullName())); - cycle.activate(nextPage); // return to the list screen - } else { - setMessage(format("user.updated.byAdmin", user.getFullName())); - cycle.activate("userForm"); // return to current page - } - } - } - - public void delete(IRequestCycle cycle) { - if (log.isDebugEnabled()) { - log.debug("entered delete method"); - } - - getUserManager().removeUser(getUser().getUsername()); - - UserList nextPage = (UserList) cycle.getPage("users"); - nextPage.setMessage(format("user.deleted", getUser().getFullName())); - cycle.activate(nextPage); - } - - // Form Controls ========================================================== - public List getUserRoles() { - List selectedRoles = new ArrayList(getUser().getRoles().size()); - - for (Iterator it = getUser().getRoles().iterator(); - (it != null) && it.hasNext();) { - Role role = (Role) it.next(); - selectedRoles.add(role.getName()); - } - - return selectedRoles; - } - - private void sendNewUserEmail(HttpServletRequest request, User user) { - // Send user an e-mail - if (log.isDebugEnabled()) { - log.debug("Sending user '" + user.getUsername() + - "' an account information e-mail"); - } - - Map global = (Map) getGlobal(); - ApplicationContext ctx = - (ApplicationContext) global.get(BaseEngine.APPLICATION_CONTEXT_KEY); - - SimpleMailMessage message = - (SimpleMailMessage) ctx.getBean("mailMessage"); - message.setTo(user.getFullName() + "<" + user.getEmail() + ">"); - - StringBuffer msg = new StringBuffer(); - msg.append(format("newuser.email.message", user.getFullName())); - msg.append("\n\n" + getMessage("user.username")); - msg.append(": " + user.getUsername() + "\n"); - msg.append(getMessage("user.password") + ": "); - msg.append(user.getPassword()); - msg.append("\n\nLogin at: " + RequestUtil.getAppURL(request)); - message.setText(msg.toString()); - - message.setSubject(getMessage("signup.email.subject")); - - MailEngine engine = (MailEngine) ctx.getBean("mailEngine"); - engine.send(message); - } -} +package org.appfuse.webapp.action; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; + +import net.sf.acegisecurity.Authentication; +import net.sf.acegisecurity.AuthenticationTrustResolver; +import net.sf.acegisecurity.AuthenticationTrustResolverImpl; +import net.sf.acegisecurity.context.ContextHolder; +import net.sf.acegisecurity.context.security.SecureContext; + +import org.apache.commons.lang.StringUtils; +import org.apache.tapestry.IRequestCycle; +import org.apache.tapestry.event.PageEvent; +import org.apache.tapestry.event.PageRenderListener; +import org.apache.tapestry.form.IPropertySelectionModel; +import org.apache.tapestry.valid.IValidationDelegate; +import org.apache.tapestry.valid.ValidationConstraint; +import org.appfuse.Constants; +import org.appfuse.model.Role; +import org.appfuse.model.User; +import org.appfuse.service.MailEngine; +import org.appfuse.service.RoleManager; +import org.appfuse.service.UserExistsException; +import org.appfuse.service.UserManager; +import org.appfuse.util.StringUtil; +import org.appfuse.webapp.util.RequestUtil; +import org.springframework.context.ApplicationContext; +import org.springframework.mail.SimpleMailMessage; + +public abstract class UserForm extends BasePage implements PageRenderListener { + private IPropertySelectionModel countries; + private IPropertySelectionModel availableRoles; + public abstract UserManager getUserManager(); + public abstract void setUserManager(UserManager mgr); + public abstract RoleManager getRoleManager(); + public abstract void setRoleManager(RoleManager mgr); + public abstract void setUser(User user); + public abstract User getUser(); + public abstract void setFrom(String from); + public abstract String getFrom(); + + public IPropertySelectionModel getAvailableRoles() { + if (availableRoles == null) { + List roles = + (List) getServletContext().getAttribute(Constants.AVAILABLE_ROLES); + availableRoles = new RoleModel(roles); + } + + return availableRoles; + } + + public IPropertySelectionModel getCountries() { + if (countries == null) { + countries = new CountryModel(getLocale()); + } + + return countries; + } + + public void pageBeginRender(PageEvent event) { + // if user doing an add, create an empty user with default settings + if ((getUser() == null) && !event.getRequestCycle().isRewinding()) { + setUser(new User()); + setFrom("list"); // shows role selection + getUser().addRole(new Role(Constants.USER_ROLE)); + } else if (event.getRequestCycle().isRewinding()) { // before population + setUser(new User()); + } + + // if user logged in with remember me, display a warning that they can't change passwords + log.debug("checking for remember me login..."); + + AuthenticationTrustResolver resolver = new AuthenticationTrustResolverImpl(); + SecureContext ctx = (SecureContext) ContextHolder.getContext(); + + if (ctx != null) { + Authentication auth = ctx.getAuthentication(); + + if (resolver.isRememberMe(auth)) { + getSession().setAttribute("cookieLogin", "true"); + + // add warning message + setMessage(getMessage("userProfile.cookieLogin")); + } + } + } + + public void cancel(IRequestCycle cycle) { + if (log.isDebugEnabled()) { + log.debug("Entering 'cancel' method"); + } + + if (!StringUtils.equals(getRequest().getParameter("from"), "Slist")) { + cycle.activate("mainMenu"); + } else { + cycle.activate("users"); + } + } + + public void save(IRequestCycle cycle) throws UserExistsException { + if (log.isDebugEnabled()) { + log.debug("entered save method"); + } + + // make sure the password fields match + IValidationDelegate delegate = getValidationDelegate(); + + if (!StringUtils.equals(getUser().getPassword(), getUser().getConfirmPassword())) { + addError(delegate, "confirmPasswordField", + format("errors.twofields", + getMessage("user.confirmPassword"), + getMessage("user.password")), + ValidationConstraint.CONSISTENCY); + } + + if (delegate.getHasErrors()) { + return; + } + + String password = getUser().getPassword(); + String originalPassword = getRequest().getParameter("originalPassword"); + + Boolean encrypt = (Boolean) getConfiguration().get(Constants.ENCRYPT_PASSWORD); + boolean doEncrypt = (encrypt != null) ? encrypt.booleanValue() : false; + + if (doEncrypt && (StringUtils.equals(getRequest().getParameter("encryptPass"), "true") || + !StringUtils.equals("S"+password, originalPassword))) { + String algorithm = (String) getConfiguration().get(Constants.ENC_ALGORITHM); + + if (algorithm == null) { // should only happen for test case + log.debug("assuming testcase, setting algorigthm to 'SHA'"); + algorithm = "SHA"; + } + + getUser().setPassword(StringUtil.encodePassword(password, algorithm)); + } + + // workaround for input tags that don't aren't set by Tapestry (who knows why) + boolean fromList = StringUtils.equals(getRequest().getParameter("from"), "Slist"); + String[] userRoles = null; + + if (fromList) { + userRoles = getRequest().getParameterValues("userRoles"); + } else { + userRoles = getRequest().getParameterValues("hiddenUserRoles"); + } + + User user = getUser(); + UserManager userManager = getUserManager(); + + user.getRoles().clear(); + for (int i = 0; (userRoles != null) && (i < userRoles.length); i++) { + String roleName = userRoles[i]; + user.addRole(getRoleManager().getRole(roleName)); + } + + try { + userManager.saveUser(user); + } catch (UserExistsException e) { + log.warn(e.getMessage()); + addError(delegate, "emailField", + format("errors.existing.user", user.getUsername(), + user.getEmail()), ValidationConstraint.CONSISTENCY); + return; + } + + HttpSession session = getSession(); + HttpServletRequest request = getRequest(); + + if (!fromList && user.getUsername().equals(getRequest().getRemoteUser())) { + session.setAttribute(Constants.USER_KEY, user); + + // add success messages + MainMenu nextPage = (MainMenu) cycle.getPage("mainMenu"); + nextPage.setMessage(format("user.saved", user.getFullName())); + cycle.activate(nextPage); + } else { + // add success messages + if ("X".equals(request.getParameter(("version")))) { + sendNewUserEmail(request, user); + UserList nextPage = (UserList) cycle.getPage("users"); + nextPage.setMessage(format("user.added", user.getFullName())); + cycle.activate(nextPage); // return to the list screen + } else { + setMessage(format("user.updated.byAdmin", user.getFullName())); + cycle.activate("userForm"); // return to current page + } + } + } + + public void delete(IRequestCycle cycle) { + if (log.isDebugEnabled()) { + log.debug("entered delete method"); + } + + getUserManager().removeUser(getUser().getUsername()); + + UserList nextPage = (UserList) cycle.getPage("users"); + nextPage.setMessage(format("user.deleted", getUser().getFullName())); + cycle.activate(nextPage); + } + + // Form Controls ========================================================== + public List getUserRoles() { + List selectedRoles = new ArrayList(getUser().getRoles().size()); + + for (Iterator it = getUser().getRoles().iterator(); + (it != null) && it.hasNext();) { + Role role = (Role) it.next(); + selectedRoles.add(role.getName()); + } + + return selectedRoles; + } + + private void sendNewUserEmail(HttpServletRequest request, User user) { + // Send user an e-mail + if (log.isDebugEnabled()) { + log.debug("Sending user '" + user.getUsername() + "' an account information e-mail"); + } + + Map global = (Map) getGlobal(); + ApplicationContext ctx = (ApplicationContext) global.get(BaseEngine.APPLICATION_CONTEXT_KEY); + + SimpleMailMessage message = + (SimpleMailMessage) ctx.getBean("mailMessage"); + message.setTo(user.getFullName() + "<" + user.getEmail() + ">"); + + StringBuffer msg = new StringBuffer(); + msg.append(format("newuser.email.message", user.getFullName())); + msg.append("\n\n" + getMessage("user.username")); + msg.append(": " + user.getUsername() + "\n"); + msg.append(getMessage("user.password") + ": "); + msg.append(user.getPassword()); + msg.append("\n\nLogin at: " + RequestUtil.getAppURL(request)); + message.setText(msg.toString()); + + message.setSubject(getMessage("signup.email.subject")); + + MailEngine engine = (MailEngine) ctx.getBean("mailEngine"); + engine.send(message); + } +} Index: extras/tapestry/test/web/web-tests.xml =================================================================== RCS file: /cvs/appfuse/extras/tapestry/test/web/web-tests.xml,v retrieving revision 1.7 diff -u -r1.7 web-tests.xml --- extras/tapestry/test/web/web-tests.xml 28 Aug 2005 21:15:54 -0000 1.7 +++ extras/tapestry/test/web/web-tests.xml 29 Aug 2005 00:34:29 -0000 @@ -1,237 +1,237 @@ - - - - - -]> - - - - - - - - - - Successfully ran all User HTML tests! - - - - - - &config; - - &login; - - - - - - - - &config; - - &login; - - - - - - - - - - &config; - - - - - - - - - - - - - &config; - - &login; - - - - - - - - - - &config; - - &login; - - - - - - - - - - &config; - - &login; - - - - - - - - - - - - - - &config; - - &login; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - &config; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - &config; - - &login; - - - - - - - - - - &config; - - &login; - - - - - - - - - - &config; - - &login; - - - - - - - + + + + + +]> + + + + + + + + + + Successfully ran all User HTML tests! + + + + + + &config; + + &login; + + + + + + + + &config; + + &login; + + + + + + + + + + &config; + + + + + + + + + + + + + &config; + + &login; + + + + + + + + + + &config; + + &login; + + + + + + + + + + &config; + + &login; + + + + + + + + + + + + + + &config; + + &login; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + &config; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + &config; + + &login; + + + + + + + + + + &config; + + &login; + + + + + + + + + + &config; + + &login; + + + + + + + Index: extras/tapestry/web/pages/loginForm.jsp =================================================================== RCS file: /cvs/appfuse/extras/tapestry/web/pages/loginForm.jsp,v retrieving revision 1.1 diff -u -r1.1 loginForm.jsp --- extras/tapestry/web/pages/loginForm.jsp 5 Dec 2004 21:40:01 -0000 1.1 +++ extras/tapestry/web/pages/loginForm.jsp 29 Aug 2005 00:07:47 -0000 @@ -1,73 +1,68 @@ -<%@ include file="/common/taglibs.jsp"%> - -
-<%-- If you don't want to encrypt passwords programmatically, or you don't - care about using SSL for the login, you can change this form's action - to "j_security_check" --%> -
" - onsubmit="saveUsername(this);return validateForm(this)"> - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -
- " - alt="" class="icon" /> - -
-
-
- - - -
- - - -
- - -
- - - " tabindex="4" /> - " tabindex="5" - onclick="document.getElementById('j_username').focus()" /> -

- - - -
-
-
- -<%@ include file="/scripts/login.js"%> +<%@ include file="/common/taglibs.jsp"%> + +
+
" + onsubmit="saveUsername(this);return validateForm(this)"> + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ " + alt="" class="icon" /> + +
+
+
+ + + +
+ + + +
+ + +
+ " tabindex="4" /> + " tabindex="5" + onclick="document.getElementById('j_username').focus()" /> +

+ + + +
+
+
+ +<%@ include file="/scripts/login.js"%> Index: extras/webwork/build.xml =================================================================== RCS file: /cvs/appfuse/extras/webwork/build.xml,v retrieving revision 1.35 diff -u -r1.35 build.xml --- extras/webwork/build.xml 10 Aug 2005 15:21:45 -0000 1.35 +++ extras/webwork/build.xml 29 Aug 2005 00:02:08 -0000 @@ -306,8 +306,6 @@ servletspec="2.3" sessiontimeout="10" destdir="${webapp.target}/WEB-INF" distributable="false" displayname="${ant.project.name}"> - - - - - - - - -]> - - - - - - - - - - Successfully ran all User JSP tests! - - - - - - &config; - - &login; - - - - - - - - &config; - - &login; - - - - - - - - - - &config; - - - - - - - - - - - - - &config; - - &login; - - - - - - - - - - &config; - - &login; - - - - - - - - - - &config; - - &login; - - - - - - - - - - - - - - &config; - - &login; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - &config; - - - - - - - - - - - - - - - - - - - - - - - - - - - - &config; - - &login; - - - - - - - - - - &config; - - &login; - - - - - - - - - - &config; - - &login; - - - - - - - + + + + + +]> + + + + + + + + + + Successfully ran all User JSP tests! + + + + + + &config; + + &login; + + + + + + + + &config; + + &login; + + + + + + + + + + &config; + + + + + + + + + + + + + &config; + + &login; + + + + + + + + + + &config; + + &login; + + + + + + + + + + &config; + + &login; + + + + + + + + + + + + + + &config; + + &login; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + &config; + + + + + + + + + + + + + + + + + + + + + + + + + + + + &config; + + &login; + + + + + + + + + + &config; + + &login; + + + + + + + + + + &config; + + &login; + + + + + + + Index: metadata/web/filter-mappings.xml =================================================================== RCS file: /cvs/appfuse/metadata/web/filter-mappings.xml,v retrieving revision 1.19 diff -u -r1.19 filter-mappings.xml --- metadata/web/filter-mappings.xml 10 Aug 2005 15:21:46 -0000 1.19 +++ metadata/web/filter-mappings.xml 28 Aug 2005 21:41:18 -0000 @@ -10,18 +10,6 @@ securityFilter *.jsp - - loginFilter - /login.jsp - - - - - - loginFilter - /logout.jsp - - - - - - listenPort_http - - - - listenPort_https - - daoType Index: src/dao/org/appfuse/Constants.java =================================================================== RCS file: /cvs/appfuse/src/dao/org/appfuse/Constants.java,v retrieving revision 1.10 diff -u -r1.10 Constants.java --- src/dao/org/appfuse/Constants.java 28 Aug 2005 21:15:57 -0000 1.10 +++ src/dao/org/appfuse/Constants.java 28 Aug 2005 21:24:55 -0000 @@ -1,104 +1,104 @@ -package org.appfuse; - - -/** - * Constant values used throughout the application. - * - *

- * View Source - *

- * - * @author Matt Raible - */ -public final class Constants { - //~ Static fields/initializers ============================================= - - /** The name of the ResourceBundle used in this application */ - public static final String BUNDLE_KEY = "ApplicationResources"; - - /** The application scoped attribute for persistence engine used */ - public static final String DAO_TYPE = "daoType"; - public static final String DAO_TYPE_HIBERNATE = "hibernate"; - - /** Application scoped attribute for authentication url */ - public static final String AUTH_URL = "authURL"; - - /** Application scoped attributes for SSL Switching */ - public static final String HTTP_PORT = "httpPort"; - public static final String HTTPS_PORT = "httpsPort"; - - /** The application scoped attribute for indicating a secure login */ - public static final String SECURE_LOGIN = "secureLogin"; - - /** The encryption algorithm key to be used for passwords */ - public static final String ENC_ALGORITHM = "algorithm"; - - /** A flag to indicate if passwords should be encrypted */ - public static final String ENCRYPT_PASSWORD = "encryptPassword"; - - /** File separator from System properties */ - public static final String FILE_SEP = System.getProperty("file.separator"); - - /** User home from System properties */ - public static final String USER_HOME = - System.getProperty("user.home") + FILE_SEP; - - /** - * The session scope attribute under which the breadcrumb ArrayStack is - * stored - */ - public static final String BREADCRUMB = "breadcrumbs"; - - /** - * The session scope attribute under which the User object for the - * currently logged in user is stored. - */ - public static final String USER_KEY = "currentUserForm"; - - /** - * The request scope attribute under which an editable user form is stored - */ - public static final String USER_EDIT_KEY = "userForm"; - - /** - * The request scope attribute that holds the user list - */ - public static final String USER_LIST = "userList"; - - /** - * The request scope attribute for indicating a newly-registered user - */ - public static final String REGISTERED = "registered"; - - /** - * The name of the Administrator role, as specified in web.xml - */ - public static final String ADMIN_ROLE = "admin"; - - /** - * The name of the User role, as specified in web.xml - */ - public static final String USER_ROLE = "user"; - - /** - * The name of the user's role list, a request-scoped attribute - * when adding/editing a user. - */ - public static final String USER_ROLES = "userRoles"; - - /** - * The name of the available roles list, a request-scoped attribute - * when adding/editing a user. - */ - public static final String AVAILABLE_ROLES = "availableRoles"; - - /** - * Name of cookie for "Remember Me" functionality. - */ - public static final String LOGIN_COOKIE = "sessionId"; - - /** - * The name of the configuration hashmap stored in application scope. - */ - public static final String CONFIG = "appConfig"; -} +package org.appfuse; + + +/** + * Constant values used throughout the application. + * + *

+ * View Source + *

+ * + * @author Matt Raible + */ +public class Constants { + //~ Static fields/initializers ============================================= + + /** The name of the ResourceBundle used in this application */ + public static final String BUNDLE_KEY = "ApplicationResources"; + + /** The application scoped attribute for persistence engine used */ + public static final String DAO_TYPE = "daoType"; + public static final String DAO_TYPE_HIBERNATE = "hibernate"; + + /** Application scoped attribute for authentication url */ + public static final String AUTH_URL = "authURL"; + + /** Application scoped attributes for SSL Switching */ + public static final String HTTP_PORT = "httpPort"; + public static final String HTTPS_PORT = "httpsPort"; + + /** The application scoped attribute for indicating a secure login */ + public static final String SECURE_LOGIN = "secureLogin"; + + /** The encryption algorithm key to be used for passwords */ + public static final String ENC_ALGORITHM = "algorithm"; + + /** A flag to indicate if passwords should be encrypted */ + public static final String ENCRYPT_PASSWORD = "encryptPassword"; + + /** File separator from System properties */ + public static final String FILE_SEP = System.getProperty("file.separator"); + + /** User home from System properties */ + public static final String USER_HOME = + System.getProperty("user.home") + FILE_SEP; + + /** + * The session scope attribute under which the breadcrumb ArrayStack is + * stored + */ + public static final String BREADCRUMB = "breadcrumbs"; + + /** + * The session scope attribute under which the User object for the + * currently logged in user is stored. + */ + public static final String USER_KEY = "currentUserForm"; + + /** + * The request scope attribute under which an editable user form is stored + */ + public static final String USER_EDIT_KEY = "userForm"; + + /** + * The request scope attribute that holds the user list + */ + public static final String USER_LIST = "userList"; + + /** + * The request scope attribute for indicating a newly-registered user + */ + public static final String REGISTERED = "registered"; + + /** + * The name of the Administrator role, as specified in web.xml + */ + public static final String ADMIN_ROLE = "admin"; + + /** + * The name of the User role, as specified in web.xml + */ + public static final String USER_ROLE = "user"; + + /** + * The name of the user's role list, a request-scoped attribute + * when adding/editing a user. + */ + public static final String USER_ROLES = "userRoles"; + + /** + * The name of the available roles list, a request-scoped attribute + * when adding/editing a user. + */ + public static final String AVAILABLE_ROLES = "availableRoles"; + + /** + * Name of cookie for "Remember Me" functionality. + */ + public static final String LOGIN_COOKIE = "sessionId"; + + /** + * The name of the configuration hashmap stored in application scope. + */ + public static final String CONFIG = "appConfig"; +} Index: src/dao/org/appfuse/dao/UserDAO.java =================================================================== RCS file: /cvs/appfuse/src/dao/org/appfuse/dao/UserDAO.java,v retrieving revision 1.4 diff -u -r1.4 UserDAO.java --- src/dao/org/appfuse/dao/UserDAO.java 3 Apr 2005 18:52:02 -0000 1.4 +++ src/dao/org/appfuse/dao/UserDAO.java 28 Aug 2005 21:22:41 -0000 @@ -3,7 +3,6 @@ import java.util.List; import org.appfuse.model.User; -import org.appfuse.model.UserCookie; /** * User Data Access Object (DAO) interface. @@ -40,23 +39,4 @@ * @param username the user's username */ public void removeUser(String username); - - /** - * Gets a userCookie object from the database, - * based on username and password - * @param cookie with username and password - */ - public UserCookie getUserCookie(UserCookie cookie); - - /** - * Saves a userCookie object to the database - * @param cookie - */ - public void saveUserCookie(UserCookie cookie); - - /** - * Removes all cookies for a specified username - * @param username - */ - public void removeUserCookies(String username); } Index: src/dao/org/appfuse/dao/hibernate/UserDAOHibernate.java =================================================================== RCS file: /cvs/appfuse/src/dao/org/appfuse/dao/hibernate/UserDAOHibernate.java,v retrieving revision 1.7 diff -u -r1.7 UserDAOHibernate.java --- src/dao/org/appfuse/dao/hibernate/UserDAOHibernate.java 7 Dec 2004 17:09:30 -0000 1.7 +++ src/dao/org/appfuse/dao/hibernate/UserDAOHibernate.java 28 Aug 2005 22:45:55 -0000 @@ -4,7 +4,6 @@ import org.appfuse.dao.UserDAO; import org.appfuse.model.User; -import org.appfuse.model.UserCookie; import org.springframework.orm.ObjectRetrievalFailureException; /** @@ -57,48 +56,6 @@ * @see org.appfuse.dao.UserDAO#removeUser(java.lang.String) */ public void removeUser(String username) { - removeUserCookies(username); - - User user = getUser(username); - getHibernateTemplate().delete(user); - } - - /** - * @see org.appfuse.dao.UserDAO#getUserCookie(org.appfuse.model.UserCookie) - */ - public UserCookie getUserCookie(final UserCookie cookie) { - List cookies = getHibernateTemplate().find( - "from UserCookie c where c.username=? and c.cookieId=?", - new Object[]{cookie.getUsername(), cookie.getCookieId()}); - - if (cookies.size() == 0) { - return null; - } - - return (UserCookie) cookies.get(0); - } - - /** - * @see org.appfuse.dao.UserDAO#removeUserCookies(java.lang.String) - */ - public void removeUserCookies(String username) { - // delete any cookies associated with this user - List cookies = - getHibernateTemplate().find("from UserCookie c where c.username=?", - username); - - if ((cookies.size() > 0) && log.isDebugEnabled()) { - log.debug("deleting " + cookies.size() + " cookies for user '" + - username + "'"); - } - - getHibernateTemplate().deleteAll(cookies); - } - - /** - * @see org.appfuse.dao.UserDAO#saveUserCookie(org.appfuse.model.UserCookie) - */ - public void saveUserCookie(UserCookie cookie) { - getHibernateTemplate().saveOrUpdate(cookie); + getHibernateTemplate().delete(getUser(username)); } } Index: src/dao/org/appfuse/dao/hibernate/applicationContext-hibernate.xml =================================================================== RCS file: /cvs/appfuse/src/dao/org/appfuse/dao/hibernate/applicationContext-hibernate.xml,v retrieving revision 1.9 diff -u -r1.9 applicationContext-hibernate.xml --- src/dao/org/appfuse/dao/hibernate/applicationContext-hibernate.xml 16 Aug 2005 13:32:35 -0000 1.9 +++ src/dao/org/appfuse/dao/hibernate/applicationContext-hibernate.xml 28 Aug 2005 22:56:22 -0000 @@ -10,7 +10,6 @@ org/appfuse/model/Role.hbm.xml org/appfuse/model/User.hbm.xml - org/appfuse/model/UserCookie.hbm.xml
- - - PROPAGATION_REQUIRED,-UserExistsException - PROPAGATION_REQUIRED - PROPAGATION_REQUIRED - PROPAGATION_REQUIRED,readOnly - - Index: src/service/org/appfuse/service/impl/UserManagerImpl.java =================================================================== RCS file: /cvs/appfuse/src/service/org/appfuse/service/impl/UserManagerImpl.java,v retrieving revision 1.5 diff -u -r1.5 UserManagerImpl.java --- src/service/org/appfuse/service/impl/UserManagerImpl.java 25 Oct 2004 23:22:33 -0000 1.5 +++ src/service/org/appfuse/service/impl/UserManagerImpl.java 28 Aug 2005 22:49:13 -0000 @@ -2,14 +2,10 @@ import java.util.List; -import org.apache.commons.lang.StringUtils; import org.appfuse.dao.UserDAO; import org.appfuse.model.User; -import org.appfuse.model.UserCookie; import org.appfuse.service.UserExistsException; import org.appfuse.service.UserManager; -import org.appfuse.util.RandomGUID; -import org.appfuse.util.StringUtil; import org.springframework.dao.DataIntegrityViolationException; @@ -54,8 +50,7 @@ try { dao.saveUser(user); } catch (DataIntegrityViolationException e) { - throw new UserExistsException("User '" + user.getUsername() + - "' already exists!"); + throw new UserExistsException("User '" + user.getUsername() + "' already exists!"); } } @@ -68,72 +63,5 @@ } dao.removeUser(username); - } - - /** - * @see org.appfuse.service.UserManager#checkLoginCookie(java.lang.String) - */ - public String checkLoginCookie(String value) { - value = StringUtil.decodeString(value); - - String[] values = StringUtils.split(value, "|"); - - // in case of empty username in cookie, return null - if (values.length == 1) { - return null; - } - - if (log.isDebugEnabled()) { - log.debug("looking up cookieId: " + values[1]); - } - - UserCookie cookie = new UserCookie(); - cookie.setUsername(values[0]); - cookie.setCookieId(values[1]); - cookie = dao.getUserCookie(cookie); - - if (cookie != null) { - if (log.isDebugEnabled()) { - log.debug("cookieId lookup succeeded, generating new cookieId"); - } - - return saveLoginCookie(cookie); - } else { - if (log.isDebugEnabled()) { - log.debug("cookieId lookup failed, returning null"); - } - - return null; - } - } - - /** - * @see org.appfuse.service.UserManager#createLoginCookie(java.lang.String) - */ - public String createLoginCookie(String username) { - UserCookie cookie = new UserCookie(); - cookie.setUsername(username); - - return saveLoginCookie(cookie); - } - - /** - * Convenience method to set a unique cookie id and save to database - * @param cookie - * @return - */ - private String saveLoginCookie(UserCookie cookie) { - cookie.setCookieId(new RandomGUID().toString()); - dao.saveUserCookie(cookie); - - return StringUtil.encodeString(cookie.getUsername() + "|" + - cookie.getCookieId()); - } - - /** - * @see org.appfuse.service.UserManager#removeLoginCookies(java.lang.String) - */ - public void removeLoginCookies(String username) { - dao.removeUserCookies(username); } } Index: src/web/org/appfuse/webapp/action/BaseAction.java =================================================================== RCS file: /cvs/appfuse/src/web/org/appfuse/webapp/action/BaseAction.java,v retrieving revision 1.24 diff -u -r1.24 BaseAction.java --- src/web/org/appfuse/webapp/action/BaseAction.java 8 Jun 2005 14:26:45 -0000 1.24 +++ src/web/org/appfuse/webapp/action/BaseAction.java 28 Aug 2005 22:54:24 -0000 @@ -30,7 +30,6 @@ import org.appfuse.util.CurrencyConverter; import org.appfuse.util.DateConverter; import org.appfuse.util.TimestampConverter; -import org.appfuse.webapp.util.SslUtil; import org.springframework.context.ApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; @@ -81,9 +80,7 @@ */ public class BaseAction extends DispatchAction { protected final Log log = LogFactory.getLog(getClass()); - public static final String SECURE = "secure"; - private static ApplicationContext ctx = null; - private static Long defaultLong = null; + private static final Long defaultLong = null; static { ConvertUtils.register(new CurrencyConverter(), Double.class); @@ -101,10 +98,8 @@ * @return */ public Object getBean(String name) { - if (ctx == null) { - ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(servlet.getServletContext()); - } - + ApplicationContext ctx = + WebApplicationContextUtils.getRequiredWebApplicationContext(servlet.getServletContext()); return ctx.getBean(name); } @@ -149,8 +144,7 @@ /** * Gets the method name based on the mapping passed to it */ - private String getActionMethodWithMapping(HttpServletRequest request, - ActionMapping mapping) { + private String getActionMethodWithMapping(HttpServletRequest request, ActionMapping mapping) { return getActionMethod(request, mapping.getParameter()); } @@ -241,8 +235,7 @@ * @return ActionForm the form from the specifies scope, or null if nothing * found */ - protected ActionForm getActionForm(ActionMapping mapping, - HttpServletRequest request) { + protected ActionForm getActionForm(ActionMapping mapping, HttpServletRequest request) { ActionForm actionForm = null; // Remove the obsolete form bean @@ -286,44 +279,12 @@ } /** - * Method to check and see if https is required for this resource - * - * @param mapping The ActionMapping used to select this instance - * @param request The HTTP request we are processing - * @param response The HTTP response we are creating - * @return boolean true if redirection to SSL is needed - */ - protected boolean checkSsl(ActionMapping mapping, - HttpServletRequest request, - HttpServletResponse response) { - String redirectString = - SslUtil.getRedirectString(request, getServlet().getServletContext(), - SECURE.equals(mapping.getParameter())); - - if (redirectString != null) { - log.debug("protocol switch needed, redirecting..."); - - try { - // Redirect the page to the desired URL - response.sendRedirect(response.encodeRedirectURL(redirectString)); - - return true; - } catch (Exception ioe) { - log.error("redirect to new protocol failed..."); - } - } - - return false; - } - - /** * Convenience method for removing the obsolete form bean. * * @param mapping The ActionMapping used to select this instance * @param request The HTTP request we are processing */ - protected void removeFormBean(ActionMapping mapping, - HttpServletRequest request) { + protected void removeFormBean(ActionMapping mapping, HttpServletRequest request) { // Remove the obsolete form bean if (mapping.getAttribute() != null) { if ("request".equals(mapping.getScope())) { @@ -342,8 +303,7 @@ * @param request The HTTP request we are processing * @param form The ActionForm */ - protected void updateFormBean(ActionMapping mapping, - HttpServletRequest request, ActionForm form) { + protected void updateFormBean(ActionMapping mapping, HttpServletRequest request, ActionForm form) { // Remove the obsolete form bean if (mapping.getAttribute() != null) { if ("request".equals(mapping.getScope())) { Index: src/web/org/appfuse/webapp/action/SignupAction.java =================================================================== RCS file: /cvs/appfuse/src/web/org/appfuse/webapp/action/SignupAction.java,v retrieving revision 1.14 diff -u -r1.14 SignupAction.java --- src/web/org/appfuse/webapp/action/SignupAction.java 7 Jan 2005 05:17:01 -0000 1.14 +++ src/web/org/appfuse/webapp/action/SignupAction.java 28 Aug 2005 22:50:58 -0000 @@ -65,29 +65,27 @@ ActionMessages errors = new ActionMessages(); UserForm userForm = (UserForm) form; User user = (User) convert(form); - String algorithm = - (String) getConfiguration().get(Constants.ENC_ALGORITHM); // Set the default user role on this new user RoleManager roleMgr = (RoleManager) getBean("roleManager"); user.addRole(roleMgr.getRole(Constants.USER_ROLE)); try { - if (algorithm == null) { // should only happen for test case - log.debug("assuming testcase, setting algorigthm to 'SHA'"); - algorithm = "SHA"; - } + Boolean encrypt = (Boolean) getConfiguration().get(Constants.ENCRYPT_PASSWORD); + + if (encrypt != null && encrypt.booleanValue()) { + String algorithm = (String) getConfiguration().get(Constants.ENC_ALGORITHM); + if (algorithm == null) { // should only happen for test case + log.debug("assuming testcase, setting algorigthm to 'SHA'"); + algorithm = "SHA"; + } - user.setPassword(StringUtil.encodePassword(user.getPassword(), - algorithm)); + user.setPassword(StringUtil.encodePassword(user.getPassword(), algorithm)); + } + user.setEnabled(Boolean.TRUE); UserManager mgr = (UserManager) getBean("userManager"); mgr.saveUser(user); - - // Set cookies for auto-magical login ;-) - String loginCookie = mgr.createLoginCookie(user.getUsername()); - RequestUtil.setCookie(response, Constants.LOGIN_COOKIE, - loginCookie, request.getContextPath()); } catch (UserExistsException e) { log.warn(e.getMessage()); errors.add(ActionMessages.GLOBAL_MESSAGE, Index: src/web/org/appfuse/webapp/action/UserAction.java =================================================================== RCS file: /cvs/appfuse/src/web/org/appfuse/webapp/action/UserAction.java,v retrieving revision 1.32 diff -u -r1.32 UserAction.java --- src/web/org/appfuse/webapp/action/UserAction.java 15 Jun 2005 00:11:26 -0000 1.32 +++ src/web/org/appfuse/webapp/action/UserAction.java 28 Aug 2005 22:28:57 -0000 @@ -1,349 +1,345 @@ -package org.appfuse.webapp.action; - -import java.util.List; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - -import org.apache.commons.beanutils.BeanUtils; -import org.apache.commons.lang.StringUtils; - -import org.apache.struts.action.ActionForm; -import org.apache.struts.action.ActionForward; -import org.apache.struts.action.ActionMapping; -import org.apache.struts.action.ActionMessage; -import org.apache.struts.action.ActionMessages; -import org.apache.struts.util.MessageResources; - -import org.appfuse.Constants; -import org.appfuse.model.Role; -import org.appfuse.model.User; -import org.appfuse.service.MailEngine; -import org.appfuse.service.RoleManager; -import org.appfuse.service.UserExistsException; -import org.appfuse.service.UserManager; -import org.appfuse.util.StringUtil; -import org.appfuse.webapp.form.UserForm; -import org.appfuse.webapp.util.RequestUtil; - -import org.springframework.mail.SimpleMailMessage; - -/** - * Implementation of Action that interacts with the {@link - * UserForm} and retrieves values. It interacts with the {@link - * UserManager} to retrieve/persist values to the database. - * - *

- * View Source - *

- * - * @author Matt Raible - * Modified by Dan Kibler - * - * @struts.action name="userForm" path="/users" scope="request" - * validate="false" parameter="method" input="mainMenu" roles="admin" - * @struts.action name="userForm" path="/editUser" scope="request" - * validate="false" parameter="method" input="list" roles="admin" - * @struts.action name="userForm" path="/editProfile" scope="request" - * validate="false" parameter="method" input="mainMenu" - * @struts.action name="userForm" path="/saveUser" scope="request" - * validate="false" parameter="method" input="edit" - * - * @struts.action-forward name="list" path="/WEB-INF/pages/userList.jsp" - * @struts.action-forward name="edit" path="/WEB-INF/pages/userProfile.jsp" - */ -public final class UserAction extends BaseAction { - - public ActionForward add(ActionMapping mapping, ActionForm form, - HttpServletRequest request, - HttpServletResponse response) - throws Exception { - if (log.isDebugEnabled()) { - log.debug("Entering 'add' method"); - } - - User user = new User(); - user.addRole(new Role(Constants.USER_ROLE)); - UserForm userForm = (UserForm) convert(user); - updateFormBean(mapping, request, userForm); - - checkForCookieLogin(request); - - return mapping.findForward("edit"); - } - - public ActionForward cancel(ActionMapping mapping, ActionForm form, - HttpServletRequest request, - HttpServletResponse response) - throws Exception { - if (log.isDebugEnabled()) { - log.debug("Entering 'cancel' method"); - } - - if (!StringUtils.equals(request.getParameter("from"), "list")) { - return mapping.findForward("mainMenu"); - } else { - return mapping.findForward("viewUsers"); - } - } - - public ActionForward delete(ActionMapping mapping, ActionForm form, - HttpServletRequest request, - HttpServletResponse response) - throws Exception { - if (log.isDebugEnabled()) { - log.debug("Entering 'delete' method"); - } - - // Extract attributes and parameters we will need - ActionMessages messages = new ActionMessages(); - UserForm userForm = (UserForm) form; - - // Exceptions are caught by ActionExceptionHandler - UserManager mgr = (UserManager) getBean("userManager"); - mgr.removeUser(userForm.getUsername()); - - messages.add(ActionMessages.GLOBAL_MESSAGE, - new ActionMessage("user.deleted", userForm.getFirstName() - + ' ' + userForm.getLastName())); - - saveMessages(request.getSession(), messages); - - // return a forward to searching users - return mapping.findForward("viewUsers"); - } - - public ActionForward edit(ActionMapping mapping, ActionForm form, - HttpServletRequest request, - HttpServletResponse response) - throws Exception { - if (log.isDebugEnabled()) { - log.debug("Entering 'edit' method"); - } - - UserForm userForm = (UserForm) form; - HttpSession session = request.getSession(); - - // if URL is "editProfile" - make sure it's the current user - if (request.getRequestURI().indexOf("editProfile") > -1) { - // reject if username passed in or "list" parameter passed in - // someone that is trying this probably knows the AppFuse code - // but it's a legitimate bug, so I'll fix it. ;-) - if ((request.getParameter("username") != null) || - (request.getParameter("from") != null)) { - response.sendError(HttpServletResponse.SC_FORBIDDEN); - log.warn("User '" + request.getRemoteUser() + - "' is trying to edit user '" + - request.getParameter("username") + "'"); - - return null; - } - } - - // Exceptions are caught by ActionExceptionHandler - UserManager mgr = (UserManager) getBean("userManager"); - User user = null; - - // if a user's username is passed in - if (request.getParameter("username") != null) { - // lookup the user using that id - user = mgr.getUser(userForm.getUsername()); - } else { - // look it up based on the current user's id - user = mgr.getUser(getUser(session).getUsername()); - } - - BeanUtils.copyProperties(userForm, convert(user)); - userForm.setConfirmPassword(userForm.getPassword()); - updateFormBean(mapping, request, userForm); - - checkForCookieLogin(request); - - // return a forward to edit forward - return mapping.findForward("edit"); - } - - public ActionForward save(ActionMapping mapping, ActionForm form, - HttpServletRequest request, - HttpServletResponse response) - throws Exception { - if (log.isDebugEnabled()) { - log.debug("Entering 'save' method"); - } - - // run validation rules on this form - // See https://appfuse.dev.java.net/issues/show_bug.cgi?id=128 - ActionMessages errors = form.validate(mapping, request); - - if (!errors.isEmpty()) { - saveErrors(request, errors); - return mapping.findForward("edit"); - } - - // Extract attributes and parameters we will need - ActionMessages messages = new ActionMessages(); - HttpSession session = request.getSession(); - UserForm userForm = (UserForm) form; - String password = userForm.getPassword(); - User user = new User(); - - // Exceptions are caught by ActionExceptionHandler - // all we need to persist is the parent object - BeanUtils.copyProperties(user, userForm); - - if (StringUtils.equals(request.getParameter("encryptPass"), "true")) { - String algorithm = - (String) getConfiguration().get(Constants.ENC_ALGORITHM); - - if (algorithm == null) { // should only happen for test case - log.debug("assuming testcase, setting algorigthm to 'SHA'"); - algorithm = "SHA"; - } - - user.setPassword(StringUtil.encodePassword(password, algorithm)); - } - - UserManager mgr = (UserManager) getBean("userManager"); - RoleManager roleMgr = (RoleManager) getBean("roleManager"); - String[] userRoles = request.getParameterValues("userRoles"); - - for (int i = 0; userRoles != null && i < userRoles.length; i++) { - String roleName = userRoles[i]; - user.addRole(roleMgr.getRole(roleName)); - } - - try { - mgr.saveUser(user); - } catch (UserExistsException e) { - log.warn(e.getMessage()); - errors.add(ActionMessages.GLOBAL_MESSAGE, - new ActionMessage("errors.existing.user", - userForm.getUsername(), - userForm.getEmail())); - saveErrors(request, errors); - - return mapping.findForward("edit"); - } - - BeanUtils.copyProperties(userForm, convert(user)); - userForm.setConfirmPassword(userForm.getPassword()); - updateFormBean(mapping, request, userForm); - - if (!StringUtils.equals(request.getParameter("from"), "list")) { - session.setAttribute(Constants.USER_KEY, user); - - // update the user's remember me cookie if they didn't login - // with a cookie - if ((RequestUtil.getCookie(request, Constants.LOGIN_COOKIE) != null) && - (session.getAttribute("cookieLogin") == null)) { - // delete all user cookies and add a new one - mgr.removeLoginCookies(userForm.getUsername()); - - String autoLogin = - mgr.createLoginCookie(userForm.getUsername()); - RequestUtil.setCookie(response, Constants.LOGIN_COOKIE, - autoLogin, request.getContextPath()); - } - - // add success messages - messages.add(ActionMessages.GLOBAL_MESSAGE, - new ActionMessage("user.saved")); - saveMessages(request.getSession(), messages); - - // return a forward to main Menu - return mapping.findForward("mainMenu"); - } else { - // add success messages - if ("".equals(request.getParameter("version"))) { - messages.add(ActionMessages.GLOBAL_MESSAGE, - new ActionMessage("user.added", user.getFullName())); - saveMessages(request.getSession(), messages); - sendNewUserEmail(request, userForm); - - return mapping.findForward("addUser"); - } else { - messages.add(ActionMessages.GLOBAL_MESSAGE, - new ActionMessage("user.updated.byAdmin", - user.getFullName())); - saveMessages(request, messages); - - return mapping.findForward("edit"); - } - } - } - - public ActionForward search(ActionMapping mapping, ActionForm form, - HttpServletRequest request, - HttpServletResponse response) - throws Exception { - if (log.isDebugEnabled()) { - log.debug("Entering 'search' method"); - } - - UserForm userForm = (UserForm) form; - - // Exceptions are caught by ActionExceptionHandler - UserManager mgr = (UserManager) getBean("userManager"); - User user = (User) convert(userForm); - List users = mgr.getUsers(user); - request.setAttribute(Constants.USER_LIST, users); - - // return a forward to the user list definition - return mapping.findForward("list"); - } - - public ActionForward unspecified(ActionMapping mapping, ActionForm form, - HttpServletRequest request, - HttpServletResponse response) - throws Exception { - - return search(mapping, form, request, response); - } - - private void sendNewUserEmail(HttpServletRequest request, UserForm userForm) - throws Exception { - MessageResources resources = getResources(request); - - // Send user an e-mail - if (log.isDebugEnabled()) { - log.debug("Sending user '" + userForm.getUsername() + - "' an account information e-mail"); - } - - SimpleMailMessage message = (SimpleMailMessage) getBean("mailMessage"); - message.setTo(userForm.getFullName() + "<" + userForm.getEmail() + ">"); - - StringBuffer msg = new StringBuffer(); - msg.append(resources.getMessage("newuser.email.message", - userForm.getFullName())); - msg.append("\n\n" + resources.getMessage("userForm.username")); - msg.append(": " + userForm.getUsername() + "\n"); - msg.append(resources.getMessage("userForm.password") + ": "); - msg.append(userForm.getPassword()); - msg.append("\n\nLogin at: " + RequestUtil.getAppURL(request)); - message.setText(msg.toString()); - - message.setSubject(resources.getMessage("signup.email.subject")); - - MailEngine engine = (MailEngine) getBean("mailEngine"); - engine.send(message); - } - - private void checkForCookieLogin(HttpServletRequest request) { - // if user logged in with a cookie, display a warning that they - // can't change passwords - if (log.isDebugEnabled()) { - log.debug("checking for cookieLogin..."); - } - - if (request.getSession().getAttribute("cookieLogin") != null) { - ActionMessages messages = new ActionMessages(); - - // add warning messages - messages.add(ActionMessages.GLOBAL_MESSAGE, - new ActionMessage("userProfile.cookieLogin")); - saveMessages(request, messages); - } - } -} +package org.appfuse.webapp.action; + +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import net.sf.acegisecurity.Authentication; +import net.sf.acegisecurity.AuthenticationTrustResolver; +import net.sf.acegisecurity.AuthenticationTrustResolverImpl; +import net.sf.acegisecurity.context.ContextHolder; +import net.sf.acegisecurity.context.security.SecureContext; + +import org.apache.commons.beanutils.BeanUtils; +import org.apache.commons.lang.StringUtils; +import org.apache.struts.action.ActionForm; +import org.apache.struts.action.ActionForward; +import org.apache.struts.action.ActionMapping; +import org.apache.struts.action.ActionMessage; +import org.apache.struts.action.ActionMessages; +import org.apache.struts.util.MessageResources; +import org.appfuse.Constants; +import org.appfuse.model.Role; +import org.appfuse.model.User; +import org.appfuse.service.MailEngine; +import org.appfuse.service.RoleManager; +import org.appfuse.service.UserExistsException; +import org.appfuse.service.UserManager; +import org.appfuse.util.StringUtil; +import org.appfuse.webapp.form.UserForm; +import org.appfuse.webapp.util.RequestUtil; +import org.springframework.mail.SimpleMailMessage; + +/** + * Implementation of Action that interacts with the {@link + * UserForm} and retrieves values. It interacts with the {@link + * UserManager} to retrieve/persist values to the database. + * + *

+ * View Source + *

+ * + * @author Matt Raible + * Modified by Dan Kibler + * + * @struts.action name="userForm" path="/users" scope="request" + * validate="false" parameter="method" input="mainMenu" roles="admin" + * @struts.action name="userForm" path="/editUser" scope="request" + * validate="false" parameter="method" input="list" roles="admin" + * @struts.action name="userForm" path="/editProfile" scope="request" + * validate="false" parameter="method" input="mainMenu" + * @struts.action name="userForm" path="/saveUser" scope="request" + * validate="false" parameter="method" input="edit" + * + * @struts.action-forward name="list" path="/WEB-INF/pages/userList.jsp" + * @struts.action-forward name="edit" path="/WEB-INF/pages/userProfile.jsp" + */ +public final class UserAction extends BaseAction { + + public ActionForward add(ActionMapping mapping, ActionForm form, + HttpServletRequest request, + HttpServletResponse response) + throws Exception { + if (log.isDebugEnabled()) { + log.debug("Entering 'add' method"); + } + + User user = new User(); + user.addRole(new Role(Constants.USER_ROLE)); + UserForm userForm = (UserForm) convert(user); + updateFormBean(mapping, request, userForm); + + checkForRememberMeLogin(request); + + return mapping.findForward("edit"); + } + + public ActionForward cancel(ActionMapping mapping, ActionForm form, + HttpServletRequest request, + HttpServletResponse response) + throws Exception { + if (log.isDebugEnabled()) { + log.debug("Entering 'cancel' method"); + } + + if (!StringUtils.equals(request.getParameter("from"), "list")) { + return mapping.findForward("mainMenu"); + } else { + return mapping.findForward("viewUsers"); + } + } + + public ActionForward delete(ActionMapping mapping, ActionForm form, + HttpServletRequest request, + HttpServletResponse response) + throws Exception { + if (log.isDebugEnabled()) { + log.debug("Entering 'delete' method"); + } + + // Extract attributes and parameters we will need + ActionMessages messages = new ActionMessages(); + UserForm userForm = (UserForm) form; + + // Exceptions are caught by ActionExceptionHandler + UserManager mgr = (UserManager) getBean("userManager"); + mgr.removeUser(userForm.getUsername()); + + messages.add(ActionMessages.GLOBAL_MESSAGE, + new ActionMessage("user.deleted", userForm.getFirstName() + + ' ' + userForm.getLastName())); + + saveMessages(request.getSession(), messages); + + // return a forward to searching users + return mapping.findForward("viewUsers"); + } + + public ActionForward edit(ActionMapping mapping, ActionForm form, + HttpServletRequest request, + HttpServletResponse response) + throws Exception { + if (log.isDebugEnabled()) { + log.debug("Entering 'edit' method"); + } + + UserForm userForm = (UserForm) form; + HttpSession session = request.getSession(); + + // if URL is "editProfile" - make sure it's the current user + if (request.getRequestURI().indexOf("editProfile") > -1) { + // reject if username passed in or "list" parameter passed in + // someone that is trying this probably knows the AppFuse code + // but it's a legitimate bug, so I'll fix it. ;-) + if ((request.getParameter("username") != null) || + (request.getParameter("from") != null)) { + response.sendError(HttpServletResponse.SC_FORBIDDEN); + log.warn("User '" + request.getRemoteUser() + + "' is trying to edit user '" + + request.getParameter("username") + "'"); + + return null; + } + } + + // Exceptions are caught by ActionExceptionHandler + UserManager mgr = (UserManager) getBean("userManager"); + User user = null; + + // if a user's username is passed in + if (request.getParameter("username") != null) { + // lookup the user using that id + user = mgr.getUser(userForm.getUsername()); + } else { + // look it up based on the current user's id + user = mgr.getUser(getUser(session).getUsername()); + } + + BeanUtils.copyProperties(userForm, convert(user)); + userForm.setConfirmPassword(userForm.getPassword()); + updateFormBean(mapping, request, userForm); + + checkForRememberMeLogin(request); + + // return a forward to edit forward + return mapping.findForward("edit"); + } + + public ActionForward save(ActionMapping mapping, ActionForm form, + HttpServletRequest request, + HttpServletResponse response) + throws Exception { + if (log.isDebugEnabled()) { + log.debug("Entering 'save' method"); + } + + // run validation rules on this form + // See https://appfuse.dev.java.net/issues/show_bug.cgi?id=128 + ActionMessages errors = form.validate(mapping, request); + + if (!errors.isEmpty()) { + saveErrors(request, errors); + return mapping.findForward("edit"); + } + + // Extract attributes and parameters we will need + ActionMessages messages = new ActionMessages(); + HttpSession session = request.getSession(); + UserForm userForm = (UserForm) form; + String password = userForm.getPassword(); + User user = new User(); + + // Exceptions are caught by ActionExceptionHandler + // all we need to persist is the parent object + BeanUtils.copyProperties(user, userForm); + + Boolean encrypt = (Boolean) getConfiguration().get(Constants.ENCRYPT_PASSWORD); + + if (StringUtils.equals(request.getParameter("encryptPass"), "true") + && (encrypt != null && encrypt.booleanValue())) { + String algorithm = (String) getConfiguration().get(Constants.ENC_ALGORITHM); + + if (algorithm == null) { // should only happen for test case + log.debug("assuming testcase, setting algorithm to 'SHA'"); + algorithm = "SHA"; + } + + user.setPassword(StringUtil.encodePassword(user.getPassword(), algorithm)); + } + + UserManager mgr = (UserManager) getBean("userManager"); + RoleManager roleMgr = (RoleManager) getBean("roleManager"); + String[] userRoles = request.getParameterValues("userRoles"); + + for (int i = 0; userRoles != null && i < userRoles.length; i++) { + String roleName = userRoles[i]; + user.addRole(roleMgr.getRole(roleName)); + } + + try { + mgr.saveUser(user); + } catch (UserExistsException e) { + log.warn(e.getMessage()); + errors.add(ActionMessages.GLOBAL_MESSAGE, + new ActionMessage("errors.existing.user", + userForm.getUsername(), + userForm.getEmail())); + saveErrors(request, errors); + + return mapping.findForward("edit"); + } + + BeanUtils.copyProperties(userForm, convert(user)); + userForm.setConfirmPassword(userForm.getPassword()); + updateFormBean(mapping, request, userForm); + + if (!StringUtils.equals(request.getParameter("from"), "list")) { + session.setAttribute(Constants.USER_KEY, user); + + // add success messages + messages.add(ActionMessages.GLOBAL_MESSAGE, + new ActionMessage("user.saved")); + saveMessages(request.getSession(), messages); + + // return a forward to main Menu + return mapping.findForward("mainMenu"); + } else { + // add success messages + if ("".equals(request.getParameter("version"))) { + messages.add(ActionMessages.GLOBAL_MESSAGE, + new ActionMessage("user.added", user.getFullName())); + saveMessages(request.getSession(), messages); + sendNewUserEmail(request, userForm); + + return mapping.findForward("addUser"); + } else { + messages.add(ActionMessages.GLOBAL_MESSAGE, + new ActionMessage("user.updated.byAdmin", + user.getFullName())); + saveMessages(request, messages); + + return mapping.findForward("edit"); + } + } + } + + public ActionForward search(ActionMapping mapping, ActionForm form, + HttpServletRequest request, + HttpServletResponse response) + throws Exception { + if (log.isDebugEnabled()) { + log.debug("Entering 'search' method"); + } + + UserForm userForm = (UserForm) form; + + // Exceptions are caught by ActionExceptionHandler + UserManager mgr = (UserManager) getBean("userManager"); + User user = (User) convert(userForm); + List users = mgr.getUsers(user); + request.setAttribute(Constants.USER_LIST, users); + + // return a forward to the user list definition + return mapping.findForward("list"); + } + + public ActionForward unspecified(ActionMapping mapping, ActionForm form, + HttpServletRequest request, + HttpServletResponse response) + throws Exception { + + return search(mapping, form, request, response); + } + + private void sendNewUserEmail(HttpServletRequest request, UserForm userForm) + throws Exception { + MessageResources resources = getResources(request); + + // Send user an e-mail + if (log.isDebugEnabled()) { + log.debug("Sending user '" + userForm.getUsername() + + "' an account information e-mail"); + } + + SimpleMailMessage message = (SimpleMailMessage) getBean("mailMessage"); + message.setTo(userForm.getFullName() + "<" + userForm.getEmail() + ">"); + + StringBuffer msg = new StringBuffer(); + msg.append(resources.getMessage("newuser.email.message", + userForm.getFullName())); + msg.append("\n\n" + resources.getMessage("userForm.username")); + msg.append(": " + userForm.getUsername() + "\n"); + msg.append(resources.getMessage("userForm.password") + ": "); + msg.append(userForm.getPassword()); + msg.append("\n\nLogin at: " + RequestUtil.getAppURL(request)); + message.setText(msg.toString()); + + message.setSubject(resources.getMessage("signup.email.subject")); + + MailEngine engine = (MailEngine) getBean("mailEngine"); + engine.send(message); + } + + private void checkForRememberMeLogin(HttpServletRequest request) { + // if user logged in with remember me, display a warning that they can't change passwords + log.debug("checking for remember me login..."); + + AuthenticationTrustResolver resolver = new AuthenticationTrustResolverImpl(); + SecureContext ctx = (SecureContext) ContextHolder.getContext(); + + if (ctx != null) { + Authentication auth = ctx.getAuthentication(); + + if (resolver.isRememberMe(auth)) { + request.getSession().setAttribute("cookieLogin", "true"); + + // add warning message + ActionMessages messages = new ActionMessages(); + messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("userProfile.cookieLogin")); + saveMessages(request, messages); + } + } + } +} Index: src/web/org/appfuse/webapp/filter/ActionFilter.java =================================================================== RCS file: /cvs/appfuse/src/web/org/appfuse/webapp/filter/ActionFilter.java,v retrieving revision 1.13 diff -u -r1.13 ActionFilter.java --- src/web/org/appfuse/webapp/filter/ActionFilter.java 16 Apr 2005 22:17:21 -0000 1.13 +++ src/web/org/appfuse/webapp/filter/ActionFilter.java 28 Aug 2005 22:45:22 -0000 @@ -18,8 +18,6 @@ import org.appfuse.Constants; import org.appfuse.model.User; import org.appfuse.service.UserManager; -import org.appfuse.webapp.util.RequestUtil; -import org.appfuse.webapp.util.SslUtil; import org.springframework.context.ApplicationContext; import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.web.context.support.WebApplicationContextUtils; @@ -36,23 +34,13 @@ * @version $Revision: 1.13 $ $Date: 2005/04/16 22:17:21 $ * * @web.filter display-name="Action Filter" name="actionFilter" - * - *

Change this value to true if you want to secure your entire application. - * This can also be done in web-security.xml by setting - * to CONFIDENTIAL.

- * - * @web.filter-init-param name="isSecure" value="${secure.application}" */ public class ActionFilter implements Filter { - private static Boolean secure = Boolean.FALSE; - private final transient Log log = LogFactory.getLog(ActionFilter.class); + private final Log log = LogFactory.getLog(ActionFilter.class); private FilterConfig config = null; public void init(FilterConfig config) throws ServletException { this.config = config; - - /* This determines if the application uconn SSL or not */ - secure = Boolean.valueOf(config.getInitParameter("isSecure")); } /** @@ -68,31 +56,12 @@ // cast to the types I want to use HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) resp; - HttpSession session = request.getSession(true); + HttpSession session = request.getSession(); // notify the LocaleContextHolder what locale is being used so // service and data layer classes can get the locale LocaleContextHolder.setLocale(request.getLocale()); - // do pre filter work here - // If using https, switch to http - String redirectString = - SslUtil.getRedirectString(request, config.getServletContext(), - secure.booleanValue()); - - if (redirectString != null) { - if (log.isDebugEnabled()) { - log.debug("protocol switch needed, redirecting to '" + - redirectString + "'"); - } - - // Redirect the page to the desired URL - response.sendRedirect(response.encodeRedirectURL(redirectString)); - - // ensure we don't chain to requested resource - return; - } - User user = (User) session.getAttribute(Constants.USER_KEY); ServletContext context = config.getServletContext(); String username = request.getRemoteUser(); @@ -105,15 +74,6 @@ UserManager mgr = (UserManager) ctx.getBean("userManager"); user = mgr.getUser(username); session.setAttribute(Constants.USER_KEY, user); - - // if user wants to be remembered, create a remember me cookie - if (session.getAttribute(Constants.LOGIN_COOKIE) != null) { - session.removeAttribute(Constants.LOGIN_COOKIE); - - String loginCookie = mgr.createLoginCookie(username); - RequestUtil.setCookie(response, Constants.LOGIN_COOKIE, - loginCookie, request.getContextPath()); - } } chain.doFilter(request, response); Index: src/web/org/appfuse/webapp/listener/StartupListener.java =================================================================== RCS file: /cvs/appfuse/src/web/org/appfuse/webapp/listener/StartupListener.java,v retrieving revision 1.10 diff -u -r1.10 StartupListener.java --- src/web/org/appfuse/webapp/listener/StartupListener.java 4 Oct 2004 08:10:58 -0000 1.10 +++ src/web/org/appfuse/webapp/listener/StartupListener.java 28 Aug 2005 23:09:41 -0000 @@ -1,16 +1,23 @@ package org.appfuse.webapp.listener; import java.util.HashMap; +import java.util.Iterator; import java.util.Map; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; +import net.sf.acegisecurity.providers.AuthenticationProvider; +import net.sf.acegisecurity.providers.ProviderManager; +import net.sf.acegisecurity.providers.encoding.Md5PasswordEncoder; +import net.sf.acegisecurity.providers.rememberme.RememberMeAuthenticationProvider; + import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.appfuse.Constants; import org.appfuse.service.LookupManager; +import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.context.ApplicationContext; import org.springframework.web.context.ContextLoaderListener; import org.springframework.web.context.support.WebApplicationContextUtils; @@ -42,7 +49,7 @@ // if daoType is not specified, use DAO as default if (daoType == null) { - log.warn("No 'daoType' context carameter, using hibernate"); + log.warn("No 'daoType' context parameter, using Hibernate"); daoType = Constants.DAO_TYPE_HIBERNATE; } @@ -56,12 +63,44 @@ // Create a config object to hold all the app config values config.put(Constants.DAO_TYPE, daoType); + + ApplicationContext ctx = + WebApplicationContextUtils.getRequiredWebApplicationContext(context); + + boolean encryptPassword = false; + try { + ProviderManager provider = (ProviderManager) ctx.getBean("authenticationManager"); + for (Iterator it = provider.getProviders().iterator(); it.hasNext();) { + AuthenticationProvider p = (AuthenticationProvider) it.next(); + if (p instanceof RememberMeAuthenticationProvider) { + config.put("rememberMeEnabled", Boolean.TRUE); + } + } + + if (ctx.containsBean("passwordEncoder")) { + encryptPassword = true; + config.put(Constants.ENCRYPT_PASSWORD, Boolean.TRUE); + String algorithm = "SHA"; + if (ctx.getBean("passwordEncoder") instanceof Md5PasswordEncoder) { + algorithm = "MD5"; + } + config.put(Constants.ENC_ALGORITHM, algorithm); + } + } catch (NoSuchBeanDefinitionException n) { + // ignore, should only happen when testing + } + context.setAttribute(Constants.CONFIG, config); // output the retrieved values for the Init and Context Parameters if (log.isDebugEnabled()) { - log.debug("daoType: " + daoType); - log.debug("populating drop-downs..."); + log.debug("Persistence Framework: " + daoType); + log.debug("Remember Me Enabled? " + config.get("rememberMeEnabled")); + log.debug("Encrypt Passwords? " + encryptPassword); + if (encryptPassword) { + log.debug("Encryption Algorithm: " + config.get(Constants.ENC_ALGORITHM)); + } + log.debug("Populating drop-downs..."); } setupContext(context); @@ -77,7 +116,7 @@ context.setAttribute(Constants.AVAILABLE_ROLES, mgr.getAllRoles()); if (log.isDebugEnabled()) { - log.debug("drop-down initialization complete [OK]"); + log.debug("Drop-down initialization complete [OK]"); } } } Index: src/web/org/appfuse/webapp/util/RequestUtil.java =================================================================== RCS file: /cvs/appfuse/src/web/org/appfuse/webapp/util/RequestUtil.java,v retrieving revision 1.7 diff -u -r1.7 RequestUtil.java --- src/web/org/appfuse/webapp/util/RequestUtil.java 30 Sep 2004 04:41:19 -0000 1.7 +++ src/web/org/appfuse/webapp/util/RequestUtil.java 28 Aug 2005 21:27:43 -0000 @@ -1,13 +1,5 @@ package org.appfuse.webapp.util; -import java.io.UnsupportedEncodingException; -import java.net.URLEncoder; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; - import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -17,133 +9,10 @@ /** - * RequestUtil utility class Good ol' copy-n-paste from - * http://www.javaworld.com/javaworld/jw-02-2002/ssl/utilityclass.txt - * which is referenced in the following article: - * http://www.javaworld.com/javaworld/jw-02-2002/jw-0215-ssl.html + * Convenience class for setting and retrieving cookies. */ public class RequestUtil { - private static final String STOWED_REQUEST_ATTRIBS = "ssl.redirect.attrib.stowed"; private transient static Log log = LogFactory.getLog(RequestUtil.class); - - /** - * Creates query String from request body parameters - */ - public static String getRequestParameters(HttpServletRequest aRequest) { - // set the ALGORIGTHM as defined for the application - //ALGORITHM = (String) aRequest.getAttribute(Constants.ENC_ALGORITHM); - Map m = aRequest.getParameterMap(); - - return createQueryStringFromMap(m, "&").toString(); - } - - /** - * Builds a query string from a given map of parameters - * - * @param m A map of parameters - * @param ampersand String to use for ampersands (e.g. "&" or "&" ) - * - * @return query string (with no leading "?") - */ - public static StringBuffer createQueryStringFromMap(Map m, String ampersand) { - StringBuffer aReturn = new StringBuffer(""); - Set aEntryS = m.entrySet(); - Iterator aEntryI = aEntryS.iterator(); - - while (aEntryI.hasNext()) { - Map.Entry aEntry = (Map.Entry) aEntryI.next(); - Object o = aEntry.getValue(); - - if (o == null) { - append(aEntry.getKey(), "", aReturn, ampersand); - } else if (o instanceof String) { - append(aEntry.getKey(), o, aReturn, ampersand); - } else if (o instanceof String[]) { - String[] aValues = (String[]) o; - - for (int i = 0; i < aValues.length; i++) { - append(aEntry.getKey(), aValues[i], aReturn, ampersand); - } - } else { - append(aEntry.getKey(), o, aReturn, ampersand); - } - } - - return aReturn; - } - - /** - * Appends new key and value pair to query string - * - * @param key parameter name - * @param value value of parameter - * @param queryString existing query string - * @param ampersand string to use for ampersand (e.g. "&" or "&") - * - * @return query string (with no leading "?") - */ - private static StringBuffer append(Object key, Object value, - StringBuffer queryString, - String ampersand) { - if (queryString.length() > 0) { - queryString.append(ampersand); - } - - try { - queryString.append(URLEncoder.encode(key.toString(), "UTF-8")); - queryString.append("="); - queryString.append(URLEncoder.encode(value.toString(), "UTF-8")); - } catch (UnsupportedEncodingException e) { - // won't happen since we're hard-coding UTF-8 - } - return queryString; - } - - /** - * Stores request attributes in session - * - * @param aRequest the current request - */ - public static void stowRequestAttributes(HttpServletRequest aRequest) { - if (aRequest.getSession().getAttribute(STOWED_REQUEST_ATTRIBS) != null) { - return; - } - - Enumeration e = aRequest.getAttributeNames(); - Map map = new HashMap(); - - while (e.hasMoreElements()) { - String name = (String) e.nextElement(); - map.put(name, aRequest.getAttribute(name)); - } - - aRequest.getSession().setAttribute(STOWED_REQUEST_ATTRIBS, map); - } - - /** - * Returns request attributes from session to request - * - * @param aRequest DOCUMENT ME! - */ - public static void reclaimRequestAttributes(HttpServletRequest aRequest) { - Map map = - (Map) aRequest.getSession().getAttribute(STOWED_REQUEST_ATTRIBS); - - if (map == null) { - return; - } - - Iterator itr = map.keySet().iterator(); - - while (itr.hasNext()) { - String name = (String) itr.next(); - aRequest.setAttribute(name, map.get(name)); - } - - aRequest.getSession().removeAttribute(STOWED_REQUEST_ATTRIBS); - } /** * Convenience method to set a cookie Index: test/dao/org/appfuse/dao/UserDAOTest.java =================================================================== RCS file: /cvs/appfuse/test/dao/org/appfuse/dao/UserDAOTest.java,v retrieving revision 1.10 diff -u -r1.10 UserDAOTest.java --- test/dao/org/appfuse/dao/UserDAOTest.java 23 Aug 2005 10:12:46 -0000 1.10 +++ test/dao/org/appfuse/dao/UserDAOTest.java 28 Aug 2005 22:48:16 -0000 @@ -1,134 +1,116 @@ -package org.appfuse.dao; - -import org.appfuse.Constants; -import org.appfuse.model.Address; -import org.appfuse.model.Role; -import org.appfuse.model.User; -import org.appfuse.model.UserCookie; -import org.springframework.dao.DataAccessException; -import org.springframework.dao.DataIntegrityViolationException; - -public class UserDAOTest extends BaseDAOTestCase { - private UserDAO dao = null; - private User user = null; - private RoleDAO rdao = null; - private Role role = null; - - public void setUserDAO(UserDAO dao) { - this.dao = dao; - } - - public void setRoleDAO(RoleDAO rdao) { - this.rdao = rdao; - } - - public void testGetUserInvalid() throws Exception { - try { - user = dao.getUser("badusername"); - fail("'badusername' found in database, failing test..."); - } catch (DataAccessException d) { - assertTrue(d != null); - } - } - - public void testGetUser() throws Exception { - user = dao.getUser("tomcat"); - - assertNotNull(user); - assertEquals(1, user.getRoles().size()); - } - - public void testUpdateUser() throws Exception { - user = dao.getUser("tomcat"); - - Address address = user.getAddress(); - address.setAddress("new address"); - - dao.saveUser(user); - - assertEquals(user.getAddress(), address); - assertEquals("new address", user.getAddress().getAddress()); - - // verify that violation occurs when adding new user - // with same username - user.setVersion(null); - - try { - dao.saveUser(user); - fail("saveUser didn't throw DataIntegrityViolationException"); - } catch (DataIntegrityViolationException e) { - assertNotNull(e); - log.debug("expected exception: " + e.getMessage()); - } - - } - - public void testAddUserRole() throws Exception { - user = dao.getUser("tomcat"); - - assertEquals(1, user.getRoles().size()); - - role = rdao.getRole(Constants.ADMIN_ROLE); - user.addRole(role); - dao.saveUser(user); - - assertEquals(2, user.getRoles().size()); - - //add the same role twice - should result in no additional role - user.addRole(role); - dao.saveUser(user); - - assertEquals("more than 2 roles", 2, user.getRoles().size()); - - user.getRoles().remove(role); - dao.saveUser(user); - - assertEquals(1, user.getRoles().size()); - } - - public void testAddAndRemoveUser() throws Exception { - user = new User("testuser"); - user.setPassword("testpass"); - user.setFirstName("Test"); - user.setLastName("Last"); - Address address = new Address(); - address.setCity("Denver"); - address.setProvince("CO"); - address.setCountry("USA"); - address.setPostalCode("80210"); - user.setAddress(address); - user.setEmail("testuser@appfuse.org"); - user.setWebsite("http://raibledesigns.com"); - user.addRole(rdao.getRole(Constants.USER_ROLE)); - - dao.saveUser(user); - - assertNotNull(user.getUsername()); - assertEquals("testpass", user.getPassword()); - - dao.removeUser("testuser"); - - try { - user = dao.getUser("testuser"); - fail("getUser didn't throw DataAccessException"); - } catch (DataAccessException d) { - assertNotNull(d); - } - } - - public void testSaveAndDeleteUserCookie() throws Exception { - String cookieId = "BA67E786-C031-EA40-2769-863BB30B31EC"; - UserCookie cookie = new UserCookie(); - cookie.setUsername("tomcat"); - cookie.setCookieId(cookieId); - dao.saveUserCookie(cookie); - cookie = dao.getUserCookie(cookie); - assertEquals(cookieId, cookie.getCookieId()); - - dao.removeUserCookies(cookie.getUsername()); - - cookie = dao.getUserCookie(cookie); - - assertNull(cookie); - } +package org.appfuse.dao; + +import org.appfuse.Constants; +import org.appfuse.model.Address; +import org.appfuse.model.Role; +import org.appfuse.model.User; +import org.springframework.dao.DataAccessException; +import org.springframework.dao.DataIntegrityViolationException; + +public class UserDAOTest extends BaseDAOTestCase { + private UserDAO dao = null; + private User user = null; + private RoleDAO rdao = null; + private Role role = null; + + public void setUserDAO(UserDAO dao) { + this.dao = dao; + } + + public void setRoleDAO(RoleDAO rdao) { + this.rdao = rdao; + } + + public void testGetUserInvalid() throws Exception { + try { + user = dao.getUser("badusername"); + fail("'badusername' found in database, failing test..."); + } catch (DataAccessException d) { + assertTrue(d != null); + } + } + + public void testGetUser() throws Exception { + user = dao.getUser("tomcat"); + + assertNotNull(user); + assertEquals(1, user.getRoles().size()); + } + + public void testUpdateUser() throws Exception { + user = dao.getUser("tomcat"); + + Address address = user.getAddress(); + address.setAddress("new address"); + + dao.saveUser(user); + + assertEquals(user.getAddress(), address); + assertEquals("new address", user.getAddress().getAddress()); + + // verify that violation occurs when adding new user + // with same username + user.setVersion(null); + + try { + dao.saveUser(user); + fail("saveUser didn't throw DataIntegrityViolationException"); + } catch (DataIntegrityViolationException e) { + assertNotNull(e); + log.debug("expected exception: " + e.getMessage()); + } + } + + public void testAddUserRole() throws Exception { + user = dao.getUser("tomcat"); + + assertEquals(1, user.getRoles().size()); + + role = rdao.getRole(Constants.ADMIN_ROLE); + user.addRole(role); + dao.saveUser(user); + + assertEquals(2, user.getRoles().size()); + + //add the same role twice - should result in no additional role + user.addRole(role); + dao.saveUser(user); + + assertEquals("more than 2 roles", 2, user.getRoles().size()); + + user.getRoles().remove(role); + dao.saveUser(user); + + assertEquals(1, user.getRoles().size()); + } + + public void testAddAndRemoveUser() throws Exception { + user = new User("testuser"); + user.setPassword("testpass"); + user.setFirstName("Test"); + user.setLastName("Last"); + Address address = new Address(); + address.setCity("Denver"); + address.setProvince("CO"); + address.setCountry("USA"); + address.setPostalCode("80210"); + user.setAddress(address); + user.setEmail("testuser@appfuse.org"); + user.setWebsite("http://raibledesigns.com"); + user.addRole(rdao.getRole(Constants.USER_ROLE)); + + dao.saveUser(user); + + assertNotNull(user.getUsername()); + assertEquals("testpass", user.getPassword()); + + dao.removeUser("testuser"); + + try { + user = dao.getUser("testuser"); + fail("getUser didn't throw DataAccessException"); + } catch (DataAccessException d) { + assertNotNull(d); + } + } } Index: test/service/org/appfuse/service/UserManagerTest.java =================================================================== RCS file: /cvs/appfuse/test/service/org/appfuse/service/UserManagerTest.java,v retrieving revision 1.15 diff -u -r1.15 UserManagerTest.java --- test/service/org/appfuse/service/UserManagerTest.java 28 Aug 2005 21:15:57 -0000 1.15 +++ test/service/org/appfuse/service/UserManagerTest.java 28 Aug 2005 21:40:22 -0000 @@ -1,154 +1,129 @@ -package org.appfuse.service; - -import java.util.ArrayList; -import java.util.List; - -import org.appfuse.Constants; -import org.appfuse.dao.RoleDAO; -import org.appfuse.dao.UserDAO; -import org.appfuse.model.Role; -import org.appfuse.model.User; -import org.appfuse.model.UserCookie; -import org.appfuse.service.impl.RoleManagerImpl; -import org.appfuse.service.impl.UserManagerImpl; -import org.jmock.Mock; -import org.springframework.dao.DataIntegrityViolationException; - - -public class UserManagerTest extends BaseManagerTestCase { - //~ Instance fields ======================================================== - - private UserManager userManager = new UserManagerImpl(); - private RoleManager roleManager = new RoleManagerImpl(); - private Mock userDAO = null; - private Mock roleDAO = null; - private User user = null; - private Role role = null; - - //~ Methods ================================================================ - - protected void setUp() throws Exception { - super.setUp(); - userDAO = new Mock(UserDAO.class); - userManager.setUserDAO((UserDAO) userDAO.proxy()); - roleDAO = new Mock(RoleDAO.class); - roleManager.setRoleDAO((RoleDAO) roleDAO.proxy()); - } - - public void testGetUser() throws Exception { - User testData = new User("tomcat"); - testData.getRoles().add(new Role("user")); - // set expected behavior on dao - userDAO.expects(once()).method("getUser") - .with(eq("tomcat")).will(returnValue(testData)); - - user = userManager.getUser("tomcat"); - assertTrue(user != null); - assertTrue(user.getRoles().size() == 1); - userDAO.verify(); - } - - public void testSaveUser() throws Exception { - User testData = new User("tomcat"); - testData.getRoles().add(new Role("user")); - // set expected behavior on dao - userDAO.expects(once()).method("getUser") - .with(eq("tomcat")).will(returnValue(testData)); - - user = userManager.getUser("tomcat"); - user.setPhoneNumber("303-555-1212"); - userDAO.verify(); - - // reset expectations - userDAO.reset(); - userDAO.expects(once()).method("saveUser").with(same(user)); - - userManager.saveUser(user); - assertTrue(user.getPhoneNumber().equals("303-555-1212")); - assertTrue(user.getRoles().size() == 1); - userDAO.verify(); - } - - public void testAddAndRemoveUser() throws Exception { - user = new User(); - - // call populate method in super class to populate test data - // from a properties file matching this class name - user = (User) populate(user); - - // set expected behavior on role dao - roleDAO.expects(once()).method("getRole") - .with(eq("user")).will(returnValue(new Role("user"))); - - role = roleManager.getRole(Constants.USER_ROLE); - roleDAO.verify(); - user.addRole(role); - - // set expected behavior on user dao - userDAO.expects(once()).method("saveUser").with(same(user)); - - userManager.saveUser(user); - assertTrue(user.getUsername().equals("john")); - assertTrue(user.getRoles().size() == 1); - userDAO.verify(); - - // reset expectations - userDAO.reset(); - - userDAO.expects(once()).method("removeUser").with(eq(user.getUsername())); - userManager.removeUser(user.getUsername()); - userDAO.verify(); - - // reset expectations - userDAO.reset(); - userDAO.expects(once()).method("getUser").will(returnValue(null)); - user = userManager.getUser("john"); - assertNull(user); - userDAO.verify(); - } - - public void testLoginWithCookie() { - // set expectations - userDAO.expects(once()).method("saveUserCookie"); - - String cookieString = userManager.createLoginCookie("tomcat"); - - assertNotNull(cookieString); - userDAO.verify(); - - // reset expectations - userDAO.expects(once()).method("getUserCookie").will(returnValue(new UserCookie())); - // lookup succeeds, save will be called to generate a new one - userDAO.expects(once()).method("saveUserCookie"); - String newCookie = userManager.checkLoginCookie(cookieString); - assertNotNull(newCookie); - userDAO.verify(); - - // reset expectations - userDAO.expects(once()).method("getUserCookie").will(returnValue(null)); - newCookie = userManager.checkLoginCookie(cookieString); - assertNull(newCookie); - userDAO.verify(); - } - - public void testUserExistsException() { - // set expectations - user = new User("admin"); - user.setEmail("matt@raibledesigns.com"); - List users = new ArrayList(); - - users.add(user); - Exception ex = new DataIntegrityViolationException(""); - userDAO.expects(once()).method("saveUser").with(same(user)) - .will(throwException(ex)); - - // run test - try { - userManager.saveUser(user); - fail("Expected UserExistsException not thrown"); - } catch (UserExistsException e) { - log.debug("expected exception: " + e.getMessage()); - assertNotNull(e); - } - } -} +package org.appfuse.service; + +import java.util.ArrayList; +import java.util.List; + +import org.appfuse.Constants; +import org.appfuse.dao.RoleDAO; +import org.appfuse.dao.UserDAO; +import org.appfuse.model.Role; +import org.appfuse.model.User; +import org.appfuse.service.impl.RoleManagerImpl; +import org.appfuse.service.impl.UserManagerImpl; +import org.jmock.Mock; +import org.springframework.dao.DataIntegrityViolationException; + + +public class UserManagerTest extends BaseManagerTestCase { + //~ Instance fields ======================================================== + + private UserManager userManager = new UserManagerImpl(); + private RoleManager roleManager = new RoleManagerImpl(); + private Mock userDAO = null; + private Mock roleDAO = null; + private User user = null; + private Role role = null; + + //~ Methods ================================================================ + + protected void setUp() throws Exception { + super.setUp(); + userDAO = new Mock(UserDAO.class); + userManager.setUserDAO((UserDAO) userDAO.proxy()); + roleDAO = new Mock(RoleDAO.class); + roleManager.setRoleDAO((RoleDAO) roleDAO.proxy()); + } + + public void testGetUser() throws Exception { + User testData = new User("tomcat"); + testData.getRoles().add(new Role("user")); + // set expected behavior on dao + userDAO.expects(once()).method("getUser") + .with(eq("tomcat")).will(returnValue(testData)); + + user = userManager.getUser("tomcat"); + assertTrue(user != null); + assertTrue(user.getRoles().size() == 1); + userDAO.verify(); + } + + public void testSaveUser() throws Exception { + User testData = new User("tomcat"); + testData.getRoles().add(new Role("user")); + // set expected behavior on dao + userDAO.expects(once()).method("getUser") + .with(eq("tomcat")).will(returnValue(testData)); + + user = userManager.getUser("tomcat"); + user.setPhoneNumber("303-555-1212"); + userDAO.verify(); + + // reset expectations + userDAO.reset(); + userDAO.expects(once()).method("saveUser").with(same(user)); + + userManager.saveUser(user); + assertTrue(user.getPhoneNumber().equals("303-555-1212")); + assertTrue(user.getRoles().size() == 1); + userDAO.verify(); + } + + public void testAddAndRemoveUser() throws Exception { + user = new User(); + + // call populate method in super class to populate test data + // from a properties file matching this class name + user = (User) populate(user); + + // set expected behavior on role dao + roleDAO.expects(once()).method("getRole") + .with(eq("user")).will(returnValue(new Role("user"))); + + role = roleManager.getRole(Constants.USER_ROLE); + roleDAO.verify(); + user.addRole(role); + + // set expected behavior on user dao + userDAO.expects(once()).method("saveUser").with(same(user)); + + userManager.saveUser(user); + assertTrue(user.getUsername().equals("john")); + assertTrue(user.getRoles().size() == 1); + userDAO.verify(); + + // reset expectations + userDAO.reset(); + + userDAO.expects(once()).method("removeUser").with(eq(user.getUsername())); + userManager.removeUser(user.getUsername()); + userDAO.verify(); + + // reset expectations + userDAO.reset(); + userDAO.expects(once()).method("getUser").will(returnValue(null)); + user = userManager.getUser("john"); + assertNull(user); + userDAO.verify(); + } + + public void testUserExistsException() { + // set expectations + user = new User("admin"); + user.setEmail("matt@raibledesigns.com"); + List users = new ArrayList(); + + users.add(user); + Exception ex = new DataIntegrityViolationException(""); + userDAO.expects(once()).method("saveUser").with(same(user)) + .will(throwException(ex)); + + // run test + try { + userManager.saveUser(user); + fail("Expected UserExistsException not thrown"); + } catch (UserExistsException e) { + log.debug("expected exception: " + e.getMessage()); + assertNotNull(e); + } + } +} Index: test/web/web-tests.xml =================================================================== RCS file: /cvs/appfuse/test/web/web-tests.xml,v retrieving revision 1.30 diff -u -r1.30 web-tests.xml --- test/web/web-tests.xml 28 Aug 2005 21:15:58 -0000 1.30 +++ test/web/web-tests.xml 29 Aug 2005 00:34:58 -0000 @@ -1,236 +1,234 @@ - - - - - -]> - - - - - - - - - - - Successfully ran all User JSP tests! - - - - - - &config; - - &login; - - - - - - - - &config; - - &login; - - - - - - - - - - &config; - - - - - - - - - - - - - &config; - - &login; - - - - - - - - - - &config; - - &login; - - - - - - - - - - &config; - - &login; - - - - - - - - - - - - - - &config; - - &login; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - &config; - - - - - - - - - - - - - - - - - - - - - - - - - - - - &config; - - &login; - - - - - - - - - - &config; - - &login; - - - - - - - - - - &config; - - &login; - - - - - - - + + + + + +]> + + + + + + + + + + + Successfully ran all User JSP tests! + + + + + + &config; + + &login; + + + + + + + + &config; + + &login; + + + + + + + + + + &config; + + + + + + + + + + + + + &config; + + &login; + + + + + + + + + + &config; + + &login; + + + + + + + + + + &config; + + &login; + + + + + + + + + + + + + + &config; + + &login; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + &config; + + + + + + + + + + + + + + + + + + + + + + + + + + + + &config; + + &login; + + + + + + + + + + &config; + + &login; + + + + + + + + + + &config; + + &login; + + + + + + + Index: web/index.jsp =================================================================== RCS file: /cvs/appfuse/web/index.jsp,v retrieving revision 1.5 diff -u -r1.5 index.jsp --- web/index.jsp 18 Oct 2004 17:05:33 -0000 1.5 +++ web/index.jsp 28 Aug 2005 21:43:25 -0000 @@ -1,14 +1,4 @@ <%@ include file="/common/taglibs.jsp"%> -<%-- -You can use this logic if you're running your app on 80 & 443, -but IE seems to have issues when running on non-standard ports -and spits up a Server Not Found error ---%> - - - - - Index: web/logout.jsp =================================================================== RCS file: /cvs/appfuse/web/logout.jsp,v retrieving revision 1.5 diff -u -r1.5 logout.jsp --- web/logout.jsp 23 Mar 2005 19:00:39 -0000 1.5 +++ web/logout.jsp 28 Aug 2005 21:53:30 -0000 @@ -1,5 +1,13 @@ -<%@ include file="/common/taglibs.jsp"%> - -<% session.invalidate(); %> - - +<%@ include file="/common/taglibs.jsp"%> +<%@ page import="javax.servlet.http.Cookie" %> +<%@ page import="net.sf.acegisecurity.ui.rememberme.TokenBasedRememberMeServices" %> + +<% +session.invalidate(); +Cookie terminate = new Cookie(TokenBasedRememberMeServices.ACEGI_SECURITY_HASHED_REMEMBER_ME_COOKIE_KEY, null); + +terminate.setMaxAge(0); +response.addCookie(terminate); +%> + + Index: web/WEB-INF/applicationContext-security.xml =================================================================== RCS file: /cvs/appfuse/web/WEB-INF/applicationContext-security.xml,v retrieving revision 1.8 diff -u -r1.8 applicationContext-security.xml --- web/WEB-INF/applicationContext-security.xml 28 Aug 2005 21:15:58 -0000 1.8 +++ web/WEB-INF/applicationContext-security.xml 28 Aug 2005 21:31:43 -0000 @@ -1,158 +1,198 @@ - - - - - - - - - - CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON - PATTERN_TYPE_APACHE_ANT - /j_security_check*=httpSessionContextIntegrationFilter,authenticationProcessingFilter - /**/*.html*=httpSessionContextIntegrationFilter,remoteUserFilter,anonymousProcessingFilter,securityEnforcementFilter - /**/*.jsp*=httpSessionContextIntegrationFilter,remoteUserFilter,securityEnforcementFilter - - - - - - - - - - - - - CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON - PATTERN_TYPE_APACHE_ANT - /signup.html=ROLE_ANONYMOUS,admin,user - /passwordhint.html*=ROLE_ANONYMOUS,admin,user - /**/*.html*=admin,user - /clickstreams.jsp=admin - - - - - - - - - - - - - - - - - - - - - - - - - - SELECT username,password,enabled FROM app_user WHERE username = ? - - - SELECT username,role_name FROM user_role WHERE username = ? - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - PROPAGATION_REQUIRED,-UserExistsException - PROPAGATION_REQUIRED - PROPAGATION_REQUIRED - PROPAGATION_REQUIRED,readOnly - - - - - - - - - - - - - - - - org.appfuse.service.UserManager.getUsers=admin - org.appfuse.service.UserManager.removeUser=admin - - - - + + + + + + + + + + CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON + PATTERN_TYPE_APACHE_ANT + /**=httpSessionContextIntegrationFilter,authenticationProcessingFilter,remoteUserFilter,authenticationProcessingFilter,rememberMeProcessingFilter,anonymousProcessingFilter,securityEnforcementFilter + + + + + + + + + + + + + + + CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON + PATTERN_TYPE_APACHE_ANT + /signup.html=ROLE_ANONYMOUS,admin,user + /passwordhint.html*=ROLE_ANONYMOUS,admin,user + /**/*.html*=admin,user + /clickstreams.jsp=admin + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + SELECT username,password,enabled FROM app_user WHERE username = ? + + + SELECT username,role_name FROM user_role WHERE username = ? + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + org.appfuse.service.UserManager.getUsers=admin + org.appfuse.service.UserManager.removeUser=admin + + + + + + + + + + + + + + + + + + + + + + + + + CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON + PATTERN_TYPE_APACHE_ANT + /admin/**=REQUIRES_SECURE_CHANNEL + /login*=REQUIRES_SECURE_CHANNEL + /j_security_check*=REQUIRES_SECURE_CHANNEL + /editprofile.html*=REQUIRES_SECURE_CHANNEL + /saveuser.html*=REQUIRES_SECURE_CHANNEL + /**=REQUIRES_INSECURE_CHANNEL + + + + + + + + + + + + + Index: web/pages/loginForm.jsp =================================================================== RCS file: /cvs/appfuse/web/pages/loginForm.jsp,v retrieving revision 1.14 diff -u -r1.14 loginForm.jsp --- web/pages/loginForm.jsp 28 Apr 2005 09:47:16 -0000 1.14 +++ web/pages/loginForm.jsp 29 Aug 2005 00:07:36 -0000 @@ -1,74 +1,69 @@ -<%@ include file="/common/taglibs.jsp"%> - -
-<%-- If you don't want to encrypt passwords programmatically, or you don't - care about using SSL for the login, you can change this form's action - to "j_security_check" --%> -
" - onsubmit="saveUsername(this);return validateForm(this)"> - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -
- " - alt="" class="icon" /> - - <%--c:out value="${sessionScope.ACEGI_SECURITY_LAST_EXCEPTION.message}"/--%> -
-
-
- - - -
- - - -
- - -
- - - " tabindex="4" /> - " tabindex="5" - onclick="document.getElementById('j_username').focus()" /> -

- - - -
-
-
- -<%@ include file="/scripts/login.js"%> +<%@ include file="/common/taglibs.jsp"%> + +
+
" + onsubmit="saveUsername(this);return validateForm(this)"> + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ " + alt="" class="icon" /> + + <%--c:out value="${sessionScope.ACEGI_SECURITY_LAST_EXCEPTION.message}"/--%> +
+
+
+ + + +
+ + + +
+ + +
+ " tabindex="4" /> + " tabindex="5" + onclick="document.getElementById('j_username').focus()" /> +

+ + + +
+
+
+ +<%@ include file="/scripts/login.js"%>