UserSaveAction.java

package com.mycim.webapp.actions.setting.security.user;

import com.fa.sesa.exception.Assert;
import com.fa.sesa.exception.Errors;
import com.fa.sesa.i18n.I18nUtils;
import com.fa.sesa.threadlocal.LocalContext;
import com.mycim.framework.utils.beans.PropertyUtils;
import com.mycim.framework.utils.lang.StringUtils;
import com.mycim.valueobject.MessageIdList;
import com.mycim.valueobject.ObjectList;
import com.mycim.valueobject.bas.Relation;
import com.mycim.valueobject.bas.RelationHistory;
import com.mycim.valueobject.consts.SessionNames;
import com.mycim.valueobject.security.User;
import com.mycim.valueobject.security.UserGroup;
import com.mycim.webapp.Constants;
import com.mycim.webapp.WebUtils;
import com.mycim.webapp.actions.CimSetupAction;
import com.mycim.webapp.forms.RootForm;
import com.mycim.webapp.forms.security.UserInfoForm;
import com.mycim.webapp.utils.LdapHelper;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.util.*;

/**
 * @author Johnson Wang
 **/
public class UserSaveAction extends CimSetupAction {
    private final static String REGX = "^[a-z0-9A-Z]+$";

    @Override
    public ActionForward init(ActionMapping mapping, ActionForm form, HttpServletRequest request,
                              HttpServletResponse response) throws Exception {

        UserInfoForm theform = (UserInfoForm) form;
        String id = theform.getInstanceId().trim().toUpperCase();
        User user = new User(id, getNamedSpace(ObjectList.USER_KEY, LocalContext.getFacilityRrn()),
                             ObjectList.USER_KEY);
        // According to the instance's object, retrieve the value object
        user = (User) getInstance(user);

        // Copy value object properties to form bean.
        PropertyUtils.copyProperties(theform, user);
        theform.setPasswordConfirm(user.getPassword());

        if (user.getInstanceRrn() == 0) {
            theform.setTransId(Constants.CREATE_KEY);
            theform.setFirstLoginPasswordExpired("on");
            return mapping.findForward("modify");
        }

        if (StringUtils.isNotBlank(theform.getFirstLoginPasswordExpired()) &&
                StringUtils.equals(theform.getFirstLoginPasswordExpired(), "1")) {
            theform.setFirstLoginPasswordExpired("on");
        }

        theform.setTransId(Constants.MODIFY_KEY);
        request.setAttribute("oldPassword", theform.getPassword());
        return mapping.findForward("modify");
    }

    public ActionForward back(ActionMapping mapping, ActionForm form, HttpServletRequest request,
                              HttpServletResponse response) throws Exception {
        String jumpToUser = ((UserInfoForm) form).getJumpToUser();
        if ("1".equals(jumpToUser)) {
            response.sendRedirect(request.getContextPath() + "/userQuery.do?init=1");
        } else {
            response.sendRedirect(request.getContextPath() + "/setupentry?objtype=user");
        }
        return WebUtils.NULLActionForward;
    }

