commit fc005dd6c5342192fee6b3a6d7526c0b127996d1 Author: pioneer Date: Thu Nov 24 10:18:42 2022 +0800 open diff --git a/README.md b/README.md new file mode 100644 index 0000000..330c6ed --- /dev/null +++ b/README.md @@ -0,0 +1,6 @@ +# open-JSD-10091 + +JSD-10091 ,与统一认证系统进行认证,所有的用户信息和组织架构数据,以webservice的形式获取\ +免责说明:该源码为第三方爱好者提供,不保证源码和方案的可靠性,也不提供任何形式的源码教学指导和协助!\ +仅作为开发者学习参考使用!禁止用于任何商业用途!\ +为保护开发者隐私,开发者信息已隐去!若原开发者希望公开自己的信息,可联系【pioneer】处理。 \ No newline at end of file diff --git a/plugin.xml b/plugin.xml new file mode 100644 index 0000000..22cfec5 --- /dev/null +++ b/plugin.xml @@ -0,0 +1,20 @@ + + com.eco.plugin.xx.zcgjsync_EK + + yes + 1.0.3 + 10.0 + 2018-07-31 + fr.open + + + com.eco.plugin.xx.zcgjsync + + + + + + + + \ No newline at end of file diff --git a/src/main/java/com/eco/plugin/xx/zcgjsync/bean/OrgBean.java b/src/main/java/com/eco/plugin/xx/zcgjsync/bean/OrgBean.java new file mode 100644 index 0000000..7c315c2 --- /dev/null +++ b/src/main/java/com/eco/plugin/xx/zcgjsync/bean/OrgBean.java @@ -0,0 +1,78 @@ +package com.eco.plugin.xx.zcgjsync.bean; + +/** + * 机构实体 + */ +public class OrgBean { + + //token + private String token; + //流水号 + private String ID; + //操作类型 1:新增 2:修改 3:停用 4:启用 + private String FROMOPERTYPE; + //状态 1:已启用 0:已停用 + private String STATUS; + //单位代码 + private String IU_CODE; + //单位全称 + private String IU_FULLNAME; + //上级管理单位代码 + private String IU_LSSJDW_ID; + + public String getToken() { + return token; + } + + public void setToken(String token) { + this.token = token; + } + + public String getID() { + return ID; + } + + public void setID(String ID) { + this.ID = ID; + } + + public String getFROMOPERTYPE() { + return FROMOPERTYPE; + } + + public void setFROMOPERTYPE(String FROMOPERTYPE) { + this.FROMOPERTYPE = FROMOPERTYPE; + } + + public String getSTATUS() { + return STATUS; + } + + public void setSTATUS(String STATUS) { + this.STATUS = STATUS; + } + + public String getIU_CODE() { + return IU_CODE; + } + + public void setIU_CODE(String IU_CODE) { + this.IU_CODE = IU_CODE; + } + + public String getIU_FULLNAME() { + return IU_FULLNAME; + } + + public void setIU_FULLNAME(String IU_FULLNAME) { + this.IU_FULLNAME = IU_FULLNAME; + } + + public String getIU_LSSJDW_ID() { + return IU_LSSJDW_ID; + } + + public void setIU_LSSJDW_ID(String IU_LSSJDW_ID) { + this.IU_LSSJDW_ID = IU_LSSJDW_ID; + } +} diff --git a/src/main/java/com/eco/plugin/xx/zcgjsync/bean/UserEntity.java b/src/main/java/com/eco/plugin/xx/zcgjsync/bean/UserEntity.java new file mode 100644 index 0000000..dc3cc4c --- /dev/null +++ b/src/main/java/com/eco/plugin/xx/zcgjsync/bean/UserEntity.java @@ -0,0 +1,88 @@ +package com.eco.plugin.xx.zcgjsync.bean; + +/** + * 机构实体 + */ +public class UserEntity { + + //流水号 + private String ID; + //操作类型 1:新增 2:修改 3:停用 4:启用 + private String FROMOPERTYPE; + //状态 1:已启用 0:已停用 + private String STATUS; + //姓名 + private String NAME; + //登陆号 + private String NO; + //email + private String EMAIL; + //电话 + private String TELEPHONE; + //组织机构 + private String IU_LSSJDW_ID; + + public String getID() { + return ID; + } + + public void setID(String ID) { + this.ID = ID; + } + + public String getFROMOPERTYPE() { + return FROMOPERTYPE; + } + + public void setFROMOPERTYPE(String FROMOPERTYPE) { + this.FROMOPERTYPE = FROMOPERTYPE; + } + + public String getSTATUS() { + return STATUS; + } + + public void setSTATUS(String STATUS) { + this.STATUS = STATUS; + } + + public String getIU_LSSJDW_ID() { + return IU_LSSJDW_ID; + } + + public void setIU_LSSJDW_ID(String IU_LSSJDW_ID) { + this.IU_LSSJDW_ID = IU_LSSJDW_ID; + } + + public String getNAME() { + return NAME; + } + + public void setNAME(String NAME) { + this.NAME = NAME; + } + + public String getNO() { + return NO; + } + + public void setNO(String NO) { + this.NO = NO; + } + + public String getEMAIL() { + return EMAIL; + } + + public void setEMAIL(String EMAIL) { + this.EMAIL = EMAIL; + } + + public String getTELEPHONE() { + return TELEPHONE; + } + + public void setTELEPHONE(String TELEPHONE) { + this.TELEPHONE = TELEPHONE; + } +} diff --git a/src/main/java/com/eco/plugin/xx/zcgjsync/config/InitializeMonitor.java b/src/main/java/com/eco/plugin/xx/zcgjsync/config/InitializeMonitor.java new file mode 100644 index 0000000..9e9a4ef --- /dev/null +++ b/src/main/java/com/eco/plugin/xx/zcgjsync/config/InitializeMonitor.java @@ -0,0 +1,21 @@ +package com.eco.plugin.xx.zcgjsync.config; + +import com.fr.plugin.context.PluginContext; +import com.fr.plugin.observer.inner.AbstractPluginLifecycleMonitor; + +/** + * @author xx + * @version 10.0 + * Created by xx on 2021-12-03 + */ +public class InitializeMonitor extends AbstractPluginLifecycleMonitor { + @Override + public void afterRun(PluginContext pluginContext) { + PluginSimpleConfig.getInstance(); + } + + @Override + public void beforeStop(PluginContext pluginContext) { + + } +} diff --git a/src/main/java/com/eco/plugin/xx/zcgjsync/config/PluginSimpleConfig.java b/src/main/java/com/eco/plugin/xx/zcgjsync/config/PluginSimpleConfig.java new file mode 100644 index 0000000..c337eb3 --- /dev/null +++ b/src/main/java/com/eco/plugin/xx/zcgjsync/config/PluginSimpleConfig.java @@ -0,0 +1,79 @@ +package com.eco.plugin.xx.zcgjsync.config; + +import com.fr.config.*; +import com.fr.config.holder.Conf; +import com.fr.config.holder.factory.Holders; +import com.fr.intelli.record.Focus; +import com.fr.intelli.record.Original; +import com.fr.record.analyzer.EnableMetrics; + +@Visualization(category = "数据同步配置") +@EnableMetrics +public class PluginSimpleConfig extends DefaultConfiguration { + + private static volatile PluginSimpleConfig config = null; + + @Focus(id="com.eco.plugin.xx.zcgjsync.config", text = "数据同步配置", source = Original.PLUGIN) + public static PluginSimpleConfig getInstance() { + if (config == null) { + config = ConfigContext.getConfigInstance(PluginSimpleConfig.class); + } + return config; + } + + @Identifier(value = "clientId", name = "应用id", description = "应用id", status = Status.SHOW) + private Conf clientId = Holders.simple(""); + + @Identifier(value = "secret", name = "应用key", description = "应用key", status = Status.SHOW) + private Conf secret = Holders.simple(""); + + @Identifier(value = "privatekey", name = "解密私钥", description = "解密私钥", status = Status.SHOW) + private Conf privatekey = Holders.simple(""); + + @Identifier(value = "timeout", name = "鉴权超时时间(秒)", description = "鉴权超时时间(秒)", status = Status.SHOW) + private Conf timeout = Holders.simple(100); + + public String getClientId() { + return clientId.get(); + } + + public void setClientId(String url) { + this.clientId.set(url); + } + + public String getSecret() { + return secret.get(); + } + + public void setSecret(String url) { + this.secret.set(url); + } + + public String getPrivatekey() { + return privatekey.get(); + } + + public void setPrivatekey(String url) { + this.privatekey.set(url); + } + + public Integer getTimeout() { + return timeout.get(); + } + + public void setTimeout(Integer url) { + this.timeout.set(url); + } + + @Override + public Object clone() throws CloneNotSupportedException { + PluginSimpleConfig cloned = (PluginSimpleConfig) super.clone(); +// cloned.text = (Conf) text.clone(); +// cloned.count = (Conf) count.clone(); +// cloned.price = (Conf) price.clone(); +// cloned.time = (Conf) time.clone(); +// cloned.student = (Conf) student.clone(); + return cloned; + } + +} diff --git a/src/main/java/com/eco/plugin/xx/zcgjsync/controller/ControllerRegisterProvider.java b/src/main/java/com/eco/plugin/xx/zcgjsync/controller/ControllerRegisterProvider.java new file mode 100644 index 0000000..6d3e534 --- /dev/null +++ b/src/main/java/com/eco/plugin/xx/zcgjsync/controller/ControllerRegisterProvider.java @@ -0,0 +1,20 @@ +package com.eco.plugin.xx.zcgjsync.controller; + +import com.fr.decision.fun.impl.AbstractControllerRegisterProvider; +import com.fr.plugin.context.PluginContexts; +import com.fr.stable.fun.Authorize; + +@Authorize(callSignKey = "com.eco.plugin.xx.zcgjsync") +public class ControllerRegisterProvider extends AbstractControllerRegisterProvider { + @Override + public Class[] getControllers() { + + if(!PluginContexts.currentContext().isAvailable()) { + return new Class[]{}; + } + + return new Class[]{ + ControllerSelf.class + }; + } +} diff --git a/src/main/java/com/eco/plugin/xx/zcgjsync/controller/ControllerSelf.java b/src/main/java/com/eco/plugin/xx/zcgjsync/controller/ControllerSelf.java new file mode 100644 index 0000000..5df9a34 --- /dev/null +++ b/src/main/java/com/eco/plugin/xx/zcgjsync/controller/ControllerSelf.java @@ -0,0 +1,39 @@ +package com.eco.plugin.xx.zcgjsync.controller; + +import com.eco.plugin.xx.zcgjsync.utils.*; +import com.fr.decision.webservice.annotation.LoginStatusChecker; +import com.fr.third.springframework.stereotype.Controller; +import com.fr.third.springframework.web.bind.annotation.PostMapping; +import com.fr.third.springframework.web.bind.annotation.ResponseBody; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +@Controller +@LoginStatusChecker(required = false) +public class ControllerSelf { + + @PostMapping(value = "/syncOrg") + @ResponseBody + public void syncOrg(HttpServletRequest req,HttpServletResponse res){ + String param = Utils.getRequestBodyText(req); + String token = req.getHeader("token"); + String result = OrgUtils.operOrg(param,token); + + FRUtils.FRLogInfo("org xml:"+param+"\ntoken:"+token); + + ResponseUtils.responseText(res,result); + } + + @PostMapping(value = "/syncUser") + @ResponseBody + public void syncUser(HttpServletRequest req,HttpServletResponse res){ + String param = Utils.getRequestBodyText(req); + String token = req.getHeader("token"); + String result = UserUtils.operUser(param,token); + + FRUtils.FRLogInfo("user xml:"+param+"\ntoken:"+token); + + ResponseUtils.responseText(res,result); + } +} diff --git a/src/main/java/com/eco/plugin/xx/zcgjsync/kit/DepartmentServiceKit.java b/src/main/java/com/eco/plugin/xx/zcgjsync/kit/DepartmentServiceKit.java new file mode 100644 index 0000000..137c2da --- /dev/null +++ b/src/main/java/com/eco/plugin/xx/zcgjsync/kit/DepartmentServiceKit.java @@ -0,0 +1,108 @@ + /* + * Copyright (C), 2018-2021 + * Project: starter + * FileName: DepartmentServiceKit + * Author: xx + * Date: 2021/5/14 9:38 + */ + package com.eco.plugin.xx.zcgjsync.kit; + + import com.eco.plugin.xx.zcgjsync.utils.Utils; + import com.fr.decision.authority.AuthorityContext; + import com.fr.decision.authority.base.constant.type.operation.ManualOperationType; + import com.fr.decision.authority.data.Department; + import com.fr.decision.webservice.exception.general.DuplicatedNameException; + import com.fr.decision.webservice.v10.user.DepartmentService; + import com.fr.general.ComparatorUtils; + import com.fr.stable.StableUtils; + import com.fr.stable.query.QueryFactory; + import com.fr.stable.query.condition.QueryCondition; + import com.fr.stable.query.restriction.Restriction; + import com.fr.stable.query.restriction.RestrictionFactory; + import java.util.ArrayList; + import java.util.Collections; + import java.util.List; + + /** + *
+ * + * + * @author xx + * @since 1.0.0 + */ + public class DepartmentServiceKit extends DepartmentService { + public static final String DECISION_DEP_ROOT = "decision-dep-root"; + private static volatile DepartmentServiceKit departmentServiceKit = null; + + public DepartmentServiceKit() { + } + + public static DepartmentServiceKit getInstance() { + if (departmentServiceKit == null) { + departmentServiceKit = new DepartmentServiceKit(); + } + return departmentServiceKit; + } + + /** + * 根据id获取部门 + * @param id + * @return + * @throws Exception + */ + public Department getByid(String id) throws Exception { + return AuthorityContext.getInstance().getDepartmentController().getById(id); + } + + /** + * 添加部门 + * @param id + * @param pId + * @param depName + * @return + * @throws Exception + */ + public Department addDepartment(String id, String pId, String depName) throws Exception { + if ((Utils.isNotNullStr(pId) && pId.equals(DECISION_DEP_ROOT)) || Utils.isNullStr(pId)) { + pId = null; + } + this.checkDuplicatedDepartmentName(pId, depName); + Department department = (new Department()).id(id).name(depName).parentId(pId).creationType(ManualOperationType.KEY).lastOperationType(ManualOperationType.KEY).enable(true); + AuthorityContext.getInstance().getDepartmentController().add(department); + return department; + } + + private void checkDuplicatedDepartmentName(String parentId, String depName) throws Exception { + QueryCondition condition = QueryFactory.create().addRestriction(RestrictionFactory.and(new Restriction[]{RestrictionFactory.eq("name", depName), RestrictionFactory.eq("parentId", parentId)})); + Department sameNameDep = AuthorityContext.getInstance().getDepartmentController().findOne(condition); + if (sameNameDep != null) { + throw new DuplicatedNameException(); + } + } + + private String getDepartmentFullPath(String pId, String depName, String splitter) throws Exception { + List paths = new ArrayList<>(); + paths.add(depName); + while (!ComparatorUtils.equals(pId, DECISION_DEP_ROOT) && pId != null) { + Department parentDepartment = AuthorityContext.getInstance().getDepartmentController().getById(pId); + paths.add(parentDepartment.getName()); + pId = parentDepartment.getParentId(); + } + Collections.reverse(paths); + return StableUtils.join(paths.toArray(new String[0]), splitter); + } + + public void editDepartment(String departmentId, String depName, String pId) throws Exception { + if (Utils.isNotNullStr(pId) && pId.equals(DECISION_DEP_ROOT)) { + pId = null; + } + Department department = AuthorityContext.getInstance().getDepartmentController().getById(departmentId); + String departmentFullPath = DepartmentService.getInstance().getDepartmentFullPath(departmentId); + if (!ComparatorUtils.equals(department.getName(), depName)) { + this.checkDuplicatedDepartmentName(department.getParentId(), depName); + department.setName(depName); + department.setParentId(pId); + AuthorityContext.getInstance().getDepartmentController().update(department); + } + } + } \ No newline at end of file diff --git a/src/main/java/com/eco/plugin/xx/zcgjsync/kit/I18nKit.java b/src/main/java/com/eco/plugin/xx/zcgjsync/kit/I18nKit.java new file mode 100644 index 0000000..a3c9f5a --- /dev/null +++ b/src/main/java/com/eco/plugin/xx/zcgjsync/kit/I18nKit.java @@ -0,0 +1,23 @@ +package com.eco.plugin.xx.zcgjsync.kit; + +import com.fr.locale.InterProviderFactory; + +import java.util.Locale; +import java.util.Map; + +public class I18nKit { + public I18nKit() { + } + + public static String getLocText(String string) { + return InterProviderFactory.getProvider().getLocText(string); + } + + public static String getLocText(String string, String... args) { + return InterProviderFactory.getProvider().getLocText(string, args); + } + + public static Map getEntireKV(Locale locale) { + return InterProviderFactory.getClientProvider().getEntireKV(locale); + } +} \ No newline at end of file diff --git a/src/main/java/com/eco/plugin/xx/zcgjsync/kit/UserServiceKit.java b/src/main/java/com/eco/plugin/xx/zcgjsync/kit/UserServiceKit.java new file mode 100644 index 0000000..70e313c --- /dev/null +++ b/src/main/java/com/eco/plugin/xx/zcgjsync/kit/UserServiceKit.java @@ -0,0 +1,100 @@ +package com.eco.plugin.xx.zcgjsync.kit; + +import com.eco.plugin.xx.zcgjsync.utils.FRUtils; +import com.eco.plugin.xx.zcgjsync.utils.Utils; +import com.fr.decision.authority.AuthorityContext; +import com.fr.decision.authority.base.constant.SoftRoleType; +import com.fr.decision.authority.base.constant.type.operation.ManualOperationType; +import com.fr.decision.authority.data.User; +import com.fr.decision.base.util.UUIDUtil; +import com.fr.decision.privilege.encrpt.PasswordValidator; +import com.fr.decision.webservice.bean.user.UserBean; +import com.fr.decision.webservice.exception.general.DuplicatedNameException; +import com.fr.decision.webservice.exception.general.SpecialCharProhibitException; +import com.fr.decision.webservice.exception.login.UserPasswordCanNotEmptyException; +import com.fr.decision.webservice.utils.CharLimitType; +import com.fr.decision.webservice.utils.UserSourceFactory; +import com.fr.decision.webservice.utils.WebServiceUtils; +import com.fr.decision.webservice.v10.user.UserService; +import com.fr.stable.StringUtils; +import com.fr.stable.query.QueryFactory; +import com.fr.stable.query.condition.QueryCondition; +import com.fr.stable.query.restriction.Restriction; +import com.fr.stable.query.restriction.RestrictionFactory; + +public class UserServiceKit extends UserService { + private static volatile UserServiceKit userServiceKit = null; + + public UserServiceKit() { + } + + public static UserServiceKit getInstance() { + if (userServiceKit == null) { + userServiceKit = new UserServiceKit(); + } + return userServiceKit; + } + + public void editUser(UserBean userBean, String var2) throws Exception { + this.editUserInfo(userBean); + if (userBean.isResetPassword()) { + this.resetPassword(userBean); + } + +// this.updateUserRoles(var2, userBean); +// this.updateUserDepartmentPost(var2, userBean); + } + + /** + * 添加用户 + * @param userBean + * @throws Exception + */ + public void addUser(UserBean userBean) throws Exception { + if (StringUtils.isEmpty(userBean.getPassword())) { + throw new UserPasswordCanNotEmptyException(); + } else { + String username = userBean.getUsername(); + String mobile = Utils.replaceNullStr(userBean.getMobile(),""); + String email = Utils.replaceNullStr(userBean.getEmail(),""); + String id = userBean.getId(); + String psd = userBean.getPassword(); + this.checkUsernameLegal(username, CharLimitType.USER_LIMIT); +// this.checkNonRequiredField(mobile, CharLimitType.MOBILE_LIMIT); +// this.checkNonRequiredField(email, CharLimitType.EMAIL_LIMIT); + this.checkDuplicatedUser(username); + String salt = UUIDUtil.generate(); + PasswordValidator var8 = UserSourceFactory.getInstance().getUserSource(ManualOperationType.KEY).getPasswordValidator(); + User user = (new User()).userName(username).realName(userBean.getRealName()).password(var8.encode(username, psd, salt)).salt(salt).email(userBean.getEmail()).mobile(userBean.getMobile()).creationType(ManualOperationType.KEY).lastOperationType(ManualOperationType.KEY).enable(true).id(id); + FRUtils.FRLogInfo(user.toString()); + AuthorityContext.getInstance().getUserController().add(user); + this.deleteSoftData(user.getUserName()); + } + } + + private void checkUsernameLegal(String var1, CharLimitType var2) throws SpecialCharProhibitException { + if (WebServiceUtils.containSQLChars(var1) || WebServiceUtils.containIllegalChars(var2, var1)) { + throw new SpecialCharProhibitException(); + } + } + + private void checkNonRequiredField(String var1, CharLimitType var2) { + if (StringUtils.isNotEmpty(var1) && WebServiceUtils.containIllegalChars(var2, var1)) { + throw new SpecialCharProhibitException(); + } + } + + private void checkDuplicatedUser(String var1) throws Exception { + User var2 = this.getUserByUserName(var1); + if (var2 != null) { + throw new DuplicatedNameException("Duplicated names! ", var1); + } + } + + private void deleteSoftData(String var1) throws Exception { + QueryCondition var2 = QueryFactory.create().addRestriction(RestrictionFactory.and(new Restriction[]{RestrictionFactory.eq("deletedName", var1), RestrictionFactory.eq("type", SoftRoleType.USER)})); + AuthorityContext.getInstance().getSoftDataController().remove(var2); + } + + +} diff --git a/src/main/java/com/eco/plugin/xx/zcgjsync/utils/AuthUtils.java b/src/main/java/com/eco/plugin/xx/zcgjsync/utils/AuthUtils.java new file mode 100644 index 0000000..1cae2be --- /dev/null +++ b/src/main/java/com/eco/plugin/xx/zcgjsync/utils/AuthUtils.java @@ -0,0 +1,47 @@ +package com.eco.plugin.xx.zcgjsync.utils; + +import com.eco.plugin.xx.zcgjsync.config.PluginSimpleConfig; + +/** + * 鉴权类 + */ +public class AuthUtils { + + /** + * 鉴权 + * @param token + * @param now + * @param psc + * @throws Exception + */ + public static void auth(String token,Long now,PluginSimpleConfig psc) throws Exception { + String privateKey = psc.getPrivatekey(); + String plaintext = EncryptUtils.rsaDecrypt(token,privateKey); + String[] plainArray = plaintext.split("_"); + String appid = plainArray[0]; + String appKey = plainArray[1]; + Long timestamp = Long.parseLong(plainArray[2]); + + timeout(timestamp,now,psc); + + if(!appid.equals(psc.getClientId()) || !appKey.equals(psc.getSecret())){ + throw new Exception("非法的应用"); + } + } + + /** + * 判断token是否超时 + * @param timestatmp + * @param now + * @param psc + * @throws Exception + */ + private static void timeout(Long timestatmp, Long now, PluginSimpleConfig psc) throws Exception { + Long timediff = (now - timestatmp) /1000; + + //超时 + if(timediff > psc.getTimeout().intValue()){ + throw new Exception("token 超时"); + } + } +} diff --git a/src/main/java/com/eco/plugin/xx/zcgjsync/utils/EncryptUtils.java b/src/main/java/com/eco/plugin/xx/zcgjsync/utils/EncryptUtils.java new file mode 100644 index 0000000..605b6b6 --- /dev/null +++ b/src/main/java/com/eco/plugin/xx/zcgjsync/utils/EncryptUtils.java @@ -0,0 +1,332 @@ +package com.eco.plugin.xx.zcgjsync.utils; + +import com.fr.log.FineLoggerFactory; +import sun.misc.BASE64Decoder; +import sun.misc.BASE64Encoder; + +import javax.crypto.Cipher; +import javax.crypto.KeyGenerator; +import javax.crypto.SecretKey; +import javax.crypto.SecretKeyFactory; +import javax.crypto.spec.DESKeySpec; +import java.io.IOException; +import java.security.*; +import java.security.interfaces.RSAPrivateKey; +import java.security.interfaces.RSAPublicKey; +import java.security.spec.PKCS8EncodedKeySpec; +import java.security.spec.X509EncodedKeySpec; +import java.util.HashMap; +import java.util.Map; + +public class EncryptUtils { + + /** + * sha 加密 + * @param str + * @return + */ + public static String sha(String str){ + String sha256Str = ""; + + try { + MessageDigest sha256Deget = MessageDigest.getInstance("SHA-256"); + byte[] sha256Encode = sha256Deget.digest(str.getBytes()); + sha256Str = ByteToHexStr(sha256Encode); + }catch (Exception e){ + FineLoggerFactory.getLogger().info("FRLOG:SHA256加密异常:"+e.getMessage()); + } + + return sha256Str; + } + + /** + * byte数组转16进制字符串 + * @param bytes + * @return + */ + private static String ByteToHexStr(byte[] bytes) + { + String hexStr = ""; + + for(int i =0;i= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') + || c == '+' || c == '/' || c == '=') { + continue; + } + else { + return false; + } + } + + return true; + } + } + + /** + * des加密 + * @param datasource + * @param password + * @return + */ + public static String desEncrypt(String datasource, String password) { + try { + SecureRandom random = new SecureRandom(); + DESKeySpec desKey = new DESKeySpec(password.getBytes()); + // 创建一个密匙工厂,然后用它把DESKeySpec转换成 + SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); + SecretKey securekey = keyFactory.generateSecret(desKey); + // Cipher对象实际完成加密操作 + Cipher cipher = Cipher.getInstance("DES"); + // 用密匙初始化Cipher对象 + cipher.init(Cipher.ENCRYPT_MODE, securekey, random); + // 现在,获取数据并加密 + // 正式执行加密操作 + return base64Encode(cipher.doFinal(datasource.getBytes())); + } catch (Throwable e) { + FRUtils.FRLogInfo("des 加密异常 " + e.getMessage()); + } + + return null; + } + + /** + * des 解密 + * @param src + * @param password + * @return + * @throws Exception + */ + public static String desDecrypt(String src, String password) throws Exception { + // DES算法要求有一个可信任的随机数源 + SecureRandom random = new SecureRandom(); + // 创建一个DESKeySpec对象 + DESKeySpec desKey = new DESKeySpec(password.getBytes("UTF-8")); + // 创建一个密匙工厂 + SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); + // 将DESKeySpec对象转换成SecretKey对象 + SecretKey securekey = keyFactory.generateSecret(desKey); + // Cipher对象实际完成解密操作 + Cipher cipher = Cipher.getInstance("DES"); + // 用密匙初始化Cipher对象 + cipher.init(Cipher.DECRYPT_MODE, securekey, random); + // 真正开始解密操作 + return new String(cipher.doFinal(base64DecodeB(src))); + } + + /** + * 随机生成RSA密钥对 + * @throws NoSuchAlgorithmException + * @return privateKey,publicKey + */ + public static Map genRSAKeyPair() throws NoSuchAlgorithmException { + // KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象 + KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA"); + // 初始化密钥对生成器,密钥大小为96-1024位 + keyPairGen.initialize(1024,new SecureRandom()); + // 生成一个密钥对,保存在keyPair中 + KeyPair keyPair = keyPairGen.generateKeyPair(); + RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); // 得到私钥 + RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); // 得到公钥 + String publicKeyString = base64Encode(publicKey.getEncoded()); + // 得到私钥字符串 + String privateKeyString = base64Encode(privateKey.getEncoded()); + // 将公钥和私钥保存到Map + Map result = new HashMap(); + result.put("publicKey",publicKeyString.replaceAll("\n","").replace("\r","").trim()); + result.put("privateKey",privateKeyString.replaceAll("\n","").replace("\r","").trim()); + + return result; + } + + /** + * rsa 加密 + * @param str + * @param publicKey + * @return + * @throws Exception + */ + public static String rsaEncrypt(String str,String publicKey) throws Exception { + //base64编码的公钥 + byte[] decoded = base64DecodeB(publicKey); + RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded)); + //RSA加密 + Cipher cipher = Cipher.getInstance("RSA"); + cipher.init(Cipher.ENCRYPT_MODE, pubKey); + String outStr = base64Encode(cipher.doFinal(str.getBytes("UTF-8"))).replaceAll("\n","").replace("\r","").trim(); + return outStr; + } + + /** + * rsa解密 + * @param str + * @param privateKey + * @return + * @throws Exception + */ + public static String rsaDecrypt(String str,String privateKey) throws Exception { + //64位解码加密后的字符串 + byte[] inputByte = base64DecodeB(str); + //base64编码的私钥 + byte[] decoded = base64DecodeB(privateKey); + RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded)); + //RSA解密 + Cipher cipher = Cipher.getInstance("RSA"); + cipher.init(Cipher.DECRYPT_MODE, priKey); + String outStr = new String(cipher.doFinal(inputByte)); + return outStr; + } + + +} diff --git a/src/main/java/com/eco/plugin/xx/zcgjsync/utils/FRUserUtils.java b/src/main/java/com/eco/plugin/xx/zcgjsync/utils/FRUserUtils.java new file mode 100644 index 0000000..ca8b892 --- /dev/null +++ b/src/main/java/com/eco/plugin/xx/zcgjsync/utils/FRUserUtils.java @@ -0,0 +1,248 @@ +package com.eco.plugin.xx.zcgjsync.utils; + +import com.fr.decision.authority.AuthorityContext; +import com.fr.decision.authority.controller.DepartmentController; +import com.fr.decision.authority.controller.UserController; +import com.fr.decision.authority.data.Department; +import com.fr.decision.authority.data.User; +import com.fr.decision.privilege.TransmissionTool; +import com.fr.decision.webservice.bean.user.*; +import com.fr.decision.webservice.v10.login.ExtendTokenProcessor; +import com.fr.decision.webservice.v10.login.LoginService; +import com.fr.decision.webservice.v10.user.UserService; +import com.fr.stable.query.QueryFactory; + +import javax.servlet.http.HttpServletRequest; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +public class FRUserUtils { + + /** + * 获取用户Service + * @return + */ + public static UserService getUserService(){ + return UserService.getInstance(); + } + + /** + * 获取全量用户 + * @return + * @throws Exception + */ + public static List getAllUsers() throws Exception { +// List userbean = UserMiddleRoleService.getInstance().getAllUsers(false); + List users = new ArrayList(); + getAllUser(getAdminUser().getUsername(),0,1000,users); + return users; + } + + /** + * + * @param adminUsername 管理员用户名 + * @param page 页数 + * @param num 每页的数据 + * @param users 保存用户的列表 + */ + private static void getAllUser(String adminUsername,int page,int num,List users) throws Exception { + Map result = getUserService().getAllUsers(adminUsername,page,num,"","",true); + Long total = (Long)result.get("total"); + List item = (List)result.get("items"); + users.addAll(item); + + page = page+1; + + if(page * num >= total){ + return ; + } + + getAllUser(adminUsername,page,num,users); + } + /** + * 添加用户 + * @param userBean + */ + public static void addUser(UserBean userBean) throws Exception { + userBean.setPassword(TransmissionTool.defaultEncrypt(userBean.getPassword())); + getUserService().addUser(userBean); + } + + /** + * 删除用户 + * @param userBean + */ + public static void updateUser(User userBean) throws Exception { + UserController userController = AuthorityContext.getInstance().getUserController(); + userController.update(userBean); +// UserServiceKit.getInstance().editUser(userBean,getAdminUser().getId()); + } + + /** + * 删除用户 + * @param user + * @return + */ + public static int deleteUser(User user) throws Exception { + String userId = user.getId(); + + UserUpdateBean userUpdateBean = new UserUpdateBean(); + userUpdateBean.setRemoveUserIds(new String[]{userId}); + + return getUserService().deleteUsers(userUpdateBean); + } + + /** + * 根据用户名获取用户实体 + * @param userName + * @return + */ + public static User getUserByUserName(String userName) throws Exception { + return getUserService().getUserByUserName(userName); + } + + /** + * 根据用户名获取用户实体 + * @param userName + * @return + */ + public static UserBean getUserBeanByUserName(String userName ) throws Exception { + String id = getUserService().getUserByUserName(userName).getId(); + return getUser(id); + } + + /** + * 根据id获取用户 + * @param id + * @return + * @throws Exception + */ + public static UserBean getUser(String id) throws Exception { + return getUserService().getUser(id); + } + + /** + * 判断是否是管理员 + * @param username + * @return + */ + public static boolean isAdmin(String username) throws Exception{ + return getUserService().isAdmin(getUserByUserName(username).getId()); + } + + /** + * 禁用启用用户 + * @param userId + * @param state false 禁用 true 启用 + * @throws Exception 异常说明失败 + */ + public static void forbidUser(String userId,boolean state) throws Exception { + getUserService().forbidUser(userId,state); + } + + /** + * 修改用户部门 + * @param departmentId + * @param postId +// * @param ud + * @throws Exception + */ + public static void updateDepartmentPostUsers(String departmentId, String postId, String userid) throws Exception { + AuthorityContext.getInstance().getUserController().addUserToDepartmentAndPost(userid, departmentId, postId); +// getUserService().updateDepartmentPostUsers(departmentId,postId,ud); + } + + +// /** +// * 验证密码是否正确 +// * @param psd 明文密码 +// * @param user 根据用户名获取得用户对象 +// * @return +// */ +// public static boolean checkPsd(String psd,User user){ +// String shaPsd = CipherUtils.jdksha256(psd); +// +// return shaPsd.equals(user.getPassword()); +// } + public static User getCurrentUser(HttpServletRequest req) throws Exception { + String username = LoginService.getInstance().getCurrentUserNameFromRequestCookie(req); + + if(Utils.isNullStr(username)){ + return null; + } + + return getUserByUserName(username); + } + + public static UserBean getCurrentUserBean(HttpServletRequest req) throws Exception { + String username = LoginService.getInstance().getCurrentUserNameFromRequestCookie(req); + + if(Utils.isNullStr(username)){ + return null; + } + + return getUserBeanByUserName(username); + } + + /** + * 获取用户部门角色 + * @param username + * @return + * @throws Exception + */ + private static UserRolesBean getUserRolesBean(String username) throws Exception { + return FRUserUtils.getUserService().getUserDepAndCustomRoles(username); + } + + /** + * 获取部门职务 + * @param username + * @return + * @throws Exception + */ + public static List getDepRoleBean(String username) throws Exception{ + return getUserRolesBean(username).getDepRoles(); + } + + /** + * 获取角色 + * @param username + * @return + * @throws Exception + */ + public static List getCustomRoles(String username) throws Exception{ + return getUserRolesBean(username).getCustomRoles(); + } + + public static UserBean getAdminUser() throws Exception { + String adminid = getUserService().getAdminUserIdList().get(0); + return getUser(adminid); + } + + public static String getUsernameFromToken(String token){ + String username = ExtendTokenProcessor.KEY.getUsername(token); + return username; + } + + /** + * 清除用户的机构和职务 + * @param userid + * @throws Exception + */ + public static void clearUserDepAndPost(String userid) throws Exception { + DepartmentController departmentController = AuthorityContext.getInstance().getDepartmentController(); +// PostController postController = AuthorityContext.getInstance().getPostController(); + List departments = departmentController.findByUser(userid, QueryFactory.create()); +// List postBeanList = postController.findByUser(userid, QueryFactory.create()); + UserController userController = AuthorityContext.getInstance().getUserController(); +// +// for(Post post : postBeanList){ +// List departments = departmentController.findByPost(post.getId(),QueryFactory.create()); + for(Department department:departments){ + userController.removeUserFromDepartmentAndPost(userid, department.getId(), ""); + } +// } + } + +} diff --git a/src/main/java/com/eco/plugin/xx/zcgjsync/utils/FRUtils.java b/src/main/java/com/eco/plugin/xx/zcgjsync/utils/FRUtils.java new file mode 100644 index 0000000..6da6911 --- /dev/null +++ b/src/main/java/com/eco/plugin/xx/zcgjsync/utils/FRUtils.java @@ -0,0 +1,332 @@ +package com.eco.plugin.xx.zcgjsync.utils; + +import com.fr.base.ServerConfig; +import com.fr.base.TableData; +import com.fr.base.TemplateUtils; +import com.fr.decision.authority.AuthorityContext; +import com.fr.decision.authority.base.constant.type.operation.ManualOperationType; +import com.fr.decision.authority.data.User; +import com.fr.decision.base.util.UUIDUtil; +import com.fr.decision.privilege.encrpt.PasswordValidator; +import com.fr.decision.webservice.bean.authentication.OriginUrlResponseBean; +import com.fr.decision.webservice.interceptor.handler.ReportTemplateRequestChecker; +import com.fr.decision.webservice.login.LogInOutResultInfo; +import com.fr.decision.webservice.utils.DecisionServiceConstants; +import com.fr.decision.webservice.utils.DecisionStatusService; +import com.fr.decision.webservice.utils.UserSourceFactory; +import com.fr.decision.webservice.v10.login.LoginService; +import com.fr.decision.webservice.v10.login.event.LogInOutEvent; +import com.fr.decision.webservice.v10.user.UserService; +import com.fr.event.EventDispatcher; +import com.fr.file.TableDataConfig; +import com.fr.general.data.DataModel; +import com.fr.log.FineLoggerFactory; +import com.fr.script.Calculator; +import com.fr.stable.StringUtils; +import com.fr.stable.query.QueryFactory; +import com.fr.stable.query.restriction.RestrictionFactory; +import com.fr.third.springframework.web.method.HandlerMethod; +import com.fr.web.controller.ReportRequestService; +import com.fr.web.utils.WebUtils; + +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; +import java.io.IOException; +import java.util.List; + +public class FRUtils { + /** + * 判断用户是否存在 + * @param userName + * @return + */ + public static boolean isUserExist(String userName){ + if (StringUtils.isEmpty(userName)) { + return false; + } else { + try { + List userList = AuthorityContext.getInstance().getUserController().find(QueryFactory.create().addRestriction(RestrictionFactory.eq("userName", userName))); + return userList != null && !userList.isEmpty(); + } catch (Exception e) { + FineLoggerFactory.getLogger().error(e.getMessage()); + return false; + } + } + } + + /** + * 判断是否登录FR + * @param req + * @return + */ + public static boolean isLogin(HttpServletRequest req){ + return LoginService.getInstance().isLogged(req); + } + + /** + * 帆软登录 + * @param httpServletRequest + * @param httpServletResponse + * @param userName + * @param url + */ + public static void login(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse,String userName,String url){ + + FineLoggerFactory.getLogger().info("FRLOG:用户名:"+userName); + FineLoggerFactory.getLogger().info("FRLOG:跳转链接:"+url); + + + //判断用户名是否为空 + if(!Utils.isNullStr(userName)){ + if(isUserExist(userName)){ + String FRToken = ""; + + try { + //HttpSession session = httpServletRequest.getSession(true); + + FRToken = LoginService.getInstance().login(httpServletRequest, httpServletResponse, userName); + + //httpServletRequest.setAttribute(DecisionServiceConstants.FINE_AUTH_TOKEN_NAME,FRToken); + + //session.setAttribute(DecisionServiceConstants.FINE_AUTH_TOKEN_NAME, FRToken); + EventDispatcher.fire(LogInOutEvent.LOGIN,new LogInOutResultInfo(httpServletRequest,httpServletResponse,userName,true)); + FineLoggerFactory.getLogger().info("FRLOG:登陆成功!"); + + if(!Utils.isNullStr(url)){ + httpServletResponse.sendRedirect(url); + } + } catch (Exception e) { + ResponseUtils.failedResponse(httpServletResponse,"登录异常,请联系管理员!"); + FineLoggerFactory.getLogger().info("FRLOG:登录异常,请联系管理员!"); + FineLoggerFactory.getLogger().info("FRLOGException:"+e.getMessage()); + } + }else{ + ResponseUtils.failedResponse(httpServletResponse,"用户在报表系统中不存在!"); + FineLoggerFactory.getLogger().info("FRLOG:用户在报表系统中不存在!"); + } + }else{ + ResponseUtils.failedResponse(httpServletResponse,"用户名不能为空!"); + FineLoggerFactory.getLogger().info("FRLOG:用户名不能为空!"); + } + } + + /** + * 帆软登录 + * @param httpServletRequest + * @param httpServletResponse + * @param token + * @param url + */ + public static void loginByToken(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse,String token,String url){ + + FineLoggerFactory.getLogger().info("FRLOG:token:"+token); + FineLoggerFactory.getLogger().info("FRLOG:跳转链接:"+url); + + + //判断用户名是否为空 + if(!Utils.isNullStr(token)){ + writeToken2Cookie(httpServletResponse,token,-1); + + HttpSession session = httpServletRequest.getSession(true); + + httpServletRequest.setAttribute(DecisionServiceConstants.FINE_AUTH_TOKEN_NAME,token); + + session.setAttribute(DecisionServiceConstants.FINE_AUTH_TOKEN_NAME, token); + + if(!Utils.isNullStr(url)){ + try { + httpServletResponse.sendRedirect(url); + } catch (IOException e) { + ResponseUtils.failedResponse(httpServletResponse,"跳转异常!"); + FineLoggerFactory.getLogger().info("FRLOG:跳转异常!"); + } + } + }else{ + ResponseUtils.failedResponse(httpServletResponse,"token不能为空!"); + FineLoggerFactory.getLogger().info("FRLOG:token不能为空!"); + } + } + + /** + * 获取token + * @param httpServletRequest + * @param httpServletResponse + * @param username + * @return + */ + public static String getToken(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse,String username){ + String token = ""; + try { + token = LoginService.getInstance().login(httpServletRequest, httpServletResponse, username); + } catch (Exception e) { + FineLoggerFactory.getLogger().info("FRLOG:获取token失败"+e.getMessage()); + } + + return token; + } + + private static void writeToken2Cookie(HttpServletResponse req, String token, int num) { + try { + if (StringUtils.isNotEmpty(token)) { + Cookie cookie = new Cookie("fine_auth_token", token); + long maxAge = num == -2 ? 1209600000L : (long)num; + cookie.setMaxAge((int)maxAge); + cookie.setPath(ServerConfig.getInstance().getCookiePath()); + req.addCookie(cookie); + Cookie rememberCookie = new Cookie("fine_remember_login", String.valueOf(num == -2 ? -2 : -1)); + rememberCookie.setMaxAge((int)maxAge); + rememberCookie.setPath(ServerConfig.getInstance().getCookiePath()); + req.addCookie(rememberCookie); + } else { + FineLoggerFactory.getLogger().error("empty token cannot save."); + } + } catch (Exception e) { + FineLoggerFactory.getLogger().error(e.getMessage(), e); + } + + } + + /** + * 后台登出 + * @param httpServletRequest + * @param httpServletResponse + */ + public static void logoutByToken(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse,String token) + { + httpServletRequest.setAttribute("fine_auth_token",token); + logout(httpServletRequest,httpServletResponse); + } + + /** + * + * @param httpServletRequest + * @param httpServletResponse + */ + public static void logout(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse) + { + if(!isLogin(httpServletRequest)){ + return ; + } + + try { + LoginService.getInstance().logout(httpServletRequest,httpServletResponse); + } catch (Exception e) { + ResponseUtils.failedResponse(httpServletResponse,"登出异常,请联系管理员!"); + FineLoggerFactory.getLogger().info("FRLOG:登出异常,请联系管理员!"); + FineLoggerFactory.getLogger().info("FRLOGException:"+e.getMessage()); + } + } + + /** + * 打印FR日志 + * @param message + */ + public static void FRLogInfo(String message){ + FineLoggerFactory.getLogger().info("FRLOG:"+message); + } + + /** + * 打印FR日志-error + * @param message + */ + public static void FRLogError(String message){ + FineLoggerFactory.getLogger().error("FRLOG:"+message); + } + + + /** + * 根据用户名获取用户信息 + * @param userName + * @return + */ + public static User getFRUserByUserName(String userName){ + try { + return UserService.getInstance().getUserByUserName(userName); + } catch (Exception e) { + FRLogInfo("获取用户信息异常:"+e.getMessage()); + } + + return null; + } + + /** + * 解密FR密码 + * @param password + * @return + */ +// public static String decryptFRPsd(String password){ +// FRLogInfo("解密密码:"+password); +// return TransmissionTool.decrypt(password); +// } + + /** + * 根据明文密码生成数据库中的密码,用户密码校验用 + * @return + */ + public static String getDBPsd(String username,String password){ + PasswordValidator pv = UserSourceFactory.getInstance().getUserSource(ManualOperationType.KEY).getPasswordValidator(); + String uuid = UUIDUtil.generate(); + + return pv.encode(username, password, uuid); + } + + /** + * 获取带参数的访问链接 + * @return + */ + public static String getAllUrl(HttpServletRequest httpServletRequest){ + return WebUtils.getOriginalURL(httpServletRequest); + } + + /** + * 根据originKey获取源链接 + * @param req + * @return + * @throws Exception + */ + public static String getOriginUrl(HttpServletRequest req) throws Exception { + String origin = req.getParameter("origin"); + if (StringUtils.isNotEmpty(origin)) { + OriginUrlResponseBean originUrlResponseBean = (OriginUrlResponseBean) DecisionStatusService.originUrlStatusService().get(origin); + DecisionStatusService.originUrlStatusService().delete(origin); + if (originUrlResponseBean != null) { + return originUrlResponseBean.getOriginUrl(); + } + } + + return new OriginUrlResponseBean(TemplateUtils.render("${fineServletURL}")).getOriginUrl(); + } + + /** + * 判断是否开启模板认证 + * @param + * @return + * @throws Exception + */ + public static boolean isTempAuth(HttpServletRequest req,HttpServletResponse res) throws Exception { + ReportTemplateRequestChecker checker = new ReportTemplateRequestChecker(); + HandlerMethod hm = new HandlerMethod(new ReportRequestService(),ReportRequestService.class.getMethod("preview", HttpServletRequest.class, HttpServletResponse.class, String.class)); + return checker.checkRequest(req,res,hm); + } + + /** + * 获取数据集数据 + * @param serverDataSetName + * @return + */ + public static DataModel getTableData(String serverDataSetName){ + TableData userInfo = TableDataConfig.getInstance().getTableData(serverDataSetName); + DataModel userInfoDM = userInfo.createDataModel(Calculator.createCalculator()); +// userInfoDM.getRowCount(); +// userInfoDM.getColumnIndex(); +// userInfoDM.getValueAt() + return userInfoDM; + } + + public static String getIndex(HttpServletRequest req){ + String url = req.getScheme()+"://"+req.getServerName()+":"+String.valueOf(req.getServerPort())+req.getRequestURI(); + return url; + } +} diff --git a/src/main/java/com/eco/plugin/xx/zcgjsync/utils/OrgUtils.java b/src/main/java/com/eco/plugin/xx/zcgjsync/utils/OrgUtils.java new file mode 100644 index 0000000..ad8f5e9 --- /dev/null +++ b/src/main/java/com/eco/plugin/xx/zcgjsync/utils/OrgUtils.java @@ -0,0 +1,172 @@ +package com.eco.plugin.xx.zcgjsync.utils; + +import com.eco.plugin.xx.zcgjsync.bean.OrgBean; +import com.eco.plugin.xx.zcgjsync.config.PluginSimpleConfig; +import com.eco.plugin.xx.zcgjsync.kit.DepartmentServiceKit; +import com.fr.decision.authority.data.Department; + +/** + * 机构操作类 + */ +public class OrgUtils { + private static String success = "S"; + private static String fail = "F"; + private static String duplicate = "添加机构失败,已存在相同的机构名称"; + private static String unknown = "未知异常"; + private static String successMsg = "操作成功"; + private static String notExist = "您操作的机构不存在"; + private static String authFail = "鉴权失败"; + + public static String operOrg(String xml,String token){ + PluginSimpleConfig psc = PluginSimpleConfig.getInstance(); + OrgBean orgBean = getOrgBean(xml); + try { + AuthUtils.auth(token,System.currentTimeMillis(), psc); + } catch (Exception e) { + return getResultXml(orgBean.getID(),fail,authFail+";"+e.getMessage()); + } + + String operType = orgBean.getFROMOPERTYPE(); + + DepartmentServiceKit kit = DepartmentServiceKit.getInstance(); + //新增或启用 + if("1".equals(operType) || "4".equals(operType)){ + return addOrg(orgBean,kit); + } + + //修改 + if("2".equals(operType)){ + return updateOrg(orgBean,kit); + } + + //停用,相当于删除 + if("3".equals(operType)){ + return deleteOrg(orgBean,kit); + } + + return getResultXml(orgBean.getID(),fail,"未识别的操作类型FROMOPERTYPE:"+operType); + } + + /** + * 删除机构 + * @param orgBean + * @param kit + * @return + */ + private static String deleteOrg(OrgBean orgBean, DepartmentServiceKit kit){ + String orgid = orgBean.getIU_CODE(); + + try { + Department department = kit.getByid(orgid); + + if(department == null || Utils.isNullStr(department.getId())){ + return getResultXml(orgBean.getID(),fail,notExist); + } + + kit.deleteDepartment(orgid); + } catch (Exception e) { + return getResultXml(orgBean.getID(),fail,unknown+e.getMessage()); + } + + return getResultXml(orgBean.getID(),success,successMsg); + } + + /** + * 修改机构 + * @param orgBean + * @param kit + * @return + */ + private static String updateOrg(OrgBean orgBean, DepartmentServiceKit kit){ + String orgid = orgBean.getIU_CODE(); + String pid = orgBean.getIU_LSSJDW_ID(); + String orgName = orgBean.getIU_FULLNAME(); + + try { + Department department = kit.getByid(orgid); + + if(department == null || Utils.isNullStr(department.getId())){ + return getResultXml(orgBean.getID(),fail,notExist); + } + + kit.editDepartment(orgid,orgName,pid); + } catch (Exception e) { + return getResultXml(orgBean.getID(),fail,unknown+e.getMessage()); + } + + return getResultXml(orgBean.getID(),success,successMsg); + } + + /** + * 添加机构 + * @param orgBean + * @param kit + * @return + */ + private static String addOrg(OrgBean orgBean, DepartmentServiceKit kit){ + String orgid = orgBean.getIU_CODE(); + String pid = orgBean.getIU_LSSJDW_ID(); + String orgName = orgBean.getIU_FULLNAME(); + + try { + Department department = kit.getByid(orgid); + + if(department != null && !Utils.isNullStr(department.getId())){ + return getResultXml(orgBean.getID(),fail,duplicate); + } + + kit.addDepartment(orgid,pid,orgName); + } catch (Exception e) { + return getResultXml(orgBean.getID(),fail,unknown+e.getMessage()); + } + + return getResultXml(orgBean.getID(),success,successMsg); + } + + /** + * 获取返回报文 + * @param id + * @param status + * @param msg + * @return + */ + private static String getResultXml(String id,String status,String msg){ + String resultXml = "\n" + + "\n" + + " \n" + + " #id\n" + + " #status\n" + + " 1\n" + + " #msg\n" + + " \n" + + ""; + + return resultXml.replace("#id",id).replace("#status",status).replace("#msg",msg); + } + + /** + * 从xml报文解析OrgBean实体 + * @param xmltext + * @return + */ + private static OrgBean getOrgBean(String xmltext){ + String ID = xmltext.substring(xmltext.indexOf("")+4,xmltext.indexOf("")); + String FROMOPERTYPE = xmltext.substring(xmltext.indexOf("")+14,xmltext.indexOf("")); + String STATUS = xmltext.substring(xmltext.indexOf("")+8,xmltext.indexOf("")); + String IU_CODE = xmltext.substring(xmltext.indexOf("")+9,xmltext.indexOf("")); + String IU_FULLNAME = xmltext.substring(xmltext.indexOf("")+13,xmltext.indexOf("")); + String IU_LSSJDW_ID = xmltext.substring(xmltext.indexOf("")+14,xmltext.indexOf("")); + + OrgBean ob = new OrgBean(); + ob.setID(ID); + ob.setFROMOPERTYPE(FROMOPERTYPE); + ob.setSTATUS(STATUS); + ob.setIU_CODE(IU_CODE); + ob.setIU_FULLNAME(IU_FULLNAME); + ob.setIU_LSSJDW_ID(IU_LSSJDW_ID); + + return ob; + } +} + + diff --git a/src/main/java/com/eco/plugin/xx/zcgjsync/utils/ResponseUtils.java b/src/main/java/com/eco/plugin/xx/zcgjsync/utils/ResponseUtils.java new file mode 100644 index 0000000..98a16b8 --- /dev/null +++ b/src/main/java/com/eco/plugin/xx/zcgjsync/utils/ResponseUtils.java @@ -0,0 +1,108 @@ +package com.eco.plugin.xx.zcgjsync.utils; + +import com.fr.json.JSONObject; +import com.fr.log.FineLoggerFactory; +import com.fr.web.utils.WebUtils; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.PrintWriter; + +public class ResponseUtils { + private static final int SUCCESS = 200; + private static final int FAILED = -1; + + public static void successResponse(HttpServletResponse res, String body) { + response(res, body, SUCCESS); + } + + public static void failedResponse(HttpServletResponse res, String body) { + response(res, body, FAILED); + } + + private static void response(HttpServletResponse res, String body, int code) { + JSONObject object = new JSONObject(); + PrintWriter pw; + try { + object.put("code", code); + object.put("data", body); + pw = WebUtils.createPrintWriter(res); + } catch (Exception e) { + FineLoggerFactory.getLogger().info(e.getMessage()); + return; + } + res.setContentType("application/json;charset=utf-8"); + String result = object.toString(); + pw.println(result); + pw.flush(); + pw.close(); + } + + public static void response(HttpServletResponse res,JSONObject json){ + PrintWriter pw; + try { + pw = WebUtils.createPrintWriter(res); + } catch (Exception e) { + FineLoggerFactory.getLogger().info(e.getMessage()); + return; + } + res.setContentType("application/json;charset=utf-8"); + String result = json.toString(); + pw.println(result); + pw.flush(); + pw.close(); + } + + public static void responseText(HttpServletResponse res,String text){ + PrintWriter pw; + try { + pw = WebUtils.createPrintWriter(res); + } catch (Exception e) { + FineLoggerFactory.getLogger().info(e.getMessage()); + return; + } + res.setContentType("text/html;charset=utf-8"); + pw.println(text); + pw.flush(); + pw.close(); + } + + public static void responseXml(HttpServletResponse res,String xml){ + PrintWriter pw; + try { + pw = WebUtils.createPrintWriter(res); + } catch (Exception e) { + FineLoggerFactory.getLogger().info(e.getMessage()); + return; + } + res.setContentType("text/xml;charset=utf-8"); + pw.println(xml); + pw.flush(); + pw.close(); + } + + public static void setCSRFHeader(HttpServletResponse httpServletResponse){ + httpServletResponse.setHeader("Access-Control-Allow-Origin", "*"); + httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE,HEAD,PUT,PATCH"); + httpServletResponse.setHeader("Access-Control-Max-Age", "36000"); + httpServletResponse.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept,Authorization,authorization"); + } + + public static void responseJsonp(HttpServletRequest req, HttpServletResponse res, JSONObject json){ + PrintWriter pw; + try { + pw = WebUtils.createPrintWriter(res); + } catch (Exception e) { + FineLoggerFactory.getLogger().info(e.getMessage()); + return; + } + res.setContentType("text/javascript;charset=utf-8;charset=utf-8"); + String result = json.toString(); + + String jsonp=req.getParameter("callback"); + + pw.println(jsonp+"("+result+")"); + pw.flush(); + pw.close(); + } +} diff --git a/src/main/java/com/eco/plugin/xx/zcgjsync/utils/UserUtils.java b/src/main/java/com/eco/plugin/xx/zcgjsync/utils/UserUtils.java new file mode 100644 index 0000000..632609e --- /dev/null +++ b/src/main/java/com/eco/plugin/xx/zcgjsync/utils/UserUtils.java @@ -0,0 +1,230 @@ +package com.eco.plugin.xx.zcgjsync.utils; + +import com.eco.plugin.xx.zcgjsync.bean.UserEntity; +import com.eco.plugin.xx.zcgjsync.config.PluginSimpleConfig; +import com.eco.plugin.xx.zcgjsync.kit.DepartmentServiceKit; +import com.eco.plugin.xx.zcgjsync.kit.UserServiceKit; +import com.fr.decision.authority.data.User; +import com.fr.decision.webservice.bean.user.UserBean; + +import java.util.UUID; + +/** + * 机构操作类 + */ +public class UserUtils { + private static String success = "S"; + private static String fail = "F"; + private static String duplicate = "添加用户失败,已存在相同的用户名称"; + private static String unknown = "未知异常"; + private static String successMsg = "操作成功"; + private static String notExist = "您操作的用户不存在"; + private static String authFail = "鉴权失败"; + + public static String operUser(String xml,String token){ + PluginSimpleConfig psc = PluginSimpleConfig.getInstance(); + UserEntity userEntity = getUserBean(xml); + try { + AuthUtils.auth(token,System.currentTimeMillis(), psc); + } catch (Exception e) { + return getResultXml(userEntity.getID(),fail,authFail+";"+e.getMessage()); + } + + String operType = userEntity.getFROMOPERTYPE(); + + UserServiceKit kit = UserServiceKit.getInstance(); + //新增或启用 + if("1".equals(operType)){ + return addUser(userEntity,kit); + } + + //修改 + if("2".equals(operType)){ + return updateUser(userEntity,kit); + } + + User user = null; + try { + user = FRUserUtils.getUserByUserName(userEntity.getNO()); + } catch (Exception e) { + return getResultXml(userEntity.getID(),fail,unknown+e.getMessage()); + } + + //停用 + if("3".equals(operType)){ + try { + FRUserUtils.forbidUser(user.getId(),false); + } catch (Exception e) { + return getResultXml(userEntity.getID(),fail,"停用用户失败"); + } + return getResultXml(userEntity.getID(),success,successMsg); + } + + //启用 + if("4".equals(operType)){ + try { + FRUserUtils.forbidUser(user.getId(),true); + } catch (Exception e) { + return getResultXml(userEntity.getID(),fail,"启用用户失败"); + } + return getResultXml(userEntity.getID(),success,successMsg); + } + + return getResultXml(userEntity.getID(),fail,"未识别的操作类型FROMOPERTYPE:"+operType); + } + + /** + * 删除机构 + * @param userEntity + * @param kit + * @return + */ + private static String deleteUser(UserEntity userEntity, DepartmentServiceKit kit){ + + + try { + User user = FRUserUtils.getUserByUserName(userEntity.getNO()); + + if(user == null || Utils.isNullStr(user.getId())){ + return getResultXml(userEntity.getID(),fail,notExist); + } + + FRUserUtils.deleteUser(user); + } catch (Exception e) { + return getResultXml(userEntity.getID(),fail,unknown+e.getMessage()); + } + + return getResultXml(userEntity.getID(),success,successMsg); + } + + /** + * 修改用户 + * @param userEntity + * @param kit + * @return + */ + private static String updateUser(UserEntity userEntity, UserServiceKit kit){ + try { + User user = FRUserUtils.getUserByUserName(userEntity.getNO()); + + if(user == null || Utils.isNullStr(user.getId())){ + return getResultXml(userEntity.getID(),fail,notExist); + } + + UserBean userBean = userEntityToBean(userEntity); + userBean.setId(user.getId()); + + kit.editUser(userBean,""); + + FRUserUtils.clearUserDepAndPost(user.getId()); + FRUserUtils.updateDepartmentPostUsers(userEntity.getIU_LSSJDW_ID(),"",user.getId()); + + } catch (Exception e) { + return getResultXml(userEntity.getID(),fail,unknown+e.getMessage()); + } + + return getResultXml(userEntity.getID(),success,successMsg); + } + + /** + * 添加用户 + * @param userEntity + * @param kit + * @return + */ + private static String addUser(UserEntity userEntity, UserServiceKit kit){ + try { + User user = FRUserUtils.getUserByUserName(userEntity.getNO()); + + if(user != null && !Utils.isNullStr(user.getId())){ + return getResultXml(userEntity.getID(),fail,duplicate); + } + + UserBean userBean = userEntityToBean(userEntity); + kit.addUser(userBean); + + //更新用户状态 + String userid = userBean.getId(); + FRUserUtils.forbidUser(userid,"1".equals(userEntity.getSTATUS())); + + //设置用户组织机构 + String orgid = userEntity.getIU_LSSJDW_ID(); + if(Utils.isNotNullStr(orgid)){ + FRUserUtils.updateDepartmentPostUsers(orgid,"",userid); + } + + } catch (Exception e) { + return getResultXml(userEntity.getID(),fail,unknown+e.getMessage()); + } + + return getResultXml(userEntity.getID(),success,successMsg); + } + + /** + * + * @param userEntity + * @return + */ + private static UserBean userEntityToBean(UserEntity userEntity){ + UserBean userBean = new UserBean(); + userBean.setId(UUID.randomUUID().toString()); + userBean.setPassword("sinoma123"); + userBean.setUsername(userEntity.getNO()); + userBean.setRealName(userEntity.getNAME()); + userBean.setEmail(userEntity.getEMAIL()); + userBean.setMobile(userEntity.getTELEPHONE()); + + return userBean; + } + + /** + * 获取返回报文 + * @param id + * @param status + * @param msg + * @return + */ + private static String getResultXml(String id,String status,String msg){ + String resultXml = "\n" + + "\n" + + " \n" + + " #id\n" + + " #status\n" + + " 1\n" + + " #msg\n" + + " \n" + + ""; + + return resultXml.replace("#id",id).replace("#status",status).replace("#msg",msg); + } + + /** + * 从xml报文解析userBean实体 + * @param xmltext + * @return + */ + private static UserEntity getUserBean(String xmltext){ + String ID = xmltext.substring(xmltext.indexOf("")+4,xmltext.indexOf("")); + String FROMOPERTYPE = xmltext.substring(xmltext.indexOf("")+14,xmltext.indexOf("")); + String STATUS = xmltext.substring(xmltext.indexOf("")+8,xmltext.indexOf("")); + String NAME = xmltext.substring(xmltext.indexOf("")+6,xmltext.indexOf("")); + String NO = xmltext.substring(xmltext.indexOf("")+4,xmltext.indexOf("")); + String EMAIL = xmltext.substring(xmltext.indexOf("")+7,xmltext.indexOf("")); + String TELEPHONE = xmltext.substring(xmltext.indexOf("")+11,xmltext.indexOf("")); + String IU_LSSJDW_ID = xmltext.substring(xmltext.indexOf("")+14,xmltext.indexOf("")); + + UserEntity ub = new UserEntity(); + ub.setID(ID); + ub.setFROMOPERTYPE(FROMOPERTYPE); + ub.setSTATUS(STATUS); + ub.setNAME(NAME); + ub.setNO(NO); + ub.setEMAIL(EMAIL); + ub.setTELEPHONE(TELEPHONE); + ub.setIU_LSSJDW_ID(IU_LSSJDW_ID); + + return ub; + } +} + + diff --git a/src/main/java/com/eco/plugin/xx/zcgjsync/utils/Utils.java b/src/main/java/com/eco/plugin/xx/zcgjsync/utils/Utils.java new file mode 100644 index 0000000..150d7af --- /dev/null +++ b/src/main/java/com/eco/plugin/xx/zcgjsync/utils/Utils.java @@ -0,0 +1,350 @@ +package com.eco.plugin.xx.zcgjsync.utils; + +import com.fr.base.TemplateUtils; +import com.fr.data.NetworkHelper; +import com.fr.decision.webservice.v10.user.UserService; +import com.fr.io.utils.ResourceIOUtils; +import com.fr.json.JSONObject; +import com.fr.stable.CodeUtils; +import com.fr.stable.StringUtils; +import com.fr.third.org.apache.commons.codec.digest.DigestUtils; +import com.fr.web.utils.WebUtils; + +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.BufferedReader; +import java.io.InputStream; +import java.net.URLEncoder; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class Utils { + + /** + * 判断字符串是否为空 + * @param str + * @return true 空字符串 false 非空字符串 + */ + public static boolean isNullStr(String str){ + return !(str != null && !str.isEmpty() && !"null".equals(str)); + } + + /** + * 判断字符串是否非空 + * @param str + * @return + */ + public static boolean isNotNullStr(String str){ + return !isNullStr(str); + } + + /** + * MD5加密 + * @param str + * @return + */ + public static String getMd5Str(String str) + { + return DigestUtils.md5Hex(str); + } + + /** + * 帆软shaEncode加密 + */ + + public static String shaEncode(String str){ + return CodeUtils.sha256Encode(str); + } + + /** + * 获取uuid + */ + public static String uuid(){ + return UUID.randomUUID().toString(); + } + + /** + * 替换空字符串 + * @param str + * @param replace + * @return + */ + public static String replaceNullStr(String str,String replace){ + if(isNullStr(str)){ + return replace; + } + + return str; + } + + /** + * 获取请求体 + * @param req + * @return + */ + public static JSONObject getRequestBody(HttpServletRequest req){ + StringBuffer sb = new StringBuffer(); + String line = null; + try { + BufferedReader reader = req.getReader(); + while ((line = reader.readLine()) != null) + sb.append(line); + } catch (Exception e) { + FRUtils.FRLogInfo("getRequestBody:exception:"+e.getMessage()); + } + //将空格和换行符替换掉避免使用反序列化工具解析对象时失败 + String jsonString = sb.toString().replaceAll("\\s","").replaceAll("\n",""); + FRUtils.FRLogInfo("reqBody:"+jsonString); + JSONObject json = new JSONObject(jsonString); + + return json; + } + + /** + * 获取文本请求体 + * @param req + * @return + */ + public static String getRequestBodyText(HttpServletRequest req){ + StringBuffer sb = new StringBuffer(); + String line = null; + try { + BufferedReader reader = req.getReader(); + while ((line = reader.readLine()) != null) + sb.append(line); + } catch (Exception e) { + FRUtils.FRLogInfo("getRequestBody:exception:"+e.getMessage()); + } + //将空格和换行符替换掉避免使用反序列化工具解析对象时失败 + String jsonString = sb.toString().replaceAll("\\s","").replaceAll("\n",""); + + return jsonString; + } + + /** + * 获取ip + * @return + */ + public static String getIp(HttpServletRequest req){ + String realIp = req.getHeader("X-Real-IP"); + String fw = req.getHeader("X-Forwarded-For"); + if (StringUtils.isNotEmpty(fw) && !"unKnown".equalsIgnoreCase(fw)) { + int para3 = fw.indexOf(","); + return para3 != -1 ? fw.substring(0, para3) : fw; + } else { + fw = realIp; + if (StringUtils.isNotEmpty(realIp) && !"unKnown".equalsIgnoreCase(realIp)) { + return realIp; + } else { + if (StringUtils.isBlank(realIp) || "unknown".equalsIgnoreCase(realIp)) { + fw = req.getHeader("Proxy-Client-IP"); + } + + if (StringUtils.isBlank(fw) || "unknown".equalsIgnoreCase(fw)) { + fw = req.getHeader("WL-Proxy-Client-IP"); + } + + if (StringUtils.isBlank(fw) || "unknown".equalsIgnoreCase(fw)) { + fw = req.getHeader("HTTP_CLIENT_IP"); + } + + if (StringUtils.isBlank(fw) || "unknown".equalsIgnoreCase(fw)) { + fw = req.getHeader("HTTP_X_FORWARDED_FOR"); + } + + if (StringUtils.isBlank(fw) || "unknown".equalsIgnoreCase(fw)) { + fw = req.getRemoteAddr(); + } + + return fw; + } + } + } + + /** + * 根据key获取cookie + * @param req + * @return + */ + public static String getCookieByKey(HttpServletRequest req,String key){ + Cookie[] cookies = req.getCookies(); + String cookie = ""; + + if(cookies == null || cookies.length <=0){ + return ""; + } + + for(int i = 0; i < cookies.length; i++) { + Cookie item = cookies[i]; + if (item.getName().equalsIgnoreCase(key)) { + cookie = item.getValue(); + } + } + + FRUtils.FRLogInfo("cookie:"+cookie); + + return cookie; + } + + /** + * 判断是否是手机端的链接 + * @param req + * @return + */ + public static boolean isMobile(HttpServletRequest req) { + String[] mobileArray = {"iPhone", "iPad", "android", "windows phone", "xiaomi"}; + String userAgent = req.getHeader("user-agent"); + if (userAgent != null && userAgent.toUpperCase().contains("MOBILE")) { + for(String mobile : mobileArray) { + if(userAgent.toUpperCase().contains(mobile.toUpperCase())) { + return true; + } + } + } + return NetworkHelper.getDevice(req).isMobile(); + } + + /** + * 只编码中文 + * @param url + * @return + */ + public static String encodeCH(String url ){ + Matcher matcher = Pattern.compile("[\\u4e00-\\u9fa5]").matcher(url); + + while(matcher.find()){ + String chn = matcher.group(); + url = url.replaceAll(chn, URLEncoder.encode(chn)); + } + + return url; + } + + /** + * 获取web-inf文件夹下的文件 + * filename /resources/ip4enc.properties + */ + public static InputStream getResourcesFile(String filename){ + return ResourceIOUtils.read(filename); + } + + /** + * + * @param res + * @param path /com/fr/plugin/loginAuth/html/getMac.html + * @param parameterMap + */ + public static void toErrorPage(HttpServletResponse res,String path,Map parameterMap){ + if(parameterMap == null){ + parameterMap = new HashMap(); + } + + try { + String macPage = TemplateUtils.renderTemplate(path, parameterMap); + WebUtils.printAsString(res, macPage); + }catch (Exception e){ + FRUtils.FRLogError("跳转页面异常"); + } + + } + + /** + * 判断是否是管理员 + * @param username + * @return + */ + public static boolean isAdmin(String username) throws Exception{ + return UserService.getInstance().isAdmin(UserService.getInstance().getUserByUserName(username).getId()); + } + + /** + * 去掉浏览器中的参数 + * @param url + * @param param + * @return + */ + public static String removeParam(String url,String param){ + if(!url.contains("?"+param) && !url.contains("&"+param)){ + return url; + } + + return url.substring(0,url.indexOf(url.contains("?"+param) ? "?"+param : "&"+param)); + } + + /** + * 获取跳转链接 + * @param req + * @param param + * @return + */ + public static String getRedirectUrl(HttpServletRequest req,String param){ + String url = FRUtils.getAllUrl(req); + + if(isNotNullStr(param)){ + url = removeParam(url,param); + } + + url = encodeCH(url); + + return url; + } + + /** + * 去除空格换行 + * @param str + * @return + */ + public static String trim(String str){ + return str.trim().replaceAll("\n","").replaceAll("\r",""); + } + + /** + * list 转化为指定字符分割的字符串 + * @param list + * @param list + * @return + */ + public static String listToStr(List list, String split){ + String result = ""; + + if(list == null || list.size() <= 0){ + return result; + } + + for(String str : list){ + result+=","+str; + } + + result = result.substring(1); + + return result; + } + + /** + * array 转化为指定字符分割的字符串 + * @param list + * @param list + * @return + */ + public static String arrayToStr(String[] list, String split){ + String result = ""; + + if(list == null ||list.length <= 0){ + return result; + } + + for(int i=0;i