LoginAuthenticationAction.java

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

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.logging.Logger;
import com.mycim.framework.logging.LoggerFactory;
import com.mycim.framework.utils.lang.StringUtils;
import com.mycim.framework.utils.lang.collections.MapUtils;
import com.mycim.framework.utils.lang.math.NumberUtils;
import com.mycim.webapp.Constants;
import com.mycim.webapp.actions.SystemSetupAction;
import com.mycim.webapp.forms.security.LoginAuthenticationForm;
import com.mycim.webapp.utils.LdapHelper;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import javax.naming.NamingEnumeration;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.LdapContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zhi.cai
 * @version 6.0.0
 * @date 2020/5/21
 **/
public class LoginAuthenticationAction extends SystemSetupAction {

    private static final Logger logger = LoggerFactory.getLogger(LoginAuthenticationAction.class);

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

        LoginAuthenticationForm theForm = (LoginAuthenticationForm) form;
        Long facilityRrn = LocalContext.getFacilityRrn();
        theForm.setLanguage(I18nUtils.getCurrentLanguage().toString());

        if (request.getParameter(Constants.MODIFY_KEY) != null) {
            return authenticationSet(mapping, request, theForm, facilityRrn);
        } else if (request.getParameter("reset") != null) {
            return authenticationInit(mapping, theForm, facilityRrn);
        }
        return authenticationInit(mapping, theForm, facilityRrn);
    }

    public Map ldapConnectTest(LoginAuthenticationForm theForm) {
        Map resultMsg = new HashMap();
        Map<String, Object> ldapInfo = theForm.toMap();
        String language = I18nUtils.getCurrentLanguage().toString();
        String usr = theForm.getTestUser();
        String pwd = theForm.getTestPwd();
        validateLdapInfo(theForm, "test");
        String msg = LdapHelper.authenticate(usr, pwd, ldapInfo);
        Assert.isFalse(msg.length() > 0, Errors.create().content(msg).build());

        if (StringUtils.equalsIgnoreCase(language, "CN")) {
            resultMsg.put("msg", "Ldap 连接测试成功!");
        } else {
            resultMsg.put("msg", "Ldap connect test success!");
        }
        return resultMsg;
    }

    public Map getUserInfo(LoginAuthenticationForm theForm) throws Exception {
        validateLdapInfo(theForm, "test");
        Map<String, Object> ldapInfo = theForm.toMap();
        String usr = theForm.getTestUser();
        Map userInfo = LdapHelper.searchUserInfo(usr, ldapInfo);

        return userInfo;
    }


    public List getUserInfoList(LoginAuthenticationForm theForm) throws Exception {
        validateLdapInfo(theForm, "test");
        String usr = theForm.getTestUser();
        Map<String, Object> ldapInfo = theForm.toMap();
        List jsonList = LdapHelper.getUserKey(usr, ldapInfo);

        return jsonList;
    }


    public List searchSubEntry(LoginAuthenticationForm theForm) throws Exception {
        String usr = theForm.getTestUser();
        Map<String, Object> ldapInfo = theForm.toMap();

        String baseDn = MapUtils.getString(ldapInfo, "searchDn");
        LdapContext ctx = LdapHelper.getCtx(ldapInfo);
        //        logger.info("得到了LdapContext...: " + JsonUtils.toString(ctx));
        NamingEnumeration<Object> sret = LdapHelper.searchSubEntry(ctx, baseDn, "", "");
        List resutList = new ArrayList();
        while (sret.hasMore()) {
            SearchResult sr = (SearchResult) sret.next();
            Map obj = new HashMap();
            obj.put("attributes", sr.getAttributes());
            obj.put("nameInNamespace", sr.getNameInNamespace());
            obj.put("name", sr.getName());
            obj.put("object", sr.getObject());
            resutList.add(obj);
        }
        return resutList;
    }

    public ActionForward authenticationSet(ActionMapping mapping, HttpServletRequest request,
                                           LoginAuthenticationForm theForm, Long facilityRrn) {
        theForm.setFacilityRrn(facilityRrn);
        Map<String, Object> info = theForm.toMap();
        String type = theForm.getAuthenticationType();

        if (StringUtils.equalsIgnoreCase("2", type)) {
            validateLdapInfo(theForm, "set");
        }
        sysService.setLoginAuthenticationInfo(info);
        return authenticationInit(mapping, theForm, facilityRrn);
    }

    public ActionForward authenticationInit(ActionMapping mapping, LoginAuthenticationForm theForm, Long facilityRrn) {
        Map<String, Object> info = sysService.getLoginAuthenticationInfo(facilityRrn);
        if (info != null) {
            theForm.setMapInfo(info);
        }
        return (new ActionForward(mapping.getInput()));
    }

    public void validateLdapInfo(LoginAuthenticationForm theForm, String type) {
        String msg = "";
        String language = theForm.getLanguage();
        String url = theForm.getProviderUrl();
        if (StringUtils.isEmpty(url)) {
            if (StringUtils.equalsIgnoreCase(language, "CN")) {
                msg += "URL 不能为空!</br>";
            } else {
                msg += "URL can not be empty!</br>";
            }
        }
        String baseDn = theForm.getBaseDn();
        if (StringUtils.isEmpty(baseDn)) {
            if (StringUtils.equalsIgnoreCase(language, "CN")) {
                msg += "检索目录不能为空!</br>";
            } else {
                msg += "Base DN can not be empty!</br>";
            }
        }

        String securityAuthentication = theForm.getSecurityAuthentication();
        if (StringUtils.isEmpty(securityAuthentication)) {
            if (StringUtils.equalsIgnoreCase(language, "CN")) {
                msg += "认证方式不能为空!</br>";
            } else {
                msg += "Security Authentication can not be empty!</br>";
            }
        }

        String factoryInitial = theForm.getFactoryInitial();

        if (StringUtils.isEmpty(factoryInitial)) {
            if (StringUtils.equalsIgnoreCase(language, "CN")) {
                msg += "前后关系不能为空!</br>";
            } else {
                msg += "Factory Initial can not be empty!</br>";
            }
        }
        /*
        String principalSuffix = theForm.getPrincipalSuffix();
        if(StringUtils.isEmpty(principalSuffix)){
            if (StringUtils.equalsIgnoreCase(language, "CN")) {
                msg += "用户名后缀不能为空!</br>";
            } else {
                msg += "Principal Suffix can not be empty!</br>";
            }
        }
         */

        String securityPrincipal = theForm.getSecurityPrincipal();
        if (StringUtils.isEmpty(securityPrincipal)) {
            if (StringUtils.equalsIgnoreCase(language, "CN")) {
                msg += "管理员名称不能为空!</br>";
            } else {
                msg += "Security Principal can not be empty!</br>";
            }
        }

        String securityCredentials = theForm.getSecurityCredentials();

        if (StringUtils.isEmpty(securityCredentials)) {
            if (StringUtils.equalsIgnoreCase(language, "CN")) {
                msg += "管理员密码不能为空!</br>";
            } else {
                msg += "Security Credentials can not be empty!</br>";
            }
        }
        if (StringUtils.equalsIgnoreCase("test", type)) {
            String testUser = theForm.getTestUser();
            if (StringUtils.isEmpty(testUser)) {
                if (StringUtils.equalsIgnoreCase(language, "CN")) {
                    msg += "用户名不能为空!</br>";
                } else {
                    msg += "user Id can not be empty!</br>";
                }
            }

            String testPwd = theForm.getTestPwd();
            if (StringUtils.isEmpty(testPwd)) {
                if (StringUtils.equalsIgnoreCase(language, "CN")) {
                    msg += "用户密码不能为空!</br>";
                } else {
                    msg += "User password can not be empty!</br>";
                }
            }
        }

        String timeOut = theForm.getTimeOutStr();
        if (NumberUtils.toLong(timeOut, 0) < 1L) {
            if (StringUtils.equalsIgnoreCase(language, "CN")) {
                msg += "超时时间不能为空或者小于0!</br>";
            } else {
                msg += "Timeout cannot be empty or less than 0!</br>";
            }
        } else {
            theForm.setTimeOut(NumberUtils.toLong(timeOut));
        }

        Assert.isFalse(msg.length() > 0, Errors.create().content(msg).build());
    }

}