    public ActionForward create(ActionMapping mapping, RootForm theform, HttpServletRequest request,
                                HttpServletResponse response) throws Exception {
        UserInfoForm userform = (UserInfoForm) theform;
        User user = new User(userform.getInstanceId(), userform.getNamedSpace(), ObjectList.USER_KEY);
        user = (User) getInstance(user);
        user.setTransPerformedby(LocalContext.getUserId());

        userform.setPassword(StringUtils.trim(userform.getPassword()));
        userform.setPasswordConfirm(StringUtils.trim(userform.getPasswordConfirm()));

        Assert.isTrue(StringUtils.equals(userform.getPassword(), userform.getPasswordConfirm()),
                      Errors.create().key(MessageIdList.USER_PSW_NOT_SAME).content("密码不相同!").build());

        Assert.isFalse(StringUtils.isEmpty(userform.getPassword()),
                       Errors.create().key(MessageIdList.USER_PSW_NOT_SAME).content("密码不相同!").build());

        // when inserting or updating, populate the value object for process method
        PropertyUtils.copyProperties(user, userform);
        user.setTransId(Constants.CREATE_KEY);
        user.setPassword(StringUtils.encodeByMD5(user.getPassword()));
        process(user);
        // when add user, we will add it automaticly to a EVERYONE group
        // I suggest that adding this logic into session bean layer,
        // not here.
        long grpEveryone = getInstanceRrn("EVERYONE",
                                          getNamedSpace(ObjectList.USERGROUP_KEY, LocalContext.getFacilityRrn()),
                                          ObjectList.USERGROUP_KEY);

        // if such EVERYONE usergroup exist, add to it.
        if (grpEveryone > 0) {
            addUserToGroup(user.getInstanceRrn(), grpEveryone);
        }

        // 如果locked 放入no_enter用户组
        if (StringUtils.equals(user.getUserStatus(), Constants.LOCKED_KEY)) {
            long noEnterRrn = getInstanceRrn(Constants.NO_ENTER_KEY,
                                             getNamedSpace(ObjectList.USERGROUP_KEY, LocalContext.getFacilityRrn()),
                                             ObjectList.USERGROUP_KEY);
            if (noEnterRrn > 0) {
                addUserToGroup(user.getInstanceRrn(), noEnterRrn);
            }
        }
        theform.setTransId(Constants.MODIFY_KEY);
        request.setAttribute(SessionNames.USERPROFILE_KEY, user);
        return (mapping.findForward("modify"));
    }

    public ActionForward delete(ActionMapping mapping, RootForm theform, HttpServletRequest request,
                                HttpServletResponse response) {
        UserInfoForm userform = (UserInfoForm) theform;
        User user = new User(userform.getInstanceId(), userform.getNamedSpace(), ObjectList.USER_KEY);
        user = (User) getInstance(user);
        user.setTransPerformedby(LocalContext.getUserId());
        user.setTransId(Constants.DELETE_KEY);

        // clear id
        theform.setInstanceId(null);

        process(user);

        theform.setTransId(Constants.MODIFY_KEY);

        request.setAttribute("controlFlag", "1");
        return mapping.findForward("setup");
    }

    public String asynDelete(Map<String, Object> params) {
        StringBuilder msg = new StringBuilder();
        String instanceId = MapUtils.getString(params, "instanceId");
        String namedSpace = MapUtils.getString(params, "namedSpace");
        Long facilityRrn = Long.parseLong(MapUtils.getString(params, "facilityRrn"));
        User user = new User(instanceId, namedSpace, ObjectList.USER_KEY);
        user = (User) getInstance(user);
        user = qryRoleAllByUser(user, facilityRrn);
        user.setTransId(Constants.DELETE_KEY);
        msg.append(I18nUtils.getCurrentLanguage() + ".");
        if (CollectionUtils.isNotEmpty(user.getRoleList())) {
            for (Object s : user.getRoleList()) {
                Relation temp = (Relation) s;
                msg.append(temp.getInstanceId() + ".");
            }
            return msg.toString();
        }
        List<RelationHistory> historyList = securityService.getRelationHistory(user.getInstanceRrn());
        if (CollectionUtils.isNotEmpty(historyList)) {
            msg.append("no");
            return msg.toString();
        }
        process(user);
        msg.append("ok");
        return msg.toString();
    }

    public User qryRoleAllByUser(User tempUser, Long facilityRrn) {
        User user = tempUser;
        String namedSpace = baseService.getNamedSpace(facilityRrn, ObjectList.USER_KEY);
        long userRrn = baseService
                .getNamedObjectRrn(user.getInstanceId().toUpperCase(), namedSpace, ObjectList.USER_KEY);
        Collection userRoles = securityService.getUserRoles(userRrn);
        user.setRoleList(userRoles);
        if (user == null) {
            return null;
        }
        return user;
    }

