From 058b3c1a515deff371b111920d64c85f824bb22a Mon Sep 17 00:00:00 2001 From: pioneer Date: Fri, 16 Sep 2022 16:18:58 +0800 Subject: [PATCH] open --- README.md | 7 + encrypt.xml | 13 + plugin.xml | 20 + .../xxx/bwjtsso/config/InitializeMonitor.java | 21 ++ .../bwjtsso/config/PluginSimpleConfig.java | 59 +++ .../plugin/xxx/bwjtsso/filter/SSOFilter.java | 68 ++++ .../plugin/xxx/bwjtsso/utils/AesUtils.java | 104 ++++++ .../xxx/bwjtsso/utils/EncryptUtils.java | 346 ++++++++++++++++++ .../eco/plugin/xxx/bwjtsso/utils/FRUtils.java | 293 +++++++++++++++ .../xxx/bwjtsso/utils/ResponseUtils.java | 108 ++++++ .../eco/plugin/xxx/bwjtsso/utils/Utils.java | 244 ++++++++++++ 11 files changed, 1283 insertions(+) create mode 100644 README.md create mode 100644 encrypt.xml create mode 100644 plugin.xml create mode 100644 src/main/java/com/eco/plugin/xxx/bwjtsso/config/InitializeMonitor.java create mode 100644 src/main/java/com/eco/plugin/xxx/bwjtsso/config/PluginSimpleConfig.java create mode 100644 src/main/java/com/eco/plugin/xxx/bwjtsso/filter/SSOFilter.java create mode 100644 src/main/java/com/eco/plugin/xxx/bwjtsso/utils/AesUtils.java create mode 100644 src/main/java/com/eco/plugin/xxx/bwjtsso/utils/EncryptUtils.java create mode 100644 src/main/java/com/eco/plugin/xxx/bwjtsso/utils/FRUtils.java create mode 100644 src/main/java/com/eco/plugin/xxx/bwjtsso/utils/ResponseUtils.java create mode 100644 src/main/java/com/eco/plugin/xxx/bwjtsso/utils/Utils.java diff --git a/README.md b/README.md new file mode 100644 index 0000000..4fac56b --- /dev/null +++ b/README.md @@ -0,0 +1,7 @@ + +# open-JSD-9805 + +JSD-9805 fr作为被集成方,从单点请求里面拿到用户工号,并用工号后台登录\ +免责说明:该源码为第三方爱好者提供,不保证源码和方案的可靠性,也不提供任何形式的源码教学指导和协助!\ +仅作为开发者学习参考使用!禁止用于任何商业用途!\ +为保护开发者隐私,开发者信息已隐去!若原开发者希望公开自己的信息,可联系【pioneer】处理。 \ No newline at end of file diff --git a/encrypt.xml b/encrypt.xml new file mode 100644 index 0000000..1401cd1 --- /dev/null +++ b/encrypt.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/plugin.xml b/plugin.xml new file mode 100644 index 0000000..e9ef7dc --- /dev/null +++ b/plugin.xml @@ -0,0 +1,20 @@ + + com.eco.plugin.xxx.bwjtsso + + yes + 1.0.1 + 10.0 + 2018-07-31 + fr.open + + + com.eco.plugin.xxx.bwjtsso + + + + + + + + \ No newline at end of file diff --git a/src/main/java/com/eco/plugin/xxx/bwjtsso/config/InitializeMonitor.java b/src/main/java/com/eco/plugin/xxx/bwjtsso/config/InitializeMonitor.java new file mode 100644 index 0000000..9d27a22 --- /dev/null +++ b/src/main/java/com/eco/plugin/xxx/bwjtsso/config/InitializeMonitor.java @@ -0,0 +1,21 @@ +package com.eco.plugin.xxx.bwjtsso.config; + +import com.fr.plugin.context.PluginContext; +import com.fr.plugin.observer.inner.AbstractPluginLifecycleMonitor; + +/** + * @author xxx + * @version 10.0 + * Created by xxx 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/xxx/bwjtsso/config/PluginSimpleConfig.java b/src/main/java/com/eco/plugin/xxx/bwjtsso/config/PluginSimpleConfig.java new file mode 100644 index 0000000..c556810 --- /dev/null +++ b/src/main/java/com/eco/plugin/xxx/bwjtsso/config/PluginSimpleConfig.java @@ -0,0 +1,59 @@ +package com.eco.plugin.xxx.bwjtsso.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.xxx.bwjtsso.config", text = "单点登录配置", source = Original.PLUGIN) + public static PluginSimpleConfig getInstance() { + if (config == null) { + config = ConfigContext.getConfigInstance(PluginSimpleConfig.class); + } + return config; + } + + @Identifier(value = "key", name = "秘钥", description = "秘钥", status = Status.SHOW) + private Conf key = Holders.simple(""); + + @Identifier(value = "param", name = "加密参数名", description = "加密参数名", status = Status.SHOW) + private Conf param = Holders.simple(""); + + + + public String getKey() { + return key.get(); + } + + public void setKey(String url) { + this.key.set(url); + } + + public String getParam() { + return param.get(); + } + + public void setParam(String url) { + this.param.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/xxx/bwjtsso/filter/SSOFilter.java b/src/main/java/com/eco/plugin/xxx/bwjtsso/filter/SSOFilter.java new file mode 100644 index 0000000..12663c5 --- /dev/null +++ b/src/main/java/com/eco/plugin/xxx/bwjtsso/filter/SSOFilter.java @@ -0,0 +1,68 @@ +package com.eco.plugin.xxx.bwjtsso.filter; + +import com.eco.plugin.xxx.bwjtsso.config.PluginSimpleConfig; +import com.eco.plugin.xxx.bwjtsso.utils.AesUtils; +import com.eco.plugin.xxx.bwjtsso.utils.FRUtils; +import com.eco.plugin.xxx.bwjtsso.utils.ResponseUtils; +import com.eco.plugin.xxx.bwjtsso.utils.Utils; +import com.fr.decision.fun.impl.AbstractGlobalRequestFilterProvider; +import com.fr.json.JSONObject; +import com.fr.plugin.context.PluginContexts; +import com.fr.record.analyzer.EnableMetrics; +import com.fr.stable.fun.Authorize; +import javax.servlet.FilterChain; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +@EnableMetrics +@Authorize(callSignKey = "com.eco.plugin.xxx.bwjtsso") +public class SSOFilter extends AbstractGlobalRequestFilterProvider { + @Override + public String filterName() { + return "bwjtssoFilter"; + } + + @Override + public String[] urlPatterns() { + return new String[]{"/*"}; + } + + @Override + public void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain chain ){ + + if(PluginContexts.currentContext().isAvailable()){ + PluginSimpleConfig psc = PluginSimpleConfig.getInstance(); + String param = psc.getParam(); + String userid = req.getParameter(param); + + if(Utils.isNullStr(userid)){ + release(req,res,chain); + return ; + } + + String key = psc.getKey(); + String username = AesUtils.decrypt(userid,key); + + if(Utils.isNullStr(username)){ + ResponseUtils.failedResponse(res,"解析token失败!"); + return ; + } + + FRUtils.login(req,res,username,Utils.removeParam(FRUtils.getAllUrl(req),param)); + } + + release(req,res,chain); + } + + + //放行拦截器 + private void release(HttpServletRequest req, HttpServletResponse res, FilterChain chain) { + try{ + chain.doFilter(req,res); + }catch (Exception e){ + FRUtils.FRLogInfo("拦截失败"); + } + } +} + diff --git a/src/main/java/com/eco/plugin/xxx/bwjtsso/utils/AesUtils.java b/src/main/java/com/eco/plugin/xxx/bwjtsso/utils/AesUtils.java new file mode 100644 index 0000000..59b6e95 --- /dev/null +++ b/src/main/java/com/eco/plugin/xxx/bwjtsso/utils/AesUtils.java @@ -0,0 +1,104 @@ +package com.eco.plugin.xxx.bwjtsso.utils; + + +import org.apache.commons.codec.binary.Base64; + +import javax.crypto.Cipher; +import javax.crypto.spec.SecretKeySpec; +import java.net.URLEncoder; +import java.util.Date; + +public class AesUtils { + /** + * 加密 + * @param sSrc 需要加密的字符串 + * @param sKey 加密钥匙 + * @return 加密后的字符串 + * @throws Exception + */ + public static String encrypt(String sSrc, String sKey) throws Exception { + + try{ + if (null == sKey){ + System.out.print("Key为空null"); + return null; + } + // 判断Key是否为16位 + if (sKey.length() != 16){ + System.out.print("Key长度不是16位"); + return null; + } + // 判断Key是否为固定值 + if (!sKey.equals("6ay4dlwd4enjbf90")){ + System.out.print("Key值不对"); + return null; + } + byte[] raw = sKey.getBytes("utf-8"); + SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); + Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");// "算法/模式/补码方式" + cipher.init(Cipher.ENCRYPT_MODE, skeySpec); + Date now = new Date(); + long time = now.getTime(); + sSrc = sSrc + "_" + time; + System.out.println("加密前字符串是:"+sSrc); + byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8")); + return EncryptUtils.base64Encode(encrypted); + }catch (Exception ex){ + System.out.println(ex.toString()); + return null; + } + } + + /** + * 解密 + * @param sSrc 需要解密的字符串 + * @param sKey 解密钥匙 + * @return 解密后的字符串 + * @throws Exception + */ + public static String decrypt(String sSrc, String sKey){ + try{ + // 判断Key是否正确 + if (null == sKey){ + FRUtils.FRLogInfo("Key为空null"); + return null; + } + // 判断Key是否为16位 + if (sKey.length() != 16){ + FRUtils.FRLogInfo("Key长度不是16位"); + return null; + } +// // 判断Key是否为固定值 +// if (!sKey.equals("6ay4dlwd4enjbf90")){ +// FRUtils.FRLogInfo(""); +// System.out.print("Key值不对"); +// return null; +// } + byte[] raw = sKey.getBytes("utf-8"); + SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); + Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); + cipher.init(Cipher.DECRYPT_MODE, skeySpec); + byte[] encrypted1 =EncryptUtils.base64DecodeB(sSrc);// 先用base64解密 + byte[] original = cipher.doFinal(encrypted1); + String originalString = new String(original, "utf-8"); + String []strArr = originalString.split("_"); + String timeStr = strArr[1]; + long timeOld = Long.parseLong(timeStr); + Date now = new Date(); + long timeNow = now.getTime(); + long minute = (timeNow - timeOld)/1000/60; + if(minute <= 2) {// 解密在两分钟内有效 + return strArr[0]; + }else { + FRUtils.FRLogInfo("当前检验已过期!!!"); + return null; + } + + }catch (Exception ex){ + FRUtils.FRLogInfo("exception : "+ex.getMessage()); + + return null; + } + } + +} diff --git a/src/main/java/com/eco/plugin/xxx/bwjtsso/utils/EncryptUtils.java b/src/main/java/com/eco/plugin/xxx/bwjtsso/utils/EncryptUtils.java new file mode 100644 index 0000000..a10ee5b --- /dev/null +++ b/src/main/java/com/eco/plugin/xxx/bwjtsso/utils/EncryptUtils.java @@ -0,0 +1,346 @@ +package com.eco.plugin.xxx.bwjtsso.utils; + +import com.fr.json.JSONObject; +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); + result.put("privateKey",privateKeyString); + + 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"))); + 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; + } + + public static void main(String[] args) throws Exception { + Map keys =genRSAKeyPair(); + String publicKey = keys.get("publicKey"); + String privateKey = keys.get("privateKey"); + + JSONObject json = new JSONObject(); + json.put("username","xiamaofa"); + json.put("timestamp",111111111); + + String jsonstr =json.toString(); + String encrypt = rsaEncrypt(jsonstr,publicKey); + String decrypt = rsaDecrypt(encrypt,privateKey); + + System.out.println(decrypt); + } +} diff --git a/src/main/java/com/eco/plugin/xxx/bwjtsso/utils/FRUtils.java b/src/main/java/com/eco/plugin/xxx/bwjtsso/utils/FRUtils.java new file mode 100644 index 0000000..bccad90 --- /dev/null +++ b/src/main/java/com/eco/plugin/xxx/bwjtsso/utils/FRUtils.java @@ -0,0 +1,293 @@ +package com.eco.plugin.xxx.bwjtsso.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.data.User; +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.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 var1 = AuthorityContext.getInstance().getUserController().find(QueryFactory.create().addRestriction(RestrictionFactory.eq("userName", userName))); + return var1 != null && !var1.isEmpty(); + } catch (Exception var2) { + FineLoggerFactory.getLogger().error(var2.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 var1, String var2, int var3) { + try { + if (StringUtils.isNotEmpty(var2)) { + Cookie var4 = new Cookie("fine_auth_token", var2); + long var5 = var3 == -2 ? 1209600000L : (long)var3; + var4.setMaxAge((int)var5); + var4.setPath(ServerConfig.getInstance().getCookiePath()); + var1.addCookie(var4); + Cookie var7 = new Cookie("fine_remember_login", String.valueOf(var3 == -2 ? -2 : -1)); + var7.setMaxAge((int)var5); + var7.setPath(ServerConfig.getInstance().getCookiePath()); + var1.addCookie(var7); + } else { + FineLoggerFactory.getLogger().error("empty token cannot save."); + } + } catch (Exception var8) { + FineLoggerFactory.getLogger().error(var8.getMessage(), var8); + } + + } + + /** + * + * @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 getAllUrl(HttpServletRequest httpServletRequest){ + return WebUtils.getOriginalURL(httpServletRequest); + } + + /** + * 根据originKey获取源链接 + * @param originKey + * @return + * @throws Exception + */ + public static String getOriginUrl(String originKey) throws Exception { + if (StringUtils.isNotEmpty(originKey)) { + OriginUrlResponseBean originUrlResponseBean = (OriginUrlResponseBean) DecisionStatusService.originUrlStatusService().get(originKey); + DecisionStatusService.originUrlStatusService().delete(originKey); + if (originUrlResponseBean != null) { + return originUrlResponseBean.getOriginUrl(); + } + } + + return new OriginUrlResponseBean(TemplateUtils.render("${fineServletURL}")).getOriginUrl(); + } + + /** + * 判断是否开启模板认证 + * @param originKey + * @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); + } + + public static TableData getTableData(String serverDataSetName){ + TableData userInfo = TableDataConfig.getInstance().getTableData("serverDataSetName"); + +// DataModel userInfoDM = userInfo.createDataModel(Calculator.createCalculator()); + return userInfo; + } +} diff --git a/src/main/java/com/eco/plugin/xxx/bwjtsso/utils/ResponseUtils.java b/src/main/java/com/eco/plugin/xxx/bwjtsso/utils/ResponseUtils.java new file mode 100644 index 0000000..dd638cb --- /dev/null +++ b/src/main/java/com/eco/plugin/xxx/bwjtsso/utils/ResponseUtils.java @@ -0,0 +1,108 @@ +package com.eco.plugin.xxx.bwjtsso.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/xxx/bwjtsso/utils/Utils.java b/src/main/java/com/eco/plugin/xxx/bwjtsso/utils/Utils.java new file mode 100644 index 0000000..7c7872c --- /dev/null +++ b/src/main/java/com/eco/plugin/xxx/bwjtsso/utils/Utils.java @@ -0,0 +1,244 @@ +package com.eco.plugin.xxx.bwjtsso.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.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",""); + + JSONObject json = new JSONObject(jsonString); + + return json; + } + + /** + * 获取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 var3 = fw.indexOf(","); + return var3 != -1 ? fw.substring(0, var3) : 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); + } + + 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()); + } + + 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)); + } +}