commit 4366fb88212d2a4b50db7c5d54a40fe801e89dd6 Author: pioneer Date: Tue Nov 8 17:25:45 2022 +0800 open diff --git a/README.md b/README.md new file mode 100644 index 0000000..eaeade3 --- /dev/null +++ b/README.md @@ -0,0 +1,6 @@ +# open-JSD-9921 + +JSD-9921 URL单点并实现屏蔽外网\ +免责说明:该源码为第三方爱好者提供,不保证源码和方案的可靠性,也不提供任何形式的源码教学指导和协助!\ +仅作为开发者学习参考使用!禁止用于任何商业用途!\ +为保护开发者隐私,开发者信息已隐去!若原开发者希望公开自己的信息,可联系【pioneer】处理。 \ No newline at end of file diff --git a/plugin.xml b/plugin.xml new file mode 100644 index 0000000..319332c --- /dev/null +++ b/plugin.xml @@ -0,0 +1,21 @@ + + com.eco.plugin.xx.hlzjsso + + yes + 1.0.7 + 10.0 + 2018-07-31 + fr.open + + + com.eco.plugin.xx.hlzjsso + + + + + + + + + \ No newline at end of file diff --git a/src/main/java/com/eco/plugin/xx/hlzjsso/config/InitializeMonitor.java b/src/main/java/com/eco/plugin/xx/hlzjsso/config/InitializeMonitor.java new file mode 100644 index 0000000..35c3ade --- /dev/null +++ b/src/main/java/com/eco/plugin/xx/hlzjsso/config/InitializeMonitor.java @@ -0,0 +1,21 @@ +package com.eco.plugin.xx.hlzjsso.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/hlzjsso/config/PluginSimpleConfig.java b/src/main/java/com/eco/plugin/xx/hlzjsso/config/PluginSimpleConfig.java new file mode 100644 index 0000000..4656d4f --- /dev/null +++ b/src/main/java/com/eco/plugin/xx/hlzjsso/config/PluginSimpleConfig.java @@ -0,0 +1,134 @@ +package com.eco.plugin.xx.hlzjsso.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.hlzjsso.config", text = "单点登录配置", source = Original.PLUGIN) + public static PluginSimpleConfig getInstance() { + if (config == null) { + config = ConfigContext.getConfigInstance(PluginSimpleConfig.class); + } + return config; + } + + @Identifier(value = "secret", name = "私钥", description = "私钥", status = Status.SHOW) + private Conf secret = Holders.simple(""); + + @Identifier(value = "paramname", name = "token参数名", description = "token参数名", status = Status.SHOW) + private Conf paramname = Holders.simple(""); + + @Identifier(value = "timeout", name = "token超时时间(s)", description = "token超时时间(s)", status = Status.SHOW) + private Conf timeout = Holders.simple(""); + + @Identifier(value = "hz", name = "账号转化后缀", description = "账号转化后缀", status = Status.SHOW) + private Conf hz = Holders.simple("A"); + + @Identifier(value = "isAll", name = "白名单功能开关", description = "白名单功能开关", status = Status.SHOW) + private Conf isAll = Holders.simple(true); + + @Identifier(value = "isPt", name = "普通用户权限控制开关", description = "普通用户权限控制开关", status = Status.SHOW) + private Conf isPt = Holders.simple(true); + + @Identifier(value = "isAdmin", name = "管理员权限控制开关", description = "管理员权限控制开关", status = Status.SHOW) + private Conf isAdmin = Holders.simple(true); + + @Identifier(value = "zhzh", name = "账户转化开关", description = "账户转化开关", status = Status.SHOW) + private Conf zhzh = Holders.simple(true); + + @Identifier(value = "白名单配置", name = "白名单配置", description = "白名单配置", status = Status.SHOW) + private Conf white = Holders.simple(""); + + public String getHz() { + return hz.get(); + } + + public void setHz(String url) { + this.hz.set(url); + } + + public Boolean getIsAll() { + return isAll.get(); + } + + public void setIsAll(Boolean url) { + this.isAll.set(url); + } + + public Boolean getIsPt() { + return isPt.get(); + } + + public void setIsPt(Boolean url) { + this.isPt.set(url); + } + + public Boolean getIsAdmin() { + return isAdmin.get(); + } + + public void setIsAdmin(Boolean url) { + this.isAdmin.set(url); + } + + public Boolean getZhzh() { + return zhzh.get(); + } + + public void setZhzh(Boolean url) { + this.zhzh.set(url); + } + + public String getWhite() { + return white.get(); + } + + public void setWhite(String url) { + this.white.set(url); + } + + public String getSecret() { + return secret.get(); + } + + public void setSecret(String url) { + this.secret.set(url); + } + + public String getParamname() { + return paramname.get(); + } + + public void setParamname(String url) { + this.paramname.set(url); + } + + public String getTimeout() { + return timeout.get(); + } + + public void setTimeout(String 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/hlzjsso/controller/ControllerRegisterProvider.java b/src/main/java/com/eco/plugin/xx/hlzjsso/controller/ControllerRegisterProvider.java new file mode 100644 index 0000000..5a137ec --- /dev/null +++ b/src/main/java/com/eco/plugin/xx/hlzjsso/controller/ControllerRegisterProvider.java @@ -0,0 +1,14 @@ +package com.eco.plugin.xx.hlzjsso.controller; + +import com.fr.decision.fun.impl.AbstractControllerRegisterProvider; +import com.fr.plugin.transform.FunctionRecorder; + +@FunctionRecorder +public class ControllerRegisterProvider extends AbstractControllerRegisterProvider { + @Override + public Class[] getControllers() { + return new Class[]{ + ControllerSelf.class + }; + } +} diff --git a/src/main/java/com/eco/plugin/xx/hlzjsso/controller/ControllerSelf.java b/src/main/java/com/eco/plugin/xx/hlzjsso/controller/ControllerSelf.java new file mode 100644 index 0000000..688a4f6 --- /dev/null +++ b/src/main/java/com/eco/plugin/xx/hlzjsso/controller/ControllerSelf.java @@ -0,0 +1,57 @@ +package com.eco.plugin.xx.hlzjsso.controller; + +import com.eco.plugin.xx.hlzjsso.config.PluginSimpleConfig; +import com.eco.plugin.xx.hlzjsso.utils.IPWhiteUtils; +import com.eco.plugin.xx.hlzjsso.utils.ResponseUtils; +import com.eco.plugin.xx.hlzjsso.utils.Utils; +import com.fr.decision.webservice.annotation.LoginStatusChecker; +import com.fr.json.JSONObject; +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 = "/canLogin") + @ResponseBody + public void canLogin(HttpServletRequest req,HttpServletResponse res){ + JSONObject param = Utils.getRequestBody(req); + String username = param.getString("username"); + PluginSimpleConfig psc = PluginSimpleConfig.getInstance(); + boolean isWhite = IPWhiteUtils.inWhite(req,psc.getWhite()); + + if(isWhite || !psc.getIsAll()){ + ResponseUtils.successResponse(res,""); + return ; + } + + boolean isAdmin = false; + try { + isAdmin = Utils.isAdmin(username); + } catch (Exception e) { + ResponseUtils.failedResponse(res,"判断管理员失败!"); + return ; + } + + //管理员且管理员权限控制开启 + if(isAdmin && psc.getIsAdmin()){ + ResponseUtils.failedResponse(res,"外网环境管理员禁止登陆!"); + return ; + } + + //普通用户权限开始 + if(!isAdmin && psc.getIsPt()){ + ResponseUtils.failedResponse(res,"外网环境普通账户禁止登陆!"); + return ; + } + + ResponseUtils.successResponse(res,""); + } + + +} diff --git a/src/main/java/com/eco/plugin/xx/hlzjsso/filter/SSOFilter.java b/src/main/java/com/eco/plugin/xx/hlzjsso/filter/SSOFilter.java new file mode 100644 index 0000000..c0cb32d --- /dev/null +++ b/src/main/java/com/eco/plugin/xx/hlzjsso/filter/SSOFilter.java @@ -0,0 +1,233 @@ +package com.eco.plugin.xx.hlzjsso.filter; + +import com.eco.plugin.xx.hlzjsso.config.PluginSimpleConfig; +import com.eco.plugin.xx.hlzjsso.utils.*; +import com.fr.decision.authority.data.User; +import com.fr.decision.fun.impl.AbstractGlobalRequestFilterProvider; +import com.fr.json.JSONArray; +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; + +@EnableMetrics +@Authorize(callSignKey = "com.eco.plugin.xx.hlzjsso") +public class SSOFilter extends AbstractGlobalRequestFilterProvider { + @Override + public String filterName() { + return "hlzjssoFilter"; + } + + @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(); + + //token为空,不做拦截 + String token = req.getParameter(psc.getParamname()); + String url = FRUtils.getAllUrl(req); + + String method = req.getMethod(); + //登陆事件 + if(url.endsWith("decision/login") && method.equals("POST")){ + login(req,res); + return ; + } + + if(Utils.isNullStr(token)){ + release(req,res,chain); + return; + } + + String decryptToken = null; + try { + decryptToken = EncryptUtils.rsaDecrypt(token,psc.getSecret()); + } catch (Exception e) { + ResponseUtils.failedResponse(res,"token解密失败:"+e.getMessage()); + return ; + } + + if(Utils.isNullStr(decryptToken)){ + ResponseUtils.failedResponse(res,"token解密失败!"); + return ; + } + + JSONObject tokenJson = new JSONObject(decryptToken); + String username = tokenJson.getString("username"); + Long timestamp = tokenJson.getLong("timestamp"); + Long now = System.currentTimeMillis(); + + boolean isWhite = IPWhiteUtils.inWhite(req,psc.getWhite()); + + //外网而且权限控制功能开关为开 + if(!isWhite && psc.getIsAll()){ + + boolean isAdmin = false; + try { + isAdmin = Utils.isAdmin(username); + } catch (Exception e) { + ResponseUtils.failedResponse(res,"判断管理员失败!"); + return ; + } + + //外网环境且管理员控制为开,管理员不允许单点登陆 + if(isAdmin && psc.getIsAdmin()){ + ResponseUtils.failedResponse(res,"外网环境管理员账户不允许单点登陆!"); + return ; + } + + //外网环境切账户转换为开,对普通用户进行转换 + //判断是否以A结尾,A结尾为外网账户,如果不是将A添加到用户名结尾 + boolean endwithA = username.endsWith(psc.getHz()); + + if(!isAdmin && psc.getZhzh()&&!endwithA){ + username+=psc.getHz(); + } + } + + if((now - timestamp)/1000 > Long.parseLong(psc.getTimeout())){ + ResponseUtils.failedResponse(res,"token超时,请重新生成!"); + return ; + } + + String redirect = Utils.getRedirectUrl(req,psc.getParamname()); + + //登录 + FRUtils.login(req,res,username,redirect); + } + + release(req,res,chain); + } + + //放行拦截器 + private void release(HttpServletRequest req, HttpServletResponse res, FilterChain chain) { + try{ + chain.doFilter(req,res); + }catch (Exception e){ + FRUtils.FRLogInfo("拦截失败"); + } + } + + /** + * 拦截登录事件 + * @param res + */ + private void login(HttpServletRequest req,HttpServletResponse res){ + JSONObject json = Utils.getRequestBody(req); + String username =json.getString("username"); + String psd = json.getString("password"); + String dbpsd = FRUtils.getDBPsd(username,FRUtils.decryptFRPsd(psd)); + + PluginSimpleConfig psc = PluginSimpleConfig.getInstance(); + boolean isWhite = IPWhiteUtils.inWhite(req,psc.getWhite()); + + //返回信息 + JSONObject result = new JSONObject(); + + if(!FRUtils.isUserExist(username)){ + result.put("errorCode","21300007"); + result.put("errorMsg","User not exist,or wrong password!"); + + ResponseUtils.response(res,result); + return ; + } + + if(isWhite || !psc.getIsAll()){ + User user = FRUtils.getFRUserByUserName(username); + if(!user.getPassword().equals(dbpsd)){ + result.put("errorCode","21300007"); + result.put("errorMsg","User not exist,or wrong password!"); + + ResponseUtils.response(res,result); + return ; + } + String token = FRUtils.getToken(req,res,username); + + result.put("username",username); + result.put("validity",-1); + result.put("callback",""); + result.put("accessToken",token); + + JSONObject origin = new JSONObject(); + origin.put("originUrl","/webroot/decision"); + origin.put("method","GET"); + origin.put("parameters",new JSONArray()); + + result.put("originUrlResponse",origin); + result.put("url","/webroot/decision"); + JSONObject data = new JSONObject(); + data.put("data",result); + ResponseUtils.response(res,data); + return ; + } + + boolean isAdmin = false; + try { + isAdmin = Utils.isAdmin(username); + } catch (Exception e) { + result.put("errorMsg","9999"); + result.put("errorCode","判断管理员失败!"); + + ResponseUtils.response(res,result); + return ; + + } + + //管理员且管理员权限控制开启 + if(isAdmin && psc.getIsAdmin()){ + result.put("errorMsg","9999"); + result.put("errorCode","外网环境管理员禁止登陆!"); + + ResponseUtils.response(res,result); + return ; + } + + //普通用户权限开始 + if(!isAdmin && psc.getIsPt()){ + result.put("errorMsg","9999"); + result.put("errorCode","外网环境普通账户禁止登陆!"); + + ResponseUtils.response(res,result); + return ; + } + + User user = FRUtils.getFRUserByUserName(username); + if(!user.getPassword().equals(dbpsd)){ + result.put("errorCode","21300007"); + result.put("errorMsg","User not exist,or wrong password!"); + + ResponseUtils.response(res,result); + return ; + } + String token = FRUtils.getToken(req,res,username); + + result.put("username",username); + result.put("validity",-1); + result.put("callback",""); + result.put("accessToken",token); + + JSONObject origin = new JSONObject(); + origin.put("originUrl","/webroot/decision"); + origin.put("method","GET"); + origin.put("parameters",new JSONArray()); + + result.put("originUrlResponse",origin); + result.put("url","/webroot/decision"); + + JSONObject data = new JSONObject(); + data.put("data",result); + + ResponseUtils.response(res,data); + } +} + diff --git a/src/main/java/com/eco/plugin/xx/hlzjsso/utils/EncryptUtils.java b/src/main/java/com/eco/plugin/xx/hlzjsso/utils/EncryptUtils.java new file mode 100644 index 0000000..b374ee4 --- /dev/null +++ b/src/main/java/com/eco/plugin/xx/hlzjsso/utils/EncryptUtils.java @@ -0,0 +1,333 @@ +package com.eco.plugin.xx.hlzjsso.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.net.URLEncoder; +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"))); + 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/hlzjsso/utils/FRUtils.java b/src/main/java/com/eco/plugin/xx/hlzjsso/utils/FRUtils.java new file mode 100644 index 0000000..82039e1 --- /dev/null +++ b/src/main/java/com/eco/plugin/xx/hlzjsso/utils/FRUtils.java @@ -0,0 +1,321 @@ +package com.eco.plugin.xx.hlzjsso.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.TransmissionTool; +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 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 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 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 + * @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/hlzjsso/utils/IPUtils.java b/src/main/java/com/eco/plugin/xx/hlzjsso/utils/IPUtils.java new file mode 100644 index 0000000..b8a3913 --- /dev/null +++ b/src/main/java/com/eco/plugin/xx/hlzjsso/utils/IPUtils.java @@ -0,0 +1,341 @@ +package com.eco.plugin.xx.hlzjsso.utils; + +import com.fr.data.NetworkHelper; +import com.fr.decision.mobile.terminal.TerminalHandler; +import com.fr.decision.webservice.v10.login.LoginService; +import com.fr.stable.web.Device; + +import javax.servlet.http.HttpServletRequest; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class IPUtils { + + + /** + * 私有IP: + * A类 10.0.0.0-10.255.255.255 + * B类 172.16.0.0-172.31.255.255 + * C类 192.168.0.0-192.168.255.255 + * + * 127这个网段是环回地址 + * localhost + */ + static List ipFilterRegexList = new ArrayList<>(); + + static { + Set ipFilter = new HashSet(); + ipFilter.add("^10\\.(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[0-9])" + + "\\.(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[0-9])" + "\\.(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[0-9])$"); + // B类地址范围: 172.16.0.0---172.31.255.255 + ipFilter.add("^172\\.(1[6789]|2[0-9]|3[01])\\" + ".(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[0-9])\\" + + ".(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[0-9])$"); + // C类地址范围: 192.168.0.0---192.168.255.255 + ipFilter.add("^192\\.168\\.(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[0-9])\\" + + ".(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[0-9])$"); + ipFilter.add("127.0.0.1"); + ipFilter.add("0.0.0.0"); + ipFilter.add("localhost"); + for (String tmp : ipFilter) { + ipFilterRegexList.add(Pattern.compile(tmp)); + } + } + + + // IP的正则,这个正则不能验证第一组数字为0的情况 + private static Pattern pattern = Pattern + .compile("([1-9]\\d?|1\\d{2}|2[01]\\d|22[0-3])\\." + + "(1\\d{1,2}|2[0-4]\\d|25[0-5]|\\d{1,2})\\." + + "(1\\d{1,2}|2[0-4]\\d|25[0-5]|\\d{1,2})\\." + + "(1\\d{1,2}|2[0-4]\\d|25[0-5]|\\d{1,2})"); + + /** + * + * getAvaliIpList:(根据IP白名单设置获取可用的IP列表). + * + * @date 2020-11-11 下午02:50:20 + * @return + */ + + private static Set getAvaliIpList(String allowIp) { + + Set ipList = new HashSet(); + for (String allow : allowIp.replaceAll("\\s", "").split(",")) { + if (allow.indexOf("*") > -1) { + String[] ips = allow.split("\\."); + String[] from = new String[] { "0", "0", "0", "0" }; + String[] end = new String[] { "255", "255", "255", "255" }; + List tem = new ArrayList(); + for (int i = 0; i < ips.length; i++) + if (ips[i].indexOf("*") > -1) { + //todo 直接用等于,不能正确获取类似192.168.**.*这种格式的ip段 + tem = complete(ips[i]); + from[i] = null; + end[i] = null; + } else { + from[i] = ips[i]; + end[i] = ips[i]; + } + + StringBuffer fromIP = new StringBuffer(); + StringBuffer endIP = new StringBuffer(); + for (int i = 0; i < 4; i++) + if (from[i] != null) { + fromIP.append(from[i]).append("."); + endIP.append(end[i]).append("."); + } else { + fromIP.append("[*]."); + endIP.append("[*]."); + } + fromIP.deleteCharAt(fromIP.length() - 1); + endIP.deleteCharAt(endIP.length() - 1); + + for (String s : tem) { + String ip = fromIP.toString().replace("[*]", + s.split(";")[0]) + + "-" + + endIP.toString().replace("[*]", s.split(";")[1]); + if (validate(ip)) { + ipList.add(ip); + } + } + } else { + if (validate(allow)) { + ipList.add(allow); + } + } + + } + + return ipList; + } + + /** + * 对单个IP节点进行范围限定 + * + * @param arg + * @return 返回限定后的IP范围,格式为List[10;19, 100;199] + */ + private static List complete(String arg) { + List com = new ArrayList(); + if (arg.length() == 1) { + com.add("0;255"); + } else if (arg.length() == 2) { + String s1 = complete(arg, 1); + if (s1 != null) + com.add(s1); + String s2 = complete(arg, 2); + if (s2 != null) + com.add(s2); + } else { + String s1 = complete(arg, 1); + if (s1 != null) + com.add(s1); + } + return com; + } + + private static String complete(String arg, int length) { + String from = ""; + String end = ""; + if (length == 1) { + from = arg.replace("*", "0"); + end = arg.replace("*", "9"); + } else { + from = arg.replace("*", "00"); + end = arg.replace("*", "99"); + } + if (Integer.valueOf(from) > 255) + return null; + if (Integer.valueOf(end) > 255) + end = "255"; + return from + ";" + end; + } + + /** + * 在添加至白名单时进行格式校验 + * + * @param ip + * @return + */ + private static boolean validate(String ip) { + for (String s : ip.split("-")) + if (!pattern.matcher(s).matches()) { + return false; + } + return true; + } + + /** + * + * checkLoginIP:(根据IP,及可用Ip列表来判断ip是否包含在白名单之中). + * @date 2017-4-17 下午03:01:03 + * @param ip + * @param ipList + * @return + */ + private static boolean checkLoginIP(String ip, Set ipList) { + if (ipList.isEmpty() || ipList.contains(ip)) + return true; + else { + for (String allow : ipList) { + if (allow.indexOf("-") > -1) { + String[] from = allow.split("-")[0].split("\\."); + String[] end = allow.split("-")[1].split("\\."); + String[] tag = ip.split("\\."); + + // 对IP从左到右进行逐段匹配 + boolean check = true; + for (int i = 0; i < 4; i++) { + int s = Integer.valueOf(from[i]); + int t = Integer.valueOf(tag[i]); + int e = Integer.valueOf(end[i]); + if (!(s <= t && t <= e)) { + check = false; + break; + } + } + if (check) { + return true; + } + } + } + } + return false; + } + + /** + * + * checkLoginIP:(根据IP地址,及IP白名单设置规则判断IP是否包含在白名单). + * @date 2017-4-17 下午03:01:37 + * @param ip + * @param ipWhiteConfig + * @return + */ + public static boolean checkLoginIP(String ip,String ipWhiteConfig){ + Set ipList = getAvaliIpList(ipWhiteConfig); + return checkLoginIP(ip, ipList); + } + + + + + + /** + * 获取真实IP 原逻辑 + * @param request + * @return + */ + public static String getRealIp2(HttpServletRequest request) { + // 这个一般是Nginx反向代理设置的参数 + String ip = request.getHeader("X-Real-IP"); + if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { + ip = request.getHeader("X-Forwarded-For"); + } + if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { + ip = request.getHeader("Proxy-Client-IP"); + } + if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { + ip = request.getHeader("WL-Proxy-Client-IP"); + } + if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { + ip = request.getRemoteAddr(); + } + // 处理多IP的情况(只取第一个IP) + if (ip != null && ip.contains(",")) { + String[] ipArray = ip.split(","); + ip = ipArray[0]; + } + //FineLoggerFactory.getLogger().info("[ENC]客户端IP为[{}]",ip); + return ip; + } + + + /** + * 获取真实IP 客户逻辑 + * @param request + * @return + */ + public static String getRealIp(HttpServletRequest request) { + String ip = request.getHeader("X-Forwarded-For"); + if (ip==null||ip.length()==0||"unknown".equalsIgnoreCase(ip)) { + ip = request.getHeader("X-Real-IP"); + } + if (ip==null||ip.length()==0||"unknown".equalsIgnoreCase(ip)) { + ip = request.getHeader("Proxy-Client-IP"); + } + if (ip==null||ip.length()==0||"unknown".equalsIgnoreCase(ip)) { + ip = request.getHeader("WL-Proxy-Client-IP"); + } + if (ip==null||ip.length()==0||"unknown".equalsIgnoreCase(ip)) { + ip = request.getRemoteAddr(); + } + + // 处理多IP的情况(只取第一个IP) + if (ip != null && ip.contains(",")) { + String[] ipArray = ip.split(","); + ip = ipArray[0]; + } + + return ip; + } + + + + + /** + * 判断IP是否内网IP + * @Title: ipIsInner + * @param ip + * @return: boolean + */ + public static boolean ipIsInner(String ip) { + boolean isInnerIp = false; + for (Pattern tmp : ipFilterRegexList) { + Matcher matcher = tmp.matcher(ip); + if (matcher.find()) { + isInnerIp = true; + break; + } + } + return isInnerIp; + } + + + // token有效性检验 + public static boolean checkTokenValid(HttpServletRequest req, String token) { + + // 判断该token是否还保存在状态服务器中,也就是判断该token是否还有用 + try { + Device device = NetworkHelper.getDevice(req); + LoginService.getInstance().loginStatusValid(token, TerminalHandler.getTerminal(req, device)); + return true; + } catch (Exception e) { + } + return false; + } + + + /** + * 判断是否是内网IP "192.168.1.1," + //设置单个IP的白名单 + * "192.168.*.2," + //设置ip通配符,对一个ip段进行匹配 + * "192.168.3.17-192.168.3.38"; //设置一个IP范围 + * @param ip + * @return + */ + public static boolean isInnerIP(String ip,String ipWhite) throws IOException { + String ip4[]=ip.split("\\."); + if(ip4.length==4) { + return checkLoginIP(ip,ipWhite); + }else{ + return false; + } + } + + +} diff --git a/src/main/java/com/eco/plugin/xx/hlzjsso/utils/IPWhiteUtils.java b/src/main/java/com/eco/plugin/xx/hlzjsso/utils/IPWhiteUtils.java new file mode 100644 index 0000000..16e6edc --- /dev/null +++ b/src/main/java/com/eco/plugin/xx/hlzjsso/utils/IPWhiteUtils.java @@ -0,0 +1,76 @@ +package com.eco.plugin.xx.hlzjsso.utils; + +import com.fr.data.NetworkHelper; +import com.fr.decision.webservice.v10.config.ConfigService; +import com.fr.decision.webservice.v10.login.TokenResource; +import com.fr.log.FineLoggerFactory; +import com.fr.stable.StringUtils; +import com.fr.third.springframework.web.util.WebUtils; + +import javax.servlet.http.HttpServletRequest; +import java.io.IOException; + +public class IPWhiteUtils{ + + private static String ipWhite; + private static String servletName="decision"; + + + /** + * 判断是否是白名单IP "192.168.1.1," + //设置单个IP的白名单 + * "192.168.*.2," + //设置ip通配符,对一个ip段进行匹配 + * "192.168.3.17-192.168.3.38"; //设置一个IP范围 + * @param req + * @return + */ + public static boolean inWhite(HttpServletRequest req,String ip2) { + try { + servletName = ConfigService.getInstance().getBasicParam().getServletPathName(); + } catch (Exception e) { + FineLoggerFactory.getLogger().error("[ENC]获取servletName失败"); + e.printStackTrace(); + } + + ipWhite= ip2; + + String ip= req.getRemoteAddr(); + + FRUtils.FRLogInfo("white:"+ip2+";ip:"+ip); + //内网标记 + boolean isInnerIPFlag= false; + try { + isInnerIPFlag = IPUtils.isInnerIP(ip,ipWhite); + } catch (IOException e) { + FineLoggerFactory.getLogger().error("[ENC]判断IP失败"); + } + + //移动设备标记 + boolean isMobileFlag=NetworkHelper.getDevice(req).isMobile(); + + //移动端原生登陆标记 + boolean isMobileLoginFlag=req.getRequestURI().contains(servletName+"/login") && !isInnerIPFlag; + + //微信登陆标记 + boolean isDingLoginFlag=req.getRequestURI().contains("weixin/single/login") && isMobileFlag; + + String token = TokenResource.COOKIE.getToken(req); + //是否登陆标记 + boolean isHasTokenFlag=!StringUtils.isEmpty(token) && IPUtils.checkTokenValid(req, token); + + //移动端原生登陆标记 + boolean isResourcesFlag=req.getRequestURI().contains(servletName+"/resources"); + + boolean isHasDingCookie=WebUtils.getCookie(req, "LOGIN_TYPE") != null; + + FineLoggerFactory.getLogger().debug("[ENC]内网[{}]|移动设备[{}]|移动原生登陆[{}]|微信登陆[{}]|是否登陆[{}]|请求[{}]",isInnerIPFlag,isMobileFlag,isMobileLoginFlag,isDingLoginFlag,isHasTokenFlag,req.getRequestURI()); + + if(isInnerIPFlag || isResourcesFlag || isHasDingCookie){ + return true; + } + else if(isDingLoginFlag){ + return true; + } else{ + return false; + } + } +} diff --git a/src/main/java/com/eco/plugin/xx/hlzjsso/utils/ResponseUtils.java b/src/main/java/com/eco/plugin/xx/hlzjsso/utils/ResponseUtils.java new file mode 100644 index 0000000..8d89c66 --- /dev/null +++ b/src/main/java/com/eco/plugin/xx/hlzjsso/utils/ResponseUtils.java @@ -0,0 +1,108 @@ +package com.eco.plugin.xx.hlzjsso.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/hlzjsso/utils/Utils.java b/src/main/java/com/eco/plugin/xx/hlzjsso/utils/Utils.java new file mode 100644 index 0000000..096656f --- /dev/null +++ b/src/main/java/com/eco/plugin/xx/hlzjsso/utils/Utils.java @@ -0,0 +1,275 @@ +package com.eco.plugin.xx.hlzjsso.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); + } + + /** + * + * @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; + } + +} diff --git a/src/main/java/com/eco/plugin/xx/hlzjsso/webresourceProvider/WebResourceProvider.java b/src/main/java/com/eco/plugin/xx/hlzjsso/webresourceProvider/WebResourceProvider.java new file mode 100644 index 0000000..d150c19 --- /dev/null +++ b/src/main/java/com/eco/plugin/xx/hlzjsso/webresourceProvider/WebResourceProvider.java @@ -0,0 +1,35 @@ +package com.eco.plugin.xx.hlzjsso.webresourceProvider; + +import com.fr.decision.fun.impl.AbstractWebResourceProvider; +import com.fr.decision.web.LoginComponent; +import com.fr.web.struct.Atom; +import com.fr.web.struct.Component; +import com.fr.web.struct.browser.RequestClient; +import com.fr.web.struct.category.ScriptPath; +import com.fr.web.struct.category.StylePath; + +/** + * Created by xx on 2021-12-03 + */ +public class WebResourceProvider extends AbstractWebResourceProvider { + @Override + public Atom attach() { + return LoginComponent.KEY; + } + + @Override + public Atom client() { + return new Component() { + @Override + public ScriptPath script(RequestClient requestClient) { + return ScriptPath.build("/com/eco/plugin/xx/hlzjsso/js/ui.js"); + } + + @Override + public StylePath style(RequestClient requestClient) { + return StylePath.EMPTY; +// return StylePath.build("/com/fr/plugin/jdfSSO/css/icon.css"); + } + }; + } +} diff --git a/src/main/resources/com/eco/plugin/xx/hlzjsso/js/ui.js b/src/main/resources/com/eco/plugin/xx/hlzjsso/js/ui.js new file mode 100644 index 0000000..e7eec5b --- /dev/null +++ b/src/main/resources/com/eco/plugin/xx/hlzjsso/js/ui.js @@ -0,0 +1,238 @@ + +var e = BI.inherit(BI.Widget, { + props: { + baseCls: "dec-login-login" + }, + _store: function () { + return BI.Models.getModel("dec.model.login.login") + }, + watch: { + supportForgetPwd: function (e) { + this.forgetPasswordRow.setVisible(e) + }, + needSlider: function (e) { + this.sliderMasker.setVisible(e) + } + }, + render: function () { + var t = this; + this.options; + return { + type: "bi.absolute", + items: [{ + el: { + type: "bi.vertical", + items: [{ + type: "dec.login.login.item", + $testId: "dec-login-username", + iconCls: "login-username-font", + tgap: 50, + watermark: BI.i18nText("Dec-User_Name"), + ref: function (e) { + t.usernameRow = e + } + }, { + type: "dec.login.login.item", + $testId: "dec-login-password", + iconCls: "login-password-font", + watermark: BI.i18nText("Dec-Password"), + inputType: "password", + ref: function (e) { + t.passwordRow = e + } + }, { + type: "bi.left_right_vertical_adapt", + bgap: 30, + items: { + left: [{ + type: "bi.multi_select_item", + $testId: "dec-login-remember", + textLgap: 5, + iconWrapperWidth: 16, + height: 16, + text: BI.i18nText("Dec-Login_Remember"), + logic: { + dynamic: !0 + }, + ref: function (e) { + t.rememberRow = e + } + } + ], + right: [{ + type: "bi.button", + $testId: "dec-login-forget-password", + clear: !0, + height: 16, + invisible: !this.model.supportForgetPwd, + text: BI.i18nText("Dec-Basic_Forget_Password"), + ref: function (e) { + t.forgetPasswordRow = e + }, + handler: function () { + t.store.setSelectedTab(DecCst.Login.Tabs.FORGET_PASSWORD) + } + } + ].concat(this._createItems()) + } + }, { + type: "bi.horizontal_auto", + items: [{ + type: "bi.button", + cls: "login-button", + text: BI.i18nText("Dec-Basic_Login"), + width: 190, + height: 40, + handler: function () { + t._start() + } + } + ] + }, { + el: { + type: "bi.vertical", + $testId: "dec-login-logged-chang-text", + cls: "login-error", + invisible: !0, + scrolly: !1, + items: [{ + type: "bi.text", + tagName: "span", + whiteSpace: "normal", + text: BI.i18nText("Dec-Login_Other_Logged_Tip") + }, { + type: "bi.text", + $testId: "dec-login-logged-chang-password", + tagName: "span", + cls: "password-btn", + text: BI.i18nText("Dec-Login_Change_Password"), + handler: function () { + t.model.isNeedVerify ? t.store.setSelectedTab(DecCst.Login.Tabs.VERIFY_BING) : t.store.setSelectedTab(DecCst.Login.Tabs.PASSWORD_OLD) + } + } + ], + ref: function (e) { + t.loginErrorRow = e + } + }, + tgap: 20 + }, { + el: { + type: "bi.text", + $testId: "dec-login-logged-text", + cls: "login-error", + invisible: !0, + whiteSpace: "normal", + text: BI.i18nText("Dec-Login_Normal_Other_Logged_Tip"), + ref: function (e) { + t.loginNormalErrorRow = e + } + }, + tgap: 20 + } + ] + }, + top: 0, + right: 40, + bottom: 0, + left: 40 + }, { + el: { + type: "bi.center_adapt", + cls: "slider-masker", + invisible: !0, + items: [{ + type: "dec.login.slider", + listeners: [{ + eventName: "EVENT_SUCCESS", + action: function () { + t._start() + } + }, { + eventName: "EVENT_CLOSE", + action: function () { + t.store.resetSlider() + } + } + ], + ref: function (e) { + t.sliderBar = e + } + } + ], + ref: function (e) { + t.sliderMasker = e + } + }, + top: 0, + right: 40, + bottom: 0, + left: 40 + } + ] + } + }, + mounted: function () { + var t = this; + this.store.initData(), + this.element.keyup(function (e) { + 13 === e.keyCode && t._start() + }) + }, + _createItems: function () { + return BI.map(BI.Constants.getConstant("dec.constant.login.way.extend"), function (e, t) { + return { + type: t.cardType + } + }) + }, + _start: function () { + var t = this, + e = this.usernameRow.getValue(), + i = this.passwordRow.getValue(), + n = this.rememberRow.isSelected() ? -2 : -1, + userC = this.usernameRow; + t.loginErrorRow.invisible(), + t.loginNormalErrorRow.invisible(), + "" !== e ? "" !== i ? (this.store.setLoginInfo({ + username: e, + validity: n, + phone: "", + captcha: "" + }), this.store.login({ + username: e, + password: this.passwordRow.getCipher(), + validity: n, + sliderToken: this.model.sliderToken, + origin: Dec.Utils.getUrlQuery("origin"), + encrypted: !0 + }, function (e) { + // var result = canLogin(userC.getValue()); + // var code = result.code; + + + + t.store.resetSlider(), + e.data && e.data.accessToken ? t.fireEvent("EVENT_LOGIN", e.data) :(e.errorMsg == 9999 ? userC.showError(e.errorCode) : BI.bind(BI.Services.getService("dec.service.login.login").getHandler(e.errorCode), t)(e)) + } + )) : this.passwordRow.showError(BI.i18nText("Dec-Error_Password_Not_Null")) : this.usernameRow.showError(BI.i18nText("Dec-Error_Username_Not_Null")) + } +}); +BI.shortcut("dec.login.login", e) + +function canLogin(username){ + var result = {}; + + $.ajax({ + async:false, + type:"post", + url:"/webroot/decision/canLogin", + contentType:"application/json;charset=utf-8", + data:JSON.stringify({username:username}), + success:function(data){ + result = data; + } + }) + + return result; +} \ No newline at end of file