    public ActionForward modify(ActionMapping mapping, RootForm theform, HttpServletRequest request,
                                HttpServletResponse response) throws Exception {
        UserInfoForm userform = (UserInfoForm) theform;
        User user = new User(userform.getInstanceId(), userform.getNamedSpace(), ObjectList.USER_KEY);
        user = (User) getInstance(user);
        user.setTransPerformedby(LocalContext.getUserId());

        userform.setPassword(StringUtils.trim(userform.getPassword()));
        userform.setPasswordConfirm(StringUtils.trim(userform.getPasswordConfirm()));

        Assert.isTrue(StringUtils.equals(userform.getPassword(), userform.getPasswordConfirm()),
                      Errors.create().key(MessageIdList.USER_PSW_NOT_SAME).content("密码不相同!").build());

        Assert.isFalse(StringUtils.isEmpty(userform.getPassword()),
                       Errors.create().key(MessageIdList.USER_PSW_NOT_SAME).content("密码不相同!").build());

        //        String ldapId = userform.getLdapId();
        //        Assert.isTrue(ldapId.matches(REGX),
        //                      Errors.create().content("LDAP ID only allows Chinese characters and
        //                      letters!").build());
        //        User _user = securityService.getUserByLdapId(ldapId);
        //        Assert.isFalse(
        //                StringUtils.isNotBlank(_user.getInstanceId()) && !StringUtils.equals(userform
        //                .getInstanceId(),
        //                                                                                     _user
        //                                                                                     .getInstanceId()),
        //                Errors.create().key(MessageIdList.USER_LDAPID_ALREADY_BOUND).content("LdapId
        //                已经被{}绑定!").args(
        //                        _user.getInstanceId()).build());

        boolean unchanged = isPasswordChanged(user, userform);
        PropertyUtils.copyProperties(user, theform);
        // if password changed, update the password modify time;
        if (!unchanged) {
            user.setPasswordModifiedTime(new Timestamp(System.currentTimeMillis()));
            user.setPassword(StringUtils.encodeByMD5(userform.getPassword()));
        }


        user.setTransId(Constants.MODIFY_KEY);
        //        user.setLdapId(ldapId);

        process(user);

        user = (User) getInstance(user);

        userform.setTransId(Constants.MODIFY_KEY);

        request.setAttribute("controlFlag", "1");
        request.setAttribute(SessionNames.USERPROFILE_KEY, user);
        request.setAttribute("oldPassword", user.getPassword());
        userform.setPassword(user.getPassword());
        userform.setPasswordConfirm(user.getPassword());
        //        userform.setLdapId(ldapId);
        return mapping.findForward("modify");


    }

    public ActionForward syncLdap(ActionMapping mapping, RootForm theform, HttpServletRequest request,
                                  HttpServletResponse response) throws Exception {
        UserInfoForm userform = (UserInfoForm) theform;
        User user = new User(userform.getInstanceId(), userform.getNamedSpace(), ObjectList.USER_KEY);
        user = (User) getInstance(user);
        Map<String, Object> authenticationInfo = sysService.getLoginAuthenticationInfo(LocalContext.getFacilityRrn());
        authenticationInfo.put("searchDn", "");
        Map userInfo = LdapHelper.searchUserInfo(user.getLdapId(), authenticationInfo);
        //        LOGGER.info("--->>>查询到信息: " + JsonUtils.toString(userInfo));
        String mail = MapUtils.getString(userInfo, "mail");
        if (StringUtils.isNotEmpty(mail)) {
            user.setEmailAddress(mail);
            user.setTransId(Constants.MODIFY_KEY);
            process(user);
        }

        user = (User) getInstance(user);
        PropertyUtils.copyProperties(theform, user);
        userform.setTransId(Constants.MODIFY_KEY);
        request.setAttribute("controlFlag", "1");
        request.setAttribute(SessionNames.USERPROFILE_KEY, user);
        request.setAttribute("oldPassword", user.getPassword());
        userform.setPassword(user.getPassword());
        userform.setPasswordConfirm(user.getPassword());
        return mapping.findForward("modify");
    }

    public ActionForward noEnter(ActionMapping mapping, RootForm theform, HttpServletRequest request,
                                 HttpServletResponse response) throws Exception {
        UserInfoForm userform = (UserInfoForm) theform;
        User user = new User(userform.getInstanceId(), userform.getNamedSpace(), ObjectList.USER_KEY);
        user = (User) getInstance(user);
        user.setTransPerformedby(LocalContext.getUserId());

        userform.setPassword(StringUtils.trim(userform.getPassword()));
        userform.setPasswordConfirm(StringUtils.trim(userform.getPasswordConfirm()));

        Assert.isTrue(StringUtils.equals(userform.getPassword(), userform.getPasswordConfirm()),
                      Errors.create().key(MessageIdList.USER_PSW_NOT_SAME).content("密码不相同!").build());

        Assert.isFalse(StringUtils.isEmpty(userform.getPassword()),
                       Errors.create().key(MessageIdList.USER_PSW_NOT_SAME).content("密码不相同!").build());

        // when inserting or updating, populate the value object for process method
        PropertyUtils.copyProperties(user, userform);

        user.setPasswordModifiedTime(new Timestamp(System.currentTimeMillis()));
        userform.setMenuId("");
        userform.setPagerNumber("");
        user.setPagerNumber("");
        String password = genRandomNum(10);
        userform.setPassword(password);
        user.setPassword(password);
        userform.setPasswordConfirm(password);
        user.setPasswordConfirm(password);
        Collection userGroups = securityService.getUserGroups(user);
        for (Iterator iterator = userGroups.iterator(); iterator.hasNext(); ) {
            Relation relation = (Relation) iterator.next();
            securityService.removeUserFromGroup(relation);
        }
        user.setShiftId("");
        userform.setShiftId("");
        user.setMenuRrn(null);
        userform.setMenuRrn(null);
        UserGroup userGroup = new UserGroup(Constants.NO_ENTER_KEY,
                                            getNamedSpace(ObjectList.USERGROUP_KEY, LocalContext.getFacilityRrn()),
                                            ObjectList.USERGROUP_KEY);
        userGroup = securityService.getUserGroup(userGroup);
        this.addUserToGroup(user, userGroup);
        user.setTransId(Constants.MODIFY_KEY);

        process(user);

        user = (User) getInstance(user);

        userform.setTransId(Constants.MODIFY_KEY);

        request.setAttribute("controlFlag", "1");
        request.setAttribute(SessionNames.USERPROFILE_KEY, user);
        request.setAttribute("oldPassword", user.getPassword());
        userform.setPasswordConfirm(user.getPassword());
        return mapping.findForward("modify");
    }

    public ActionForward canEnter(ActionMapping mapping, RootForm theform, HttpServletRequest request,
                                  HttpServletResponse response) throws Exception {
        UserInfoForm userform = (UserInfoForm) theform;
        User user = new User(userform.getInstanceId(), userform.getNamedSpace(), ObjectList.USER_KEY);
        user = (User) getInstance(user);
        user.setTransPerformedby(LocalContext.getUserId());

        userform.setPassword(StringUtils.trim(userform.getPassword()));
        userform.setPasswordConfirm(StringUtils.trim(userform.getPasswordConfirm()));

        Assert.isTrue(StringUtils.equals(userform.getPassword(), userform.getPasswordConfirm()),
                      Errors.create().key(MessageIdList.USER_PSW_NOT_SAME).content("密码不相同!").build());

        Assert.isFalse(StringUtils.isEmpty(userform.getPassword()),
                       Errors.create().key(MessageIdList.USER_PSW_NOT_SAME).content("密码不相同!").build());

        // when inserting or updating, populate the value object for process method
        PropertyUtils.copyProperties(user, userform);

        UserGroup userGroup = new UserGroup(Constants.NO_ENTER_KEY,
                                            getNamedSpace(ObjectList.USERGROUP_KEY, LocalContext.getFacilityRrn()),
                                            ObjectList.USERGROUP_KEY);
        userGroup = securityService.getUserGroup(userGroup);
        Relation relation = new Relation();
        relation.setFromRrn(user.getInstanceRrn());
        relation.setToRrn(userGroup.getInstanceRrn());
        relation.setTransId(Constants.MODIFY_KEY);
        relation.setTransPerformedby(LocalContext.getUserId());

        securityService.removeUserFromGroup(relation);
        userform.setUserStatus(Constants.NORMAL_KEY);
        user.setUserStatus(Constants.NORMAL_KEY);
        user.setTransId(Constants.MODIFY_KEY);

        process(user);

        user = (User) getInstance(user);

        userform.setTransId(Constants.MODIFY_KEY);

        request.setAttribute("controlFlag", "1");
        request.setAttribute(SessionNames.USERPROFILE_KEY, user);
        request.setAttribute("oldPassword", user.getPassword());
        userform.setPasswordConfirm(user.getPassword());

        return mapping.findForward("modify");
    }

    public ActionForward canNotEnter(ActionMapping mapping, RootForm theform, HttpServletRequest request,
                                     HttpServletResponse response) throws Exception {
        UserInfoForm userform = (UserInfoForm) theform;
        User user = new User(userform.getInstanceId(), userform.getNamedSpace(), ObjectList.USER_KEY);
        user = (User) getInstance(user);
        user.setTransPerformedby(LocalContext.getUserId());

        userform.setPassword(StringUtils.trim(userform.getPassword()));
        userform.setPasswordConfirm(StringUtils.trim(userform.getPasswordConfirm()));

        Assert.isTrue(StringUtils.equals(userform.getPassword(), userform.getPasswordConfirm()),
                      Errors.create().key(MessageIdList.USER_PSW_NOT_SAME).content("密码不相同!").build());

        Assert.isFalse(StringUtils.isEmpty(userform.getPassword()),
                       Errors.create().key(MessageIdList.USER_PSW_NOT_SAME).content("密码不相同!").build());

        // when inserting or updating, populate the value object for process method
        PropertyUtils.copyProperties(user, userform);

        UserGroup userGroup = new UserGroup(Constants.NO_ENTER_KEY,
                                            getNamedSpace(ObjectList.USERGROUP_KEY, LocalContext.getFacilityRrn()),
                                            ObjectList.USERGROUP_KEY);
        userGroup = securityService.getUserGroup(userGroup);

        this.addUserToGroup(user, userGroup);
        userform.setUserStatus(Constants.LOCKED_KEY);
        user.setUserStatus(Constants.LOCKED_KEY);
        user.setTransId(Constants.MODIFY_KEY);

        process(user);

        user = (User) getInstance(user);

        userform.setTransId(Constants.MODIFY_KEY);

        request.setAttribute("controlFlag", "1");
        request.setAttribute(SessionNames.USERPROFILE_KEY, user);
        request.setAttribute("oldPassword", user.getPassword());
        userform.setPasswordConfirm(user.getPassword());

        return mapping.findForward("modify");
    }

    public ActionForward members(ActionMapping mapping, RootForm theform, HttpServletRequest request,
                                 HttpServletResponse response) {
        User user = new User(theform.getInstanceId(), theform.getNamedSpace(), ObjectList.USER_KEY);
        user = (User) getInstance(user);
        user.setTransPerformedby(LocalContext.getUserId());
        Collection userGroups = null;
        userGroups = getUserGroups(user);
        user.setUserGroups(userGroups);
        theform.setTransId(Constants.MODIFY_KEY);
        theform.setPages(new Integer(1));
        request.setAttribute(SessionNames.USERPROFILE_KEY, user);
        return mapping.findForward("members");
    }

    public ActionForward copy(ActionMapping mapping, RootForm theform, HttpServletRequest request,
                              HttpServletResponse response) throws Exception {
        UserInfoForm userform = (UserInfoForm) theform;
        User user = new User(userform.getInstanceId(), userform.getNamedSpace(), ObjectList.USER_KEY);
        user = (User) getInstance(user);
        user.setTransPerformedby(LocalContext.getUserId());
        // copy function is a special function other than adding, deleting or updating
        // the new Id is stored in the url COPY key
        String id = request.getParameter(Constants.COPY_KEY);

        user.setInstanceId(id);

        doCopy(userform, user);
        userform.setPasswordConfirm(userform.getPassword());
        // for logic equal tag, copy is the same action as create
        userform.setTransId(Constants.CREATE_KEY);

        request.setAttribute(SessionNames.USERPROFILE_KEY, user);
        return (mapping.findForward("modify"));
    }

    /**
     * 根据部门获取usersList
     *
     * @param mapping
     * @param theform
     * @param request
     * @param response
     * @throws Exception
     */
    public void getUsers(ActionMapping mapping, RootForm theform, HttpServletRequest request,
                         HttpServletResponse response) throws Exception {

        String deptId = request.getParameter("dept");
        List<Map> userList = new ArrayList();
        userList = securityService.getUsers(deptId);

        response.setContentType("application/xml;charset=UTF-8");
        PrintWriter pw = response.getWriter();
        pw.println("<data>");
        if (userList != null) {
            Iterator it = userList.iterator();
            pw.println("<list></list>");
            while (it.hasNext()) {
                Map map = (Map) it.next();
                pw.println("<list>" + map.get("userName") + "|" + map.get("userRrn") + "</list>");
            }
        }
        pw.println("</data>");
        pw.close();

        request.setAttribute("users", userList);
    }

    /**
     * 根据部门和用户获取tel
     *
     * @param mapping
     * @param theform
     * @param request
     * @param response
     * @throws Exception
     */
    public void getTel(ActionMapping mapping, RootForm theform, HttpServletRequest request,
                       HttpServletResponse response) throws Exception {

        String deptId = request.getParameter("dept");
        String userId = request.getParameter("user");
        String tel = securityService.getTel(deptId, userId);
        tel = StringUtils.defaultIfBlank(tel, StringUtils.EMPTY);
        response.setContentType("application/xml;charset=UTF-8");
        PrintWriter pw = response.getWriter();
        pw.println(tel);
        pw.close();

        request.setAttribute("tel", tel);
    }

    public ActionForward resetPassword(ActionMapping mapping, RootForm theform, HttpServletRequest request,
                                       HttpServletResponse response) {
        UserInfoForm userform = (UserInfoForm) theform;
        User user = new User(userform.getInstanceId(), userform.getNamedSpace(), ObjectList.USER_KEY);
        user = (User) getInstance(user);
        user.setTransPerformedby(LocalContext.getUserId());

        userform.setPassword(StringUtils.trim("123456"));
        userform.setPasswordConfirm(StringUtils.trim("123456"));

        Assert.isTrue(StringUtils.equals(userform.getPassword(), userform.getPasswordConfirm()),
                      Errors.create().key(MessageIdList.USER_PSW_NOT_SAME).content("密码不相同!").build());

        Assert.isFalse(StringUtils.isEmpty(userform.getPassword()),
                       Errors.create().key(MessageIdList.USER_PSW_NOT_SAME).content("密码不相同!").build());

        // when inserting or updating, populate the value object for process method
        PropertyUtils.copyProperties(user, userform);

        user.setTransId(Constants.MODIFY_KEY);
        user.setPassword(StringUtils.encodeByMD5(user.getPassword()));
        process(user);
        userform.setTransId(Constants.MODIFY_KEY);
        WebUtils.setSuccessMsg(request);
        return mapping.findForward("modify");
    }

    private boolean isPasswordChanged(User user, UserInfoForm form) {
        return StringUtils.equals(user.getPassword(), form.getPassword());
    }

    private String genRandomNum(int pwdLen) {
        final int maxNum = 36;
        int i;
        int count = 0;
        char[] str = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
                't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};

        StringBuffer pwd = new StringBuffer();
        Random r = new Random();
        while (count < pwdLen) {

            i = Math.abs(r.nextInt(maxNum));

            if (i >= 0 && i < str.length) {
                pwd.append(str[i]);
                count++;
            }
        }

        return pwd.toString();
    }

}
/*
 * Modification Log Log No : Name : Modified Date: Description :
 */