From f3714cc172e13129066dd04a2c620ed18ac6b6be Mon Sep 17 00:00:00 2001 From: pioneer Date: Mon, 28 Nov 2022 16:44:39 +0800 Subject: [PATCH] open --- README.md | 6 + plugin.xml | 36 ++ pom.xml | 47 +++ .../xx/ltqc/auth/AuthDBAccessProvider.java | 43 +++ .../fr/plugin/xx/ltqc/auth/AuthFilter.java | 176 ++++++++++ .../com/fr/plugin/xx/ltqc/auth/Constants.java | 13 + .../java/com/fr/plugin/xx/ltqc/auth/LRGT.java | 27 ++ .../fr/plugin/xx/ltqc/auth/RemoteFilter.java | 122 +++++++ .../xx/ltqc/auth/RequestHandlerBridge.java | 26 ++ .../xx/ltqc/auth/RequestURLAliasBridge.java | 22 ++ .../ltqc/auth/action/RolePathAuthService.java | 89 +++++ .../xx/ltqc/auth/conf/AuthSsoConfig.java | 86 +++++ .../xx/ltqc/auth/dao/RolePathAuthDao.java | 21 ++ .../ltqc/auth/entity/RolePathAuthEntity.java | 71 ++++ .../xx/ltqc/auth/handler/AddRoleHandler.java | 169 +++++++++ .../xx/ltqc/auth/handler/AddUserHandler.java | 123 +++++++ .../xx/ltqc/auth/handler/CptListHandler.java | 66 ++++ .../xx/ltqc/auth/handler/DelRoleHandler.java | 70 ++++ .../xx/ltqc/auth/handler/EditRoleHandler.java | 173 +++++++++ .../xx/ltqc/auth/utils/CommonUtils.java | 139 ++++++++ .../xx/ltqc/auth/utils/CookieUtils.java | 58 +++ .../plugin/xx/ltqc/auth/utils/HttpUtil.java | 330 ++++++++++++++++++ .../plugin/xx/ltqc/auth/utils/LogUtils.java | 122 +++++++ 23 files changed, 2035 insertions(+) create mode 100644 README.md create mode 100755 plugin.xml create mode 100644 pom.xml create mode 100644 src/main/java/com/fr/plugin/xx/ltqc/auth/AuthDBAccessProvider.java create mode 100644 src/main/java/com/fr/plugin/xx/ltqc/auth/AuthFilter.java create mode 100644 src/main/java/com/fr/plugin/xx/ltqc/auth/Constants.java create mode 100644 src/main/java/com/fr/plugin/xx/ltqc/auth/LRGT.java create mode 100644 src/main/java/com/fr/plugin/xx/ltqc/auth/RemoteFilter.java create mode 100644 src/main/java/com/fr/plugin/xx/ltqc/auth/RequestHandlerBridge.java create mode 100644 src/main/java/com/fr/plugin/xx/ltqc/auth/RequestURLAliasBridge.java create mode 100644 src/main/java/com/fr/plugin/xx/ltqc/auth/action/RolePathAuthService.java create mode 100644 src/main/java/com/fr/plugin/xx/ltqc/auth/conf/AuthSsoConfig.java create mode 100644 src/main/java/com/fr/plugin/xx/ltqc/auth/dao/RolePathAuthDao.java create mode 100644 src/main/java/com/fr/plugin/xx/ltqc/auth/entity/RolePathAuthEntity.java create mode 100644 src/main/java/com/fr/plugin/xx/ltqc/auth/handler/AddRoleHandler.java create mode 100644 src/main/java/com/fr/plugin/xx/ltqc/auth/handler/AddUserHandler.java create mode 100644 src/main/java/com/fr/plugin/xx/ltqc/auth/handler/CptListHandler.java create mode 100644 src/main/java/com/fr/plugin/xx/ltqc/auth/handler/DelRoleHandler.java create mode 100644 src/main/java/com/fr/plugin/xx/ltqc/auth/handler/EditRoleHandler.java create mode 100644 src/main/java/com/fr/plugin/xx/ltqc/auth/utils/CommonUtils.java create mode 100644 src/main/java/com/fr/plugin/xx/ltqc/auth/utils/CookieUtils.java create mode 100644 src/main/java/com/fr/plugin/xx/ltqc/auth/utils/HttpUtil.java create mode 100644 src/main/java/com/fr/plugin/xx/ltqc/auth/utils/LogUtils.java diff --git a/README.md b/README.md new file mode 100644 index 0000000..87a6bf8 --- /dev/null +++ b/README.md @@ -0,0 +1,6 @@ +# open-JSD-10156 + +JSD-10156 远程设计能用普通用户登录\ +免责说明:该源码为第三方爱好者提供,不保证源码和方案的可靠性,也不提供任何形式的源码教学指导和协助!\ +仅作为开发者学习参考使用!禁止用于任何商业用途!\ +为保护开发者隐私,开发者信息已隐去!若原开发者希望公开自己的信息,可联系【pioneer】处理。 \ No newline at end of file diff --git a/plugin.xml b/plugin.xml new file mode 100755 index 0000000..5dabe91 --- /dev/null +++ b/plugin.xml @@ -0,0 +1,36 @@ + + + com.fr.plugin.xx.ltqc.auth + + yes + 1.11 + 10.0 + 2018-07-31 + fr.open + + + [2022-02-24]【1.1】新增单点功能。
+ [2022-02-28]【1.2】当前用户未登录无法访问。
+ [2022-03-07]【1.3】新增接口。
+ [2022-03-08]【1.4】关系使用ID。
+ [2022-03-08]【1.5】增加鉴权输出日志。
+ [2022-03-14]【1.6】增加目录report鉴权。
+ [2022-03-18]【1.7】admin权限放行。
+ [2022-03-18]【1.8】未登录无权限。
+ [2022-03-21]【1.9】增加全量同步逻辑。
+ [2022-03-21]【1.10】全量删除修改。
+ [2022-05-10]【1.11】全量删除修改。
+ ]]>
+ + + + + + + + + + + +
\ No newline at end of file diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..8bc5a76 --- /dev/null +++ b/pom.xml @@ -0,0 +1,47 @@ + + + + starter + com.fr.plugin + 10.0 + ../../pom.xml + + 4.0.0 + + jsd9155 + + + 8 + 8 + + + + + + ${project.basedir}/../../webroot/WEB-INF/plugins/plugin-${project.groupId}.${project.artifactId}-${project.version}/classes + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.3.2 + + 1.8 + 1.8 + + + + + + src/main/resources + + **/* + + + + + + \ No newline at end of file diff --git a/src/main/java/com/fr/plugin/xx/ltqc/auth/AuthDBAccessProvider.java b/src/main/java/com/fr/plugin/xx/ltqc/auth/AuthDBAccessProvider.java new file mode 100644 index 0000000..369e0f4 --- /dev/null +++ b/src/main/java/com/fr/plugin/xx/ltqc/auth/AuthDBAccessProvider.java @@ -0,0 +1,43 @@ +package com.fr.plugin.xx.ltqc.auth; + +import com.fr.db.fun.impl.AbstractDBAccessProvider; +import com.fr.plugin.xx.ltqc.auth.dao.RolePathAuthDao; +import com.fr.plugin.xx.ltqc.auth.entity.RolePathAuthEntity; +import com.fr.stable.db.accessor.DBAccessor; +import com.fr.stable.db.dao.BaseDAO; +import com.fr.stable.db.dao.DAOProvider; + +/** + * @Author xx + * @Date 2020/11/29 + **/ +public class AuthDBAccessProvider extends AbstractDBAccessProvider { + + private static DBAccessor dbAccessor = null; + + public static DBAccessor getDbAccessor() { + return dbAccessor; + } + + @Override + public DAOProvider[] registerDAO() { + return new DAOProvider[]{ + new DAOProvider() { + @Override + public Class getEntityClass() { + return RolePathAuthEntity.class; + } + + @Override + public Class getDAOClass() { + return RolePathAuthDao.class; + } + }, + }; + } + + @Override + public void onDBAvailable(DBAccessor dbAccessor) { + AuthDBAccessProvider.dbAccessor = dbAccessor; + } +} diff --git a/src/main/java/com/fr/plugin/xx/ltqc/auth/AuthFilter.java b/src/main/java/com/fr/plugin/xx/ltqc/auth/AuthFilter.java new file mode 100644 index 0000000..a695e2f --- /dev/null +++ b/src/main/java/com/fr/plugin/xx/ltqc/auth/AuthFilter.java @@ -0,0 +1,176 @@ +package com.fr.plugin.xx.ltqc.auth; + +import com.fr.decision.authority.AuthorityContext; +import com.fr.decision.authority.data.Authority; +import com.fr.decision.authority.data.CustomRole; +import com.fr.decision.authority.data.User; +import com.fr.decision.fun.impl.AbstractGlobalRequestFilterProvider; +import com.fr.decision.webservice.utils.WebServiceUtils; +import com.fr.decision.webservice.v10.user.CustomRoleService; +import com.fr.decision.webservice.v10.user.UserService; +import com.fr.json.JSONObject; +import com.fr.locale.InterProviderFactory; +import com.fr.log.FineLoggerFactory; +import com.fr.plugin.context.PluginContexts; +import com.fr.plugin.xx.ltqc.auth.action.RolePathAuthService; +import com.fr.plugin.xx.ltqc.auth.conf.AuthSsoConfig; +import com.fr.plugin.xx.ltqc.auth.utils.CommonUtils; +import com.fr.plugin.xx.ltqc.auth.utils.CookieUtils; +import com.fr.plugin.xx.ltqc.auth.utils.HttpUtil; +import com.fr.plugin.xx.ltqc.auth.utils.LogUtils; +import com.fr.stable.StringUtils; +import com.fr.stable.fun.Authorize; +import com.fr.web.utils.WebUtils; + +import javax.servlet.FilterChain; +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.PrintWriter; +import java.util.*; +import java.util.stream.Collectors; + + +/** + * @author xx + * @since 2021/12/04 + */ +@Authorize(callSignKey = Constants.PLUGIN_ID) +public class AuthFilter extends AbstractGlobalRequestFilterProvider { + + private static final String login_url="/authority/login/Login"; + + @Override + public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) { + String validateUser = StringUtils.EMPTY; + Cookie cookie = CookieUtils.getCookie(request, AuthSsoConfig.getInstance().getCookieKey()); + if(cookie != null && AuthSsoConfig.getInstance().isConfiged()){ + Map param = new HashMap<>(); + param.put("ticketValue",cookie.getValue()); + String res = HttpUtil.sendGet(AuthSsoConfig.getInstance().getValidateUrl(), param, null); + LogUtils.debug4plugin("validate cookie url is {}, param is {}, res is {}",AuthSsoConfig.getInstance().getValidateUrl(),param,res); + JSONObject object = new JSONObject(res); + if(object.has("data")){ + validateUser = object.getString("data"); + if(CommonUtils.checkUser(validateUser)){ + CommonUtils.login(validateUser,request,response); + }else { + setError(response,"用户不存在"); + return; + } + } + } + try { + User user = null; + if(StringUtils.isNotBlank(validateUser)){ + user = UserService.getInstance().getUserByUserName(validateUser); + }else { + try { + user = UserService.getInstance().getUserByRequestCookie(request); + }catch (Exception e){ + LogUtils.debug4plugin("current user not login"); + } + } + String let = getlet(request); + if (StringUtils.isBlank(let)) { + next(request, response, chain); + return; + } + if(user == null){ + setError(response, "当前无登录用户,无查看权限"); + return; + } + + Set adminUserIdList = new HashSet<>(UserService.getInstance().getAdminUserIdList()); + if(StringUtils.isBlank(let) || adminUserIdList.contains(user.getId())){ + next(request,response,chain); + return; + } + if (!let.startsWith("/")) { + let = "/" + let; + } + LogUtils.debug4plugin("current report is {}",let); + List roles = CustomRoleService.getInstance().getCustomRolesByUser(user.getId()); + LogUtils.debug4plugin("current user {} role is {}",user.getUserName(),roles); + if (roles == null || roles.isEmpty()) { + setError(response, "当前用户无相关角色权限"); + return; + } + Set paths = RolePathAuthService.getPathsByRole(roles.stream().map(CustomRole::getId).collect(Collectors.toSet())); + LogUtils.debug4plugin("current user {} role is {}",user.getUserName(),paths); + if (!paths.contains(let)) { + setError(response, "当前用户角色无模板权限"); + return; + } + next(request, response, chain); + } catch (Exception e) { + LogUtils.error(e.getMessage(),e); + } + } + + private String getlet(HttpServletRequest request) { + String let = WebUtils.getReportTitleFromRequest(request); + if(StringUtils.isNotBlank(let)){ + return let; + } + String requestURI = request.getRequestURI(); + if(!requestURI.contains("/v10/entry/access/")){ + return StringUtils.EMPTY; + } + String uid = requestURI.substring(requestURI.indexOf("access/") + 7); + Authority authority = null; + try { + authority = (Authority) AuthorityContext.getInstance().getAuthorityController().getById(uid); + } catch (Exception e) { + + } + if(authority != null ){ + return authority.getPath(); + } + return let; + } + + public static void next(HttpServletRequest request, HttpServletResponse response, FilterChain chain) { + try { + chain.doFilter(request, response); + } catch (Exception e) { + FineLoggerFactory.getLogger().error(e.getMessage(), e); + } + } + + @Override + public String filterName() { + return "sso"; + } + + @Override + public String[] urlPatterns() { + if (!PluginContexts.currentContext().isAvailable()) { + LogUtils.error("未注册或禁用"); + return new String[]{"/neverbeused"}; + } + return new String[]{ + "/decision", + "/decision/view/report", + "/decision/view/form", + "/decision/v10/entry/access/*" + }; + } + + private void setError(HttpServletResponse res, String reason) { + try { + PrintWriter printWriter = WebUtils.createPrintWriter(res); + Map map = new HashMap<>(); + map.put("result", InterProviderFactory.getProvider().getLocText("Fine-Engine_Error_Page_Result")); + map.put("reason", reason); + map.put("solution", InterProviderFactory.getProvider().getLocText("Fine-Engine_Please_Contact_Platform_Admin")); + String page = WebServiceUtils.parseWebPageResourceSafe("com/fr/web/controller/decision/entrance/resources/unavailable.html", map); + printWriter.write(page); + printWriter.flush(); + printWriter.close(); + } catch (Exception e) { + FineLoggerFactory.getLogger().error(e.getMessage(), e); + } + } + +} diff --git a/src/main/java/com/fr/plugin/xx/ltqc/auth/Constants.java b/src/main/java/com/fr/plugin/xx/ltqc/auth/Constants.java new file mode 100644 index 0000000..694d0ed --- /dev/null +++ b/src/main/java/com/fr/plugin/xx/ltqc/auth/Constants.java @@ -0,0 +1,13 @@ +package com.fr.plugin.xx.ltqc.auth; + +/** + * @author xx + * @date 2020/5/14 + */ +public class Constants { + public static final String PLUGIN_ID = "com.fr.plugin.xx.ltqc.auth"; + + public static final String PLUGIN_NAME= "门户集成"; + + public static final String ROOT = "/reportlets"; +} diff --git a/src/main/java/com/fr/plugin/xx/ltqc/auth/LRGT.java b/src/main/java/com/fr/plugin/xx/ltqc/auth/LRGT.java new file mode 100644 index 0000000..c445676 --- /dev/null +++ b/src/main/java/com/fr/plugin/xx/ltqc/auth/LRGT.java @@ -0,0 +1,27 @@ +package com.fr.plugin.xx.ltqc.auth; + +import com.fr.plugin.context.PluginContext; +import com.fr.plugin.xx.ltqc.auth.conf.AuthSsoConfig; +import com.fr.plugin.observer.inner.AbstractPluginLifecycleMonitor; + +/** + * @author xx + * @since 2022/01/13 + */ +public class LRGT extends AbstractPluginLifecycleMonitor { + @Override + public void afterRun(PluginContext pluginContext) { + AuthSsoConfig.getInstance(); + } + + @Override + public void beforeStop(PluginContext pluginContext) { + } + @Override + public void beforeUninstall(PluginContext pluginContext) { + } + + @Override + public void afterInstall(PluginContext var1) { + } +} \ No newline at end of file diff --git a/src/main/java/com/fr/plugin/xx/ltqc/auth/RemoteFilter.java b/src/main/java/com/fr/plugin/xx/ltqc/auth/RemoteFilter.java new file mode 100644 index 0000000..4719b8d --- /dev/null +++ b/src/main/java/com/fr/plugin/xx/ltqc/auth/RemoteFilter.java @@ -0,0 +1,122 @@ +package com.fr.plugin.xx.ltqc.auth; + +import com.fr.data.NetworkHelper; +import com.fr.decision.authority.data.User; +import com.fr.decision.fun.impl.AbstractGlobalRequestFilterProvider; +import com.fr.decision.webservice.Response; +import com.fr.decision.webservice.exception.login.UserPwdErrorException; +import com.fr.decision.webservice.exception.user.UserNotExistException; +import com.fr.decision.webservice.v10.remote.RemoteDesignStatusService; +import com.fr.decision.webservice.v10.user.UserService; +import com.fr.exception.RemoteDesignPermissionDeniedException; +import com.fr.general.ComparatorUtils; +import com.fr.json.JSONObject; +import com.fr.plugin.xx.ltqc.auth.conf.AuthSsoConfig; +import com.fr.plugin.xx.ltqc.auth.utils.CommonUtils; +import com.fr.plugin.xx.ltqc.auth.utils.HttpUtil; +import com.fr.plugin.xx.ltqc.auth.utils.LogUtils; +import com.fr.security.JwtUtils; +import com.fr.security.SecurityToolbox; +import com.fr.security.encryption.mode.EncryptionMode; +import com.fr.security.encryption.storage.StorageEncryptors; +import com.fr.stable.StringUtils; +import com.fr.web.service.RemoteDesignAuthorityDataService; +import com.fr.web.utils.WebUtils; + +import javax.servlet.FilterChain; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.util.HashMap; +import java.util.Map; + +/** + * @Author xx + * @Date 2022/5/9 + * @Description + **/ +public class RemoteFilter extends AbstractGlobalRequestFilterProvider { + @Override + public String filterName() { + return "design"; + } + + @Override + public String[] urlPatterns() { + return new String[]{"/decision/remote/design/token"}; + } + + @Override + public void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain filterChain) { + LogUtils.debug4plugin("捕获到远程设计器请求"); + try { + String username, password, compatibleParameters0; + if (StringUtils.equalsIgnoreCase(req.getMethod(), "GET")) { + username = NetworkHelper.getHTTPRequestParameter(req, "username"); + password = NetworkHelper.getHTTPRequestParameter(req, "password"); + compatibleParameters0 = NetworkHelper.getHTTPRequestParameter(req, "compatibleParameters0"); + } else { + username = NetworkHelper.getHTTPRequestParameter(req, "username"); + password = SecurityToolbox.defaultDecrypt(NetworkHelper.getHTTPRequestParameter(req, "password")); + compatibleParameters0 = NetworkHelper.getHTTPRequestParameter(req, "compatibleParameters0"); + } + if (StringUtils.isEmpty(compatibleParameters0) && !ComparatorUtils.equals(StorageEncryptors.getInstance().getCurrentEncryptionMode(), EncryptionMode.RSA)) { + throw new RemoteDesignPermissionDeniedException(); + } + String token = StringUtils.EMPTY; + Map loginParam = new HashMap<>(); + loginParam.put("username", username); + loginParam.put("password", password); + String loginRes = HttpUtil.doFormPost(AuthSsoConfig.getInstance().getEnvUrl(), null, loginParam, "UTF-8"); + LogUtils.debug4plugin("login res is {}", loginRes); + JSONObject loginObject = new JSONObject(loginRes); + if (loginObject.has("data") && loginObject.getInt("__statusCode") == 1) { + token = loginObject.getString("data"); + } else { + throw new UserPwdErrorException(); + } + LogUtils.debug4plugin("get token is {}",token); + String validateUser = StringUtils.EMPTY; + Map param = new HashMap<>(); + param.put("ticketValue", token); + String result = HttpUtil.sendGet(AuthSsoConfig.getInstance().getValidateUrl(), param, null); + LogUtils.debug4plugin("validate cookie url is {}, param is {}, res is {}", AuthSsoConfig.getInstance().getValidateUrl(), param, res); + JSONObject object = new JSONObject(result); + if (object.has("data")) { + validateUser = object.getString("data"); + if (CommonUtils.checkUser(validateUser)) { + login(res, username); + } else { + throw new UserNotExistException(); + } + } + } catch (RemoteDesignPermissionDeniedException | UserNotExistException | UserPwdErrorException e) { + setRes(res, Response.error(e.errorCode(), e.getMessage())); + } catch (Exception e) { + LogUtils.error(e.getMessage(), e); + } + } + + private void login(HttpServletResponse res, String username) throws Exception { + User user = UserService.getInstance().getUserByUserName(username); + if (user != null && RemoteDesignAuthorityDataService.getInstance().hasAuthority(user.getId())) { + setRes(res, Response.ok(this.generateToken(username))); + } else { + throw new RemoteDesignPermissionDeniedException(); + } + } + + private void setRes(HttpServletResponse res, Response body) { + try { + res.setContentType("application/json"); + WebUtils.printAsJSON(res, JSONObject.mapFrom(body)); + } catch (Exception e) { + LogUtils.error(e.getMessage(), e); + } + } + + private String generateToken(String username) throws Exception { + String jwt = JwtUtils.createDefaultJWT(username); + RemoteDesignStatusService.loginStatusService().put(jwt, username, 1209600000); + return jwt; + } +} diff --git a/src/main/java/com/fr/plugin/xx/ltqc/auth/RequestHandlerBridge.java b/src/main/java/com/fr/plugin/xx/ltqc/auth/RequestHandlerBridge.java new file mode 100644 index 0000000..db12357 --- /dev/null +++ b/src/main/java/com/fr/plugin/xx/ltqc/auth/RequestHandlerBridge.java @@ -0,0 +1,26 @@ +package com.fr.plugin.xx.ltqc.auth; + +import com.fr.decision.fun.HttpHandler; +import com.fr.decision.fun.impl.AbstractHttpHandlerProvider; +import com.fr.plugin.xx.ltqc.auth.handler.*; +import com.fr.plugin.transform.FunctionRecorder; +import com.fr.stable.fun.Authorize; + +/** + * @author xx + * @since 2021/07/28 + */ +@FunctionRecorder +@Authorize(callSignKey = Constants.PLUGIN_ID) +public class RequestHandlerBridge extends AbstractHttpHandlerProvider { + @Override + public HttpHandler[] registerHandlers() { + return new HttpHandler[]{ + new CptListHandler(), + new AddRoleHandler(), + new DelRoleHandler(), + new EditRoleHandler(), + new AddUserHandler(), + }; + } +} diff --git a/src/main/java/com/fr/plugin/xx/ltqc/auth/RequestURLAliasBridge.java b/src/main/java/com/fr/plugin/xx/ltqc/auth/RequestURLAliasBridge.java new file mode 100644 index 0000000..c484ed2 --- /dev/null +++ b/src/main/java/com/fr/plugin/xx/ltqc/auth/RequestURLAliasBridge.java @@ -0,0 +1,22 @@ +package com.fr.plugin.xx.ltqc.auth; + +import com.fr.decision.fun.impl.AbstractURLAliasProvider; +import com.fr.decision.webservice.url.alias.URLAlias; +import com.fr.decision.webservice.url.alias.URLAliasFactory; + +/** + * @author xx + * @since 2021/07/28 + */ +public class RequestURLAliasBridge extends AbstractURLAliasProvider { + @Override + public URLAlias[] registerAlias() { + return new URLAlias[]{ + URLAliasFactory.createPluginAlias("/cpt/list", "/cpt/list", false), + URLAliasFactory.createPluginAlias("/auth/addRole", "/auth/addRole", false), + URLAliasFactory.createPluginAlias("/auth/editRole", "/auth/editRole", false), + URLAliasFactory.createPluginAlias("/auth/addUser", "/auth/addUser", false), + URLAliasFactory.createPluginAlias("/auth/delRole", "/auth/delRole", false), + }; + } +} diff --git a/src/main/java/com/fr/plugin/xx/ltqc/auth/action/RolePathAuthService.java b/src/main/java/com/fr/plugin/xx/ltqc/auth/action/RolePathAuthService.java new file mode 100644 index 0000000..95144d4 --- /dev/null +++ b/src/main/java/com/fr/plugin/xx/ltqc/auth/action/RolePathAuthService.java @@ -0,0 +1,89 @@ +package com.fr.plugin.xx.ltqc.auth.action; + +import com.fr.plugin.db.PluginDBManager; +import com.fr.plugin.xx.ltqc.auth.AuthDBAccessProvider; +import com.fr.plugin.xx.ltqc.auth.dao.RolePathAuthDao; +import com.fr.plugin.xx.ltqc.auth.entity.RolePathAuthEntity; +import com.fr.plugin.xx.ltqc.auth.utils.LogUtils; +import com.fr.stable.db.action.DBAction; +import com.fr.stable.db.dao.BaseDAO; +import com.fr.stable.db.dao.DAOContext; +import com.fr.stable.db.session.DBSession; +import com.fr.stable.query.QueryFactory; +import com.fr.stable.query.restriction.RestrictionFactory; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +/** + * @Author xx + * @Date 2022/2/14 + * @Description + **/ +public class RolePathAuthService { + + public static void save(List list) { + try { + AuthDBAccessProvider.getDbAccessor().runDMLAction((DBAction) daoContext -> { + save(daoContext.getDAO(RolePathAuthDao.class), list); + return null; + }); + } catch (Exception e) { + LogUtils.debug4plugin(e.getMessage(), e); + } + + } + + + private static void save(BaseDAO dao, List list) { + try { + if (list == null || list.isEmpty()) { + return; + } + DBSession session = PluginDBManager.getInstance().getDbContext().openSession(); + session.beginTransaction();//开始事务 + Set set = list.stream().map(RolePathAuthEntity::getRole).collect(Collectors.toSet()); + dao.remove(QueryFactory.create().addRestriction(RestrictionFactory.in("role", set))); + for (RolePathAuthEntity e : list) { + dao.addOrUpdate(e); + } + session.commitTransaction();//提交 + session.closeSession(); + } catch (Exception e) { + LogUtils.debug4plugin(e.getMessage(), e); + } + + } + + public static Integer delete(String role) { + try { + return AuthDBAccessProvider.getDbAccessor().runDMLAction(new DBAction() { + @Override + public Integer run(DAOContext daoContext) throws Exception { + daoContext.getDAO(RolePathAuthDao.class).remove(QueryFactory.create().addRestriction(RestrictionFactory.eq("role", role))); + return 1; + } + }); + } catch (Exception e) { + LogUtils.debug4plugin(e.getMessage(), e); + } + return 1; + } + + public static Set getPathsByRole(Set ids) { + try { + return AuthDBAccessProvider.getDbAccessor().runDMLAction(daoContext -> { + List list = daoContext.getDAO(RolePathAuthDao.class).find(QueryFactory.create().addRestriction(RestrictionFactory.in("role", ids))); + if (list == null || list.isEmpty()) { + return new HashSet<>(); + } + return list.stream().map(RolePathAuthEntity::getPath).collect(Collectors.toSet()); + }); + } catch (Exception e) { + LogUtils.debug4plugin(e.getMessage(), e); + } + return new HashSet(); + } +} diff --git a/src/main/java/com/fr/plugin/xx/ltqc/auth/conf/AuthSsoConfig.java b/src/main/java/com/fr/plugin/xx/ltqc/auth/conf/AuthSsoConfig.java new file mode 100644 index 0000000..c230563 --- /dev/null +++ b/src/main/java/com/fr/plugin/xx/ltqc/auth/conf/AuthSsoConfig.java @@ -0,0 +1,86 @@ +package com.fr.plugin.xx.ltqc.auth.conf; + +import com.fr.config.*; +import com.fr.config.holder.Conf; +import com.fr.config.holder.factory.Holders; +import com.fr.record.analyzer.EnableMetrics; +import com.fr.stable.StringUtils; + + +/** + * @author xx + * @since 2021/12/04 + */ +@Visualization(category = "门户集成") +@EnableMetrics +public class AuthSsoConfig extends DefaultConfiguration { + + private static volatile AuthSsoConfig config = null; + + public static AuthSsoConfig getInstance() { + if (config == null) { + config = ConfigContext.getConfigInstance(AuthSsoConfig.class); + } + return config; + } + + @Identifier(value = "debugSwitch", name = "插件调试开关", description = "日志调试模式", status = Status.SHOW) + private Conf debugSwitch = Holders.simple(true); + + @Identifier(value = "cookieKey", name = "cookie键值", description = "cookie键值", status = Status.SHOW) + private Conf cookieKey = Holders.simple("VDPUAT"); + + @Identifier(value = "validateUrl", name = "校验地址", description = "校验地址", status = Status.SHOW) + private Conf validateUrl = Holders.simple(""); + + @Identifier(value = "loginUrl", name = "登录接口地址", description = "登录接口地址", status = Status.SHOW) + private Conf envUrl = Holders.simple(""); + + public Boolean getDebugSwitch() { + return this.debugSwitch.get(); + } + + public void setDebugSwitch(Boolean debugSwitch) { + this.debugSwitch.set(debugSwitch); + } + + public String getCookieKey() { + return cookieKey.get(); + } + + public void setCookieKey(String cookieKey) { + this.cookieKey.set(cookieKey); + } + + public String getValidateUrl() { + return validateUrl.get(); + } + + public void setValidateUrl(String validateUrl) { + this.validateUrl.set(validateUrl); + } + + public String getEnvUrl() { + return envUrl.get(); + } + + public void setEnvUrl(String envUrl) { + this.envUrl.set(envUrl); + } + + + @Override + public Object clone() throws CloneNotSupportedException { + AuthSsoConfig cloned = (AuthSsoConfig) super.clone(); + cloned.debugSwitch = (Conf) debugSwitch.clone(); + cloned.cookieKey = (Conf) cookieKey.clone(); + cloned.validateUrl = (Conf) validateUrl.clone(); + cloned.envUrl = (Conf) envUrl.clone(); + return cloned; + } + + + public boolean isConfiged() { + return StringUtils.isNotBlank(cookieKey.get()) && StringUtils.isNotBlank(validateUrl.get()); + } +} diff --git a/src/main/java/com/fr/plugin/xx/ltqc/auth/dao/RolePathAuthDao.java b/src/main/java/com/fr/plugin/xx/ltqc/auth/dao/RolePathAuthDao.java new file mode 100644 index 0000000..e1d8b12 --- /dev/null +++ b/src/main/java/com/fr/plugin/xx/ltqc/auth/dao/RolePathAuthDao.java @@ -0,0 +1,21 @@ +package com.fr.plugin.xx.ltqc.auth.dao; + +import com.fr.plugin.xx.ltqc.auth.entity.RolePathAuthEntity; +import com.fr.stable.db.dao.BaseDAO; +import com.fr.stable.db.session.DAOSession; + +/** + * @Author xx + * @Date 2022/2/14 + * @Description + **/ +public class RolePathAuthDao extends BaseDAO { + public RolePathAuthDao(DAOSession daoSession) { + super(daoSession); + } + + @Override + protected Class getEntityClass() { + return RolePathAuthEntity.class; + } +} diff --git a/src/main/java/com/fr/plugin/xx/ltqc/auth/entity/RolePathAuthEntity.java b/src/main/java/com/fr/plugin/xx/ltqc/auth/entity/RolePathAuthEntity.java new file mode 100644 index 0000000..80d333e --- /dev/null +++ b/src/main/java/com/fr/plugin/xx/ltqc/auth/entity/RolePathAuthEntity.java @@ -0,0 +1,71 @@ +package com.fr.plugin.xx.ltqc.auth.entity; + +import com.fr.stable.db.entity.BaseEntity; +import com.fr.stable.db.entity.TableAssociation; +import com.fr.third.javax.persistence.Column; +import com.fr.third.javax.persistence.Entity; +import com.fr.third.javax.persistence.Table; + +import java.util.Date; + +/** + * @Author xx + * @Date 2022/2/14 + * @Description + **/ +@Entity +@Table(name = "plugin_role_path_auth") //表名 +@TableAssociation(associated = true) +public class RolePathAuthEntity extends BaseEntity { + + @Column(name = "role") + private String role; + @Column(name = "path") + private String path; + @Column(name = "create_time") + private Date createTime; + @Column(name = "create_user") + private String createUser; + + public String getRole() { + return role; + } + + public void setRole(String role) { + this.role = role; + } + + public String getPath() { + return path; + } + + public void setPath(String path) { + this.path = path; + } + + public Date getCreateTime() { + return createTime; + } + + public void setCreateTime(Date createTime) { + this.createTime = createTime; + } + + public String getCreateUser() { + return createUser; + } + + public void setCreateUser(String createUser) { + this.createUser = createUser; + } + + @Override + public String toString() { + return "RolePathAuthEntity{" + + "role='" + role + '\'' + + ", path='" + path + '\'' + + ", createTime=" + createTime + + ", createUser='" + createUser + '\'' + + '}'; + } +} diff --git a/src/main/java/com/fr/plugin/xx/ltqc/auth/handler/AddRoleHandler.java b/src/main/java/com/fr/plugin/xx/ltqc/auth/handler/AddRoleHandler.java new file mode 100644 index 0000000..31cf640 --- /dev/null +++ b/src/main/java/com/fr/plugin/xx/ltqc/auth/handler/AddRoleHandler.java @@ -0,0 +1,169 @@ +package com.fr.plugin.xx.ltqc.auth.handler; + +import com.fr.decision.authority.AuthorityContext; +import com.fr.decision.authority.base.constant.type.operation.ManualOperationType; +import com.fr.decision.authority.data.CustomRole; +import com.fr.decision.authority.data.User; +import com.fr.decision.base.util.UUIDUtil; +import com.fr.decision.fun.impl.BaseHttpHandler; +import com.fr.decision.privilege.encrpt.PasswordValidator; +import com.fr.decision.webservice.bean.user.RoleBean; +import com.fr.decision.webservice.bean.user.UserBean; +import com.fr.decision.webservice.utils.UserSourceFactory; +import com.fr.decision.webservice.v10.user.CustomRoleService; +import com.fr.decision.webservice.v10.user.UserService; +import com.fr.io.utils.ResourceIOUtils; +import com.fr.json.JSONArray; +import com.fr.json.JSONObject; +import com.fr.plugin.xx.ltqc.auth.Constants; +import com.fr.plugin.xx.ltqc.auth.action.RolePathAuthService; +import com.fr.plugin.xx.ltqc.auth.entity.RolePathAuthEntity; +import com.fr.plugin.xx.ltqc.auth.utils.LogUtils; +import com.fr.third.springframework.web.bind.annotation.RequestMethod; +import com.fr.web.utils.WebUtils; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.BufferedReader; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.UUID; +import java.util.stream.Collectors; + +/** + * @Author xx + * @Date 2022/2/13 + * @Description + **/ +public class AddRoleHandler extends BaseHttpHandler { + + + @Override + public RequestMethod getMethod() { + return RequestMethod.POST; + } + + @Override + public String getPath() { + return "/auth/addRole"; + } + + @Override + public boolean isPublic() { + return false; + } + + @Override + public void handle(HttpServletRequest req, HttpServletResponse res) { + try { + res.setContentType("application/json; charset=UTF-8"); + JSONObject body = parseRequest(req); + String admin = UserService.getInstance().getAdminUserIdList().get(0); + User user = UserService.getInstance().getUserByRequestCookie(req); + if (body == null || body.isEmpty()) { + WebUtils.printAsJSON(res, error("body is not null")); + return; + } + if (!body.has("roles")) { + WebUtils.printAsJSON(res, error("role is not null")); + return; + } + JSONObject role = body.getJSONObject("roles"); + RoleBean roleBean = new RoleBean(); + roleBean.setText(role.getString("text")); + roleBean.setId(role.getString("id")); + roleBean.setDescription(role.getString("description")); + RoleBean customRole = CustomRoleService.getInstance().getCustomRole(roleBean.getId()); + CustomRole customRole1 = (new CustomRole()).id(roleBean.getId()).name(roleBean.getText()).description(roleBean.getDescription()).creationType(ManualOperationType.KEY).lastOperationType(ManualOperationType.KEY).enable(true); + if (customRole == null) { + LogUtils.debug4plugin("add role {}", customRole1); + AuthorityContext.getInstance().getCustomRoleController().add(customRole1); + } else { + LogUtils.debug4plugin("edit role {}", customRole1); + AuthorityContext.getInstance().getCustomRoleController().update(customRole1); + } + + JSONArray users = body.getJSONArray("users"); + for (int i = 0; i < users.size(); i++) { + JSONObject object = users.getJSONObject(i); + String id = object.getString("id"); + User getUser = UserService.getInstance().getUserByUserId(id); + UserBean userBean = new UserBean(); + userBean.setUsername(object.getString("userName")); + userBean.setRealName(object.getString("realName")); + userBean.setEmail(object.getString("email")); + userBean.setMobile(object.getString("mobile")); + userBean.setId(id); + List roles = UserService.getInstance().getTargetUserRoles(admin, id); + if (roles != null) { + List ids = roles.stream().map(RoleBean::getId).collect(Collectors.toList()); + ids.add(roleBean.getId()); + userBean.setRoleIds(ids.toArray(new String[0])); + } else { + userBean.setRoleIds(new String[]{roleBean.getId()}); + } + User user1 = (new User()).id(userBean.getId()).userName(userBean.getUsername()).realName(userBean.getRealName()).email(userBean.getEmail()).mobile(userBean.getMobile()).creationType(ManualOperationType.KEY).lastOperationType(ManualOperationType.KEY).enable(true); + if (getUser == null) { + userBean.setPassword(UUID.randomUUID().toString()); + String uuid = UUIDUtil.generate(); + PasswordValidator validator = UserSourceFactory.getInstance().getUserSource(ManualOperationType.KEY).getPasswordValidator(); + user1.password(validator.encode(userBean.getUsername(), userBean.getPassword(), uuid)).salt(uuid); + LogUtils.debug4plugin("add user {}", user1); + AuthorityContext.getInstance().getUserController().add(user1); + } else { + getUser.userName(userBean.getUsername()).realName(userBean.getRealName()).email(userBean.getEmail()).mobile(userBean.getMobile()).creationType(ManualOperationType.KEY).lastOperationType(ManualOperationType.KEY).enable(true); + LogUtils.debug4plugin("edit user {}", getUser); + AuthorityContext.getInstance().getUserController().update(getUser); + } + UserService.getInstance().updateUserRoles(admin, userBean); + } + + JSONArray paths = body.getJSONArray("paths"); + List saves = new ArrayList<>(); + for (int j = 0; j < paths.size(); j++) { + JSONObject path = paths.getJSONObject(j); + String realPath = Constants.ROOT + path.getString("path"); + if (!ResourceIOUtils.exist(realPath)) { + WebUtils.printAsJSON(res, error(String.format("cpt %s not exist", path))); + return; + } + RolePathAuthEntity entity = new RolePathAuthEntity(); + entity.setId(UUID.randomUUID().toString()); + entity.setRole(roleBean.getId()); + entity.setPath(path.getString("path")); + entity.setCreateUser(user.getId()); + entity.setCreateTime(new Date()); + saves.add(entity); + } + LogUtils.debug4plugin("save role {} to paths {}", roleBean.getText(), saves.stream().map(e -> e.getPath()).collect(Collectors.joining(","))); + RolePathAuthService.save(saves); + WebUtils.printAsJSON(res, JSONObject.create().put("state", 0)); + } catch (Exception e) { + LogUtils.error(e.getMessage(), e); + try { + WebUtils.printAsJSON(res, error(e.getMessage())); + } catch (Exception ex) { + LogUtils.error(ex.getMessage(), ex); + } + } + } + + private JSONObject error(String mess) { + return JSONObject.create().put("state", 1).put("mess", mess); + } + + private JSONObject parseRequest(HttpServletRequest request) { + try { + BufferedReader br = request.getReader(); + String str = ""; + String listString = ""; + while ((str = br.readLine()) != null) { + listString += str; + } + return new JSONObject(listString); + } catch (Exception e) { + return new JSONObject(); + } + } +} diff --git a/src/main/java/com/fr/plugin/xx/ltqc/auth/handler/AddUserHandler.java b/src/main/java/com/fr/plugin/xx/ltqc/auth/handler/AddUserHandler.java new file mode 100644 index 0000000..b82c24f --- /dev/null +++ b/src/main/java/com/fr/plugin/xx/ltqc/auth/handler/AddUserHandler.java @@ -0,0 +1,123 @@ +package com.fr.plugin.xx.ltqc.auth.handler; + +import com.fr.decision.authority.AuthorityContext; +import com.fr.decision.authority.base.constant.type.operation.ManualOperationType; +import com.fr.decision.authority.data.CustomRole; +import com.fr.decision.authority.data.User; +import com.fr.decision.base.util.UUIDUtil; +import com.fr.decision.fun.impl.BaseHttpHandler; +import com.fr.decision.privilege.encrpt.PasswordValidator; +import com.fr.decision.webservice.bean.user.UserBean; +import com.fr.decision.webservice.bean.user.UserUpdateBean; +import com.fr.decision.webservice.utils.UserSourceFactory; +import com.fr.decision.webservice.v10.user.CustomRoleService; +import com.fr.decision.webservice.v10.user.UserService; +import com.fr.json.JSONObject; +import com.fr.plugin.xx.ltqc.auth.utils.LogUtils; +import com.fr.stable.StringUtils; +import com.fr.third.springframework.web.bind.annotation.RequestMethod; +import com.fr.web.utils.WebUtils; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.BufferedReader; +import java.util.List; +import java.util.UUID; + +/** + * @Author xx + * @Date 2022/2/13 + * @Description + **/ +public class AddUserHandler extends BaseHttpHandler { + + + @Override + public RequestMethod getMethod() { + return RequestMethod.POST; + } + + @Override + public String getPath() { + return "/auth/addUser"; + } + + @Override + public boolean isPublic() { + return false; + } + + @Override + public void handle(HttpServletRequest req, HttpServletResponse res) { + try { + res.setContentType("application/json; charset=UTF-8"); + JSONObject body = parseRequest(req); + String admin = UserService.getInstance().getAdminUserIdList().get(0); + if (body == null || body.isEmpty()) { + WebUtils.printAsJSON(res, error("body is not null")); + return; + } + String id = body.getString("id"); + User getUser = UserService.getInstance().getUserByUserId(id); + UserBean userBean = new UserBean(); + userBean.setUsername(body.getString("userName")); + userBean.setRealName(body.getString("realName")); + userBean.setEmail(body.getString("email")); + userBean.setMobile(body.getString("mobile")); + userBean.setId(id); + String roleId = body.getString("roleId"); + if (StringUtils.isNotBlank(roleId)) { + userBean.setRoleIds(roleId.split(",")); + } + User user1 = (new User()).id(userBean.getId()).userName(userBean.getUsername()).realName(userBean.getRealName()).email(userBean.getEmail()).mobile(userBean.getMobile()).creationType(ManualOperationType.KEY).lastOperationType(ManualOperationType.KEY).enable(true); + if (getUser == null) { + userBean.setPassword(UUID.randomUUID().toString()); + String uuid = UUIDUtil.generate(); + PasswordValidator validator = UserSourceFactory.getInstance().getUserSource(ManualOperationType.KEY).getPasswordValidator(); + user1.password(validator.encode(userBean.getUsername(), userBean.getPassword(), uuid)).salt(uuid); + AuthorityContext.getInstance().getUserController().add(user1); + } else { + getUser.userName(userBean.getUsername()).realName(userBean.getRealName()).email(userBean.getEmail()).mobile(userBean.getMobile()).creationType(ManualOperationType.KEY).lastOperationType(ManualOperationType.KEY).enable(true); + AuthorityContext.getInstance().getUserController().update(getUser); + } + LogUtils.debug4plugin("delete roles by user is {}",user1.getId()); + List customRolesByUser = CustomRoleService.getInstance().getCustomRolesByUser(user1.getId()); + for (CustomRole role : customRolesByUser){ + UserUpdateBean userUpdateBean = new UserUpdateBean(); + userUpdateBean.setRemoveUserIds(new String[]{user1.getId()}); + UserService.getInstance().updateRoleUsers(role.getId(), userUpdateBean); + } + /*AuthDBAccessProvider.getDbAccessor().runQueryAction((DBAction) daoContext -> { + daoContext.getDAO(UserRoleMiddleDAO.class).remove(QueryFactory.create().addRestriction(RestrictionFactory.eq("userId", user1.getId())).addRestriction(RestrictionFactory.eq("roleType", RoleType.CUSTOM))); + return null; + });*/ + UserService.getInstance().updateUserRoles(admin, userBean); + WebUtils.printAsJSON(res, JSONObject.create().put("state", 0)); + } catch (Exception e) { + LogUtils.error(e.getMessage(), e); + try { + WebUtils.printAsJSON(res, error(e.getMessage())); + } catch (Exception ex) { + LogUtils.error(ex.getMessage(), ex); + } + } + } + + private JSONObject error(String mess) { + return JSONObject.create().put("state", 1).put("mess", mess); + } + + private JSONObject parseRequest(HttpServletRequest request) { + try { + BufferedReader br = request.getReader(); + String str = ""; + String listString = ""; + while ((str = br.readLine()) != null) { + listString += str; + } + return new JSONObject(listString); + } catch (Exception e) { + return new JSONObject(); + } + } +} diff --git a/src/main/java/com/fr/plugin/xx/ltqc/auth/handler/CptListHandler.java b/src/main/java/com/fr/plugin/xx/ltqc/auth/handler/CptListHandler.java new file mode 100644 index 0000000..b3dca22 --- /dev/null +++ b/src/main/java/com/fr/plugin/xx/ltqc/auth/handler/CptListHandler.java @@ -0,0 +1,66 @@ +package com.fr.plugin.xx.ltqc.auth.handler; + +import com.fr.decision.fun.impl.BaseHttpHandler; +import com.fr.io.utils.ResourceIOUtils; +import com.fr.json.JSONArray; +import com.fr.json.JSONObject; +import com.fr.plugin.xx.ltqc.auth.Constants; +import com.fr.third.guava.io.Files; +import com.fr.third.springframework.web.bind.annotation.RequestMethod; +import com.fr.web.utils.WebUtils; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.File; + +/** + * @Author xx + * @Date 2022/2/13 + * @Description + **/ +public class CptListHandler extends BaseHttpHandler { + + @Override + public RequestMethod getMethod() { + return RequestMethod.GET; + } + + @Override + public String getPath() { + return "/cpt/list"; + } + + @Override + public boolean isPublic() { + return false; + } + + @Override + public void handle(HttpServletRequest request, HttpServletResponse response) throws Exception { + JSONObject object = new JSONObject(); + JSONArray path = getLetPath(Constants.ROOT); + object.put("state", 0); + object.put("data", path); + response.setContentType("application/json; charset=UTF-8"); + WebUtils.printAsJSON(response, object); + } + + private JSONArray getLetPath(String path) { + JSONArray array = new JSONArray(); + String[] list = ResourceIOUtils.list(path); + for (String name : list) { + String curr = path + File.separator + name; + if (ResourceIOUtils.isDirectory(curr)) { + JSONArray childPath = getLetPath(curr); + if (childPath != null || childPath.length() != 0) { + for (int i = 0; i < childPath.length(); i++) { + array.put(childPath.getJSONObject(i)); + } + } + } else if ("cpt,frm".contains(Files.getFileExtension(curr))) { + array.put(JSONObject.create().put("path", curr.replace(Constants.ROOT, ""))); + } + } + return array; + } +} diff --git a/src/main/java/com/fr/plugin/xx/ltqc/auth/handler/DelRoleHandler.java b/src/main/java/com/fr/plugin/xx/ltqc/auth/handler/DelRoleHandler.java new file mode 100644 index 0000000..76288c5 --- /dev/null +++ b/src/main/java/com/fr/plugin/xx/ltqc/auth/handler/DelRoleHandler.java @@ -0,0 +1,70 @@ +package com.fr.plugin.xx.ltqc.auth.handler; + +import com.fr.decision.authority.AuthorityContext; +import com.fr.decision.authority.data.CustomRole; +import com.fr.decision.fun.impl.BaseHttpHandler; +import com.fr.decision.webservice.v10.user.CustomRoleService; +import com.fr.json.JSONObject; +import com.fr.plugin.xx.ltqc.auth.action.RolePathAuthService; +import com.fr.plugin.xx.ltqc.auth.utils.LogUtils; +import com.fr.stable.StringUtils; +import com.fr.third.springframework.web.bind.annotation.RequestMethod; +import com.fr.web.utils.WebUtils; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +/** + * @Author xx + * @Date 2022/2/13 + * @Description + **/ +public class DelRoleHandler extends BaseHttpHandler { + + @Override + public RequestMethod getMethod() { + return RequestMethod.GET; + } + + @Override + public String getPath() { + return "/auth/delRole"; + } + + @Override + public boolean isPublic() { + return false; + } + + @Override + public void handle(HttpServletRequest req, HttpServletResponse res) { + try { + res.setContentType("application/json; charset=UTF-8"); + String role = WebUtils.getHTTPRequestParameter(req, "role"); + CustomRole customRoles = AuthorityContext.getInstance().getCustomRoleController().getById(role); + if (StringUtils.isBlank(role)) { + WebUtils.printAsJSON(res, error("role is not null")); + return; + } + if (customRoles == null) { + WebUtils.printAsJSON(res, error(String.format("role %s not exist", role))); + return; + } + CustomRoleService.getInstance().deleteCustomRole(role); + RolePathAuthService.delete(role); + WebUtils.printAsJSON(res, JSONObject.create().put("state", 0)); + } catch (Exception e) { + LogUtils.error(e.getMessage(), e); + try { + WebUtils.printAsJSON(res, error(e.getMessage())); + } catch (Exception ex) { + LogUtils.error(ex.getMessage(), ex); + } + } + } + + private JSONObject error(String mess) { + return JSONObject.create().put("state", 1).put("mess", mess); + } + +} diff --git a/src/main/java/com/fr/plugin/xx/ltqc/auth/handler/EditRoleHandler.java b/src/main/java/com/fr/plugin/xx/ltqc/auth/handler/EditRoleHandler.java new file mode 100644 index 0000000..2d96764 --- /dev/null +++ b/src/main/java/com/fr/plugin/xx/ltqc/auth/handler/EditRoleHandler.java @@ -0,0 +1,173 @@ +package com.fr.plugin.xx.ltqc.auth.handler; + +import com.fr.decision.authority.AuthorityContext; +import com.fr.decision.authority.base.constant.type.operation.ManualOperationType; +import com.fr.decision.authority.data.CustomRole; +import com.fr.decision.authority.data.User; +import com.fr.decision.base.util.UUIDUtil; +import com.fr.decision.fun.impl.BaseHttpHandler; +import com.fr.decision.privilege.encrpt.PasswordValidator; +import com.fr.decision.webservice.bean.user.RoleBean; +import com.fr.decision.webservice.bean.user.UserBean; +import com.fr.decision.webservice.bean.user.UserUpdateBean; +import com.fr.decision.webservice.utils.UserSourceFactory; +import com.fr.decision.webservice.v10.user.CustomRoleService; +import com.fr.decision.webservice.v10.user.UserService; +import com.fr.io.utils.ResourceIOUtils; +import com.fr.json.JSONArray; +import com.fr.json.JSONObject; +import com.fr.plugin.xx.ltqc.auth.Constants; +import com.fr.plugin.xx.ltqc.auth.action.RolePathAuthService; +import com.fr.plugin.xx.ltqc.auth.entity.RolePathAuthEntity; +import com.fr.plugin.xx.ltqc.auth.utils.LogUtils; +import com.fr.stable.query.QueryFactory; +import com.fr.stable.query.data.DataList; +import com.fr.third.springframework.web.bind.annotation.RequestMethod; +import com.fr.web.utils.WebUtils; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.BufferedReader; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.UUID; +import java.util.stream.Collectors; + +/** + * @Author xx + * @Date 2022/2/13 + * @Description + **/ +public class EditRoleHandler extends BaseHttpHandler { + + + @Override + public RequestMethod getMethod() { + return RequestMethod.POST; + } + + @Override + public String getPath() { + return "/auth/editRole"; + } + + @Override + public boolean isPublic() { + return false; + } + + @Override + public void handle(HttpServletRequest req, HttpServletResponse res) { + try { + res.setContentType("application/json; charset=UTF-8"); + JSONObject body = parseRequest(req); + String admin = UserService.getInstance().getAdminUserIdList().get(0); + User user = UserService.getInstance().getUserByRequestCookie(req); + if (body == null || body.isEmpty()) { + WebUtils.printAsJSON(res, error("body is not null")); + return; + } + if (!body.has("roles")) { + WebUtils.printAsJSON(res, error("role is not null")); + return; + } + JSONObject role = body.getJSONObject("roles"); + RoleBean roleBean = new RoleBean(); + roleBean.setText(role.getString("text")); + roleBean.setId(role.getString("id")); + roleBean.setDescription(role.getString("description")); + RoleBean customRole = CustomRoleService.getInstance().getCustomRole(roleBean.getId()); + CustomRole customRole1 = (new CustomRole()).id(roleBean.getId()).name(roleBean.getText()).description(roleBean.getDescription()).creationType(ManualOperationType.KEY).lastOperationType(ManualOperationType.KEY).enable(true); + if (customRole == null) { + AuthorityContext.getInstance().getCustomRoleController().add(customRole1); + } else { + AuthorityContext.getInstance().getCustomRoleController().update(customRole1); + } + //删除所有的用户 + LogUtils.debug4plugin("delete roles by roles is {}",customRole.getId()); + DataList roleUser = AuthorityContext.getInstance().getUserController().findByCustomRole(customRole.getId(), QueryFactory.create()); + UserUpdateBean userUpdateBean = new UserUpdateBean(); + userUpdateBean.setRemoveUserIds(roleUser.getList().stream().map(User::getId).collect(Collectors.toList()).toArray(new String[0])); + UserService.getInstance().updateRoleUsers(customRole.getId(), userUpdateBean); + + JSONArray users = body.getJSONArray("users"); + for (int i = 0; i < users.size(); i++) { + JSONObject object = users.getJSONObject(i); + String id = object.getString("id"); + User getUser = UserService.getInstance().getUserByUserId(id); + UserBean userBean = new UserBean(); + userBean.setUsername(object.getString("userName")); + userBean.setRealName(object.getString("realName")); + userBean.setEmail(object.getString("email")); + userBean.setMobile(object.getString("mobile")); + userBean.setId(id); + List roles = UserService.getInstance().getTargetUserRoles(admin, id); + if (roles != null) { + List ids = roles.stream().map(RoleBean::getId).collect(Collectors.toList()); + ids.add(roleBean.getId()); + userBean.setRoleIds(ids.toArray(new String[0])); + } else { + userBean.setRoleIds(new String[]{roleBean.getId()}); + } + User user1 = (new User()).id(userBean.getId()).userName(userBean.getUsername()).realName(userBean.getRealName()).email(userBean.getEmail()).mobile(userBean.getMobile()).creationType(ManualOperationType.KEY).lastOperationType(ManualOperationType.KEY).enable(true); + if (getUser == null) { + userBean.setPassword(UUID.randomUUID().toString()); + String uuid = UUIDUtil.generate(); + PasswordValidator validator = UserSourceFactory.getInstance().getUserSource(ManualOperationType.KEY).getPasswordValidator(); + user1.password(validator.encode(userBean.getUsername(), userBean.getPassword(), uuid)).salt(uuid); + AuthorityContext.getInstance().getUserController().add(user1); + } else { + getUser.userName(userBean.getUsername()).realName(userBean.getRealName()).email(userBean.getEmail()).mobile(userBean.getMobile()).creationType(ManualOperationType.KEY).lastOperationType(ManualOperationType.KEY).enable(true); + AuthorityContext.getInstance().getUserController().update(getUser); + } + UserService.getInstance().updateUserRoles(admin, userBean); + } + + JSONArray paths = body.getJSONArray("paths"); + List saves = new ArrayList<>(); + for (int j = 0; j < paths.size(); j++) { + JSONObject path = paths.getJSONObject(j); + String realPath = Constants.ROOT + path.getString("path"); + if (!ResourceIOUtils.exist(realPath)) { + WebUtils.printAsJSON(res, error(String.format("cpt %s not exist", path))); + return; + } + RolePathAuthEntity entity = new RolePathAuthEntity(); + entity.setId(UUID.randomUUID().toString()); + entity.setRole(roleBean.getId()); + entity.setPath(path.getString("path")); + entity.setCreateUser(user.getId()); + entity.setCreateTime(new Date()); + saves.add(entity); + } + RolePathAuthService.save(saves); + WebUtils.printAsJSON(res, JSONObject.create().put("state", 0)); + } catch (Exception e) { + LogUtils.error(e.getMessage(), e); + try { + WebUtils.printAsJSON(res, error(e.getMessage())); + } catch (Exception ex) { + LogUtils.error(ex.getMessage(), ex); + } + } + } + + private JSONObject error(String mess) { + return JSONObject.create().put("state", 1).put("mess", mess); + } + + private JSONObject parseRequest(HttpServletRequest request) { + try { + BufferedReader br = request.getReader(); + String str = ""; + String listString = ""; + while ((str = br.readLine()) != null) { + listString += str; + } + return new JSONObject(listString); + } catch (Exception e) { + return new JSONObject(); + } + } +} diff --git a/src/main/java/com/fr/plugin/xx/ltqc/auth/utils/CommonUtils.java b/src/main/java/com/fr/plugin/xx/ltqc/auth/utils/CommonUtils.java new file mode 100644 index 0000000..b2b864b --- /dev/null +++ b/src/main/java/com/fr/plugin/xx/ltqc/auth/utils/CommonUtils.java @@ -0,0 +1,139 @@ +package com.fr.plugin.xx.ltqc.auth.utils; + +import com.fr.data.NetworkHelper; +import com.fr.decision.authority.data.User; +import com.fr.decision.mobile.terminal.TerminalHandler; +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.TokenResource; +import com.fr.decision.webservice.v10.user.UserService; +import com.fr.log.FineLoggerFactory; +import com.fr.stable.StringUtils; +import com.fr.stable.web.Device; +import com.fr.web.utils.WebUtils; + +import javax.servlet.FilterChain; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.util.Map; +import java.util.Properties; + +/** + * @author xx + * @since 2021/8/24 + */ +public class CommonUtils { + + public static String getProperty(Properties props, String key, String defaultValue, boolean allowBlank) { + String value = props.getProperty(key); + if (StringUtils.isNotBlank(value)) { + return value; + } else { + if (allowBlank) { + LogUtils.warn("Property[" + key + "] value is blank."); + return defaultValue; + } else { + throw new IllegalArgumentException("Property[" + key + "] cann't be blank."); + } + } + } + + public static String getProperty(Properties props, String key, boolean allowBlank) { + return getProperty(props, key, null, allowBlank); + } + + public static String getProperty(Properties props, String key) { + return getProperty(props, key, null, true); + } + + public static boolean isLogin(HttpServletRequest request) { + String oldToken = TokenResource.COOKIE.getToken(request); + return oldToken != null && checkTokenValid(request, (String) oldToken); + } + + private static boolean checkTokenValid(HttpServletRequest req, String token) { + try { + Device device = NetworkHelper.getDevice(req); + LoginService.getInstance().loginStatusValid(token, TerminalHandler.getTerminal(req, device)); + return true; + } catch (Exception ignore) { + } + return false; + } + + /** + * 跳转到过滤器链中的下一个过滤器 + * + * @param request + * @param response + * @param chain + */ + public static void next(HttpServletRequest request, HttpServletResponse response, FilterChain chain) { + try { + chain.doFilter(request, response); + } catch (Exception e) { + FineLoggerFactory.getLogger().error(e.getMessage(),e); + } + } + + public static void login(String username, HttpServletRequest request, HttpServletResponse response) { + try { + User user = UserService.getInstance().getUserByUserName(username); + String token = LoginService.getInstance().login(request, response, user.getUserName()); + request.setAttribute(DecisionServiceConstants.FINE_AUTH_TOKEN_NAME, token); + } catch (Exception e) { + FineLoggerFactory.getLogger().error("sso >> Failed to login with[" + username + "]", e); + } + } + + public static boolean checkUser(String username) { + try { + User user = UserService.getInstance().getUserByUserName(username); + return user != null; + } catch (Exception e) { + FineLoggerFactory.getLogger().error(e.getMessage(),e); + } + return false; + } + + + public static boolean isMobileDevice(HttpServletRequest request) { + if (WebUtils.getDevice(request).isMobile()) { + LogUtils.debug4plugin("current request is is mobile request ,url is {}", request.getRequestURI()); + return true; + } + String requestHeader = request.getHeader("user-agent"); + String[] deviceArray = new String[]{"android", "iphone", "ipad", "ios", "windows phone", "wechat"}; + if (requestHeader == null) { + return false; + } + requestHeader = requestHeader.toLowerCase(); + for (int i = 0; i < deviceArray.length; i++) { + if (requestHeader.toLowerCase().contains(deviceArray[i])) { + LogUtils.debug4plugin("current request:{} is mobile request!", request.getRequestURI()); + return true; + } + } + String op = WebUtils.getHTTPRequestParameter(request, "op"); + return StringUtils.isNotBlank(op) && StringUtils.equals("h5", op); + } + + public static void cacheParams(String key, Map values) { + try { + DecisionStatusService.originUrlStatusService().put(key, values); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + public static String getCachedParam(String key, String name) { + try { + Map values = DecisionStatusService.originUrlStatusService().get(key); + return values.get(name); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + +} diff --git a/src/main/java/com/fr/plugin/xx/ltqc/auth/utils/CookieUtils.java b/src/main/java/com/fr/plugin/xx/ltqc/auth/utils/CookieUtils.java new file mode 100644 index 0000000..d5a530f --- /dev/null +++ b/src/main/java/com/fr/plugin/xx/ltqc/auth/utils/CookieUtils.java @@ -0,0 +1,58 @@ +package com.fr.plugin.xx.ltqc.auth.utils; + + +import com.fr.stable.StringUtils; + +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + + +/** + * @author xx + * @since 2022/02/14 + */ +public class CookieUtils { + + /** + * 根据name获取cookie + * @param request + * @param name + * @return cookie对象 + */ + public static Cookie getCookie(HttpServletRequest request, String name) { + Cookie[] cookies = request.getCookies(); + if (cookies == null || name == null || name.length() == 0) { + return null; + } + Cookie cookie = null; + for (int i = 0; i < cookies.length; i++) { + if (cookies[i].getName().equals(name)) { + cookie = cookies[i]; + break; + } + } + return cookie; + } + + /** + * 新增cookie,过期时间为页面关闭 + * @param response + * @param name + * @param value + * @param domain + */ + public static void setCookie(HttpServletResponse response, String name, + String value, String domain) { + if (value == null) { + value = ""; + } + Cookie cookie = new Cookie(name, value); + if (!StringUtils.isEmpty(domain)) { + cookie.setDomain(domain); + } + cookie.setPath("/"); + response.addCookie(cookie); + } + +} diff --git a/src/main/java/com/fr/plugin/xx/ltqc/auth/utils/HttpUtil.java b/src/main/java/com/fr/plugin/xx/ltqc/auth/utils/HttpUtil.java new file mode 100644 index 0000000..e34cfe4 --- /dev/null +++ b/src/main/java/com/fr/plugin/xx/ltqc/auth/utils/HttpUtil.java @@ -0,0 +1,330 @@ +package com.fr.plugin.xx.ltqc.auth.utils; + +import com.fr.json.JSONObject; +import com.fr.log.FineLoggerFactory; +import com.fr.stable.StringUtils; +import com.fr.third.org.apache.http.HttpResponse; +import com.fr.third.org.apache.http.HttpStatus; +import com.fr.third.org.apache.http.NameValuePair; +import com.fr.third.org.apache.http.client.HttpClient; +import com.fr.third.org.apache.http.client.entity.UrlEncodedFormEntity; +import com.fr.third.org.apache.http.client.methods.HttpPost; +import com.fr.third.org.apache.http.config.Registry; +import com.fr.third.org.apache.http.config.RegistryBuilder; +import com.fr.third.org.apache.http.conn.socket.ConnectionSocketFactory; +import com.fr.third.org.apache.http.conn.socket.LayeredConnectionSocketFactory; +import com.fr.third.org.apache.http.conn.socket.PlainConnectionSocketFactory; +import com.fr.third.org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import com.fr.third.org.apache.http.conn.ssl.SSLContexts; +import com.fr.third.org.apache.http.conn.ssl.TrustStrategy; +import com.fr.third.org.apache.http.impl.client.CloseableHttpClient; +import com.fr.third.org.apache.http.impl.client.HttpClientBuilder; +import com.fr.third.org.apache.http.impl.conn.PoolingHttpClientConnectionManager; +import com.fr.third.org.apache.http.message.BasicNameValuePair; +import com.fr.third.org.apache.http.util.EntityUtils; + +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.HttpsURLConnection; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSession; +import java.io.*; +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.URLEncoder; +import java.security.KeyManagementException; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.cert.CertificateException; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * @Author hujian + * @Date 2020/12/05 + * @Description + **/ +public class HttpUtil { + + private static HostnameVerifier hv = new HostnameVerifier() { + @Override + public boolean verify(String urlHostName, SSLSession session) { + System.out.println("Warning: URL Host: " + urlHostName + " vs. " + + session.getPeerHost()); + return true; + } + }; + + /** + * 发送get请求 + * + * @param url + * @param param + * @param header + * @return + * @throws IOException + */ + public static String sendGet(String url, Map param, Map header) { + String result = ""; + BufferedReader in = null; + String urlNameString = url; + try { + if (param != null) { + urlNameString += "?"; + urlNameString += param.entrySet() + .stream() + .map(entry -> entry.getKey() + "=" + entry.getValue()) + .collect(Collectors.joining("&")); + } + + URL realUrl = new URL(urlNameString); + // 打开和URL之间的连接 + HttpURLConnection connection; + if (url.startsWith("https")) { + trustAllHttpsCertificates(); + HttpsURLConnection.setDefaultHostnameVerifier(hv); + connection = (HttpURLConnection) realUrl.openConnection(); + } else { + connection = (HttpURLConnection) realUrl.openConnection(); + } + //设置超时时间 + connection.setDoInput(true); + connection.setRequestMethod("GET"); + connection.setConnectTimeout(5000); + connection.setReadTimeout(15000); + // 设置通用的请求属性 + if (header != null) { + Iterator> it = header.entrySet().iterator(); + while (it.hasNext()) { + Map.Entry entry = it.next(); + System.out.println(entry.getKey() + ":::" + entry.getValue()); + connection.setRequestProperty(entry.getKey(), entry.getValue()); + } + } + connection.setRequestProperty("accept", "*/*"); + connection.setRequestProperty("connection", "Keep-Alive"); + connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); + // 建立实际的连接 + connection.connect(); + // 定义 BufferedReader输入流来读取URL的响应,设置utf8防止中文乱码 + in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8")); + String line; + while ((line = in.readLine()) != null) { + result += line; + } + if (in != null) { + in.close(); + } + }catch (Exception e){ + FineLoggerFactory.getLogger().error(e,"get url error ,url is:{},error is {}",urlNameString,e.getMessage()); + } + return result; + } + + public static String sendPost(String url,Map header, JSONObject body) { + PrintWriter out = null; + BufferedReader in = null; + String result = StringUtils.EMPTY; + String res = StringUtils.EMPTY; + try { + String urlNameString = url; + + URL realUrl = new URL(urlNameString); + // 打开和URL之间的连接 + HttpURLConnection conn; + if (url.startsWith("https")) { + trustAllHttpsCertificates(); + HttpsURLConnection.setDefaultHostnameVerifier(hv); + conn = (HttpURLConnection) realUrl.openConnection(); + } else { + conn = (HttpURLConnection) realUrl.openConnection(); + } + // 设置通用的请求属性 + conn.setRequestProperty("accept", "*/*"); + conn.setRequestProperty("connection", "Keep-Alive"); + conn.setRequestProperty("user-agent", + "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); + conn.setRequestProperty("Content-Type","application/json;;charset=UTF-8"); + //conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=----footfoodapplicationrequestnetwork"); + if(header != null){ + header.forEach((k, v) -> { + conn.setRequestProperty(k, v); + }); + } + // 发送POST请求必须设置如下两行 + conn.setDoOutput(true); + conn.setDoInput(true); + //获取请求头 + + // 获取URLConnection对象对应的输出流 + out = new PrintWriter(conn.getOutputStream()); + StringBuffer buffer = new StringBuffer(); + + // 发送请求参数 + if(body != null){ + out.print(body.toString()); + } + // flush输出流的缓冲 + out.flush(); + // 定义BufferedReader输入流来读取URL的响应 + in = new BufferedReader( + new InputStreamReader(conn.getInputStream())); + String line; + while ((line = in.readLine()) != null) { + result += line; + } + res = result; + } catch (Exception e) { + FineLoggerFactory.getLogger().error(e.getMessage(),e); + } + //使用finally块来关闭输出流、输入流 + finally{ + try{ + if(out!=null){ + out.close(); + } + if(in!=null){ + in.close(); + } + } + catch(IOException e){ + FineLoggerFactory.getLogger().error(e.getMessage(),e); + } + } + return res; + } + + private static void trustAllHttpsCertificates() throws Exception { + javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1]; + javax.net.ssl.TrustManager tm = new miTM(); + trustAllCerts[0] = tm; + javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL","SunJSSE"); + sc.init(null, trustAllCerts, null); + HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); + } + + + public static String doFormPost(String url,Map header, Map map, String chartset) { + //声明返回结果 + String result = ""; + UrlEncodedFormEntity entity = null; + HttpResponse httpResponse = null; + HttpClient httpClient = null; + try { + // 创建连接 + httpClient = getHttpsClient(); + ; + + // 设置请求头和报文 + HttpPost httpPost = new HttpPost(url); + if (header != null) { + header.forEach((k, v) -> { + httpPost.setHeader(k, v.toString()); + }); + } + //设置参数 + List list = new ArrayList(); + Iterator iterator = map.entrySet().iterator(); + while (iterator.hasNext()) { + Map.Entry elem = (Map.Entry) iterator.next(); + list.add(new BasicNameValuePair(elem.getKey(), elem.getValue())); + } + entity = new UrlEncodedFormEntity(list, chartset == null ? "UTF-8" : chartset); + httpPost.setEntity(entity); + //执行发送,获取相应结果 + httpResponse = httpClient.execute(httpPost); + if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { + result = EntityUtils.toString(httpResponse.getEntity()); + } else { + FineLoggerFactory.getLogger().error("Http post form code is {},message is {}", httpResponse.getStatusLine().getStatusCode(), EntityUtils.toString(httpResponse.getEntity())); + } + } catch (Exception e) { + FineLoggerFactory.getLogger().error(e.getMessage(), e); + } + return result; + + } + + private static CloseableHttpClient getHttpsClient() { + RegistryBuilder registryBuilder = RegistryBuilder.create(); + ConnectionSocketFactory plainSF = new PlainConnectionSocketFactory(); + registryBuilder.register("http", plainSF); + // 指定信任密钥存储对象和连接套接字工厂 + try { + KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); + // 信任任何链接 + TrustStrategy anyTrustStrategy = new TrustStrategy() { + + @Override + public boolean isTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws CertificateException { + // TODO Auto-generated method stub + return true; + } + }; + SSLContext sslContext = SSLContexts.custom().useTLS().loadTrustMaterial(trustStore, anyTrustStrategy).build(); + LayeredConnectionSocketFactory sslSF = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); + registryBuilder.register("https", sslSF); + } catch (KeyStoreException e) { + throw new RuntimeException(e); + } catch (KeyManagementException e) { + throw new RuntimeException(e); + } catch (NoSuchAlgorithmException e) { + throw new RuntimeException(e); + } + Registry registry = registryBuilder.build(); + // 设置连接管理器 + PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(registry); + // 构建客户端 + return HttpClientBuilder.create().setConnectionManager(connManager).build(); + + } + + /** + * encode url by UTF-8 + * @param url url before encoding + * @return url after encoding + */ + public static String encodeUrl(String url){ + String eurl = url; + try { + eurl = URLEncoder.encode(url,"UTF-8"); + } catch (UnsupportedEncodingException e) { + } + return eurl; + } + + private static class miTM implements javax.net.ssl.TrustManager, + javax.net.ssl.X509TrustManager { + @Override + public java.security.cert.X509Certificate[] getAcceptedIssuers() { + return null; + } + + public boolean isServerTrusted( + java.security.cert.X509Certificate[] certs) { + return true; + } + + public boolean isClientTrusted( + java.security.cert.X509Certificate[] certs) { + return true; + } + + @Override + public void checkServerTrusted( + java.security.cert.X509Certificate[] certs, String authType) + throws java.security.cert.CertificateException { + return; + } + + @Override + public void checkClientTrusted( + java.security.cert.X509Certificate[] certs, String authType) + throws java.security.cert.CertificateException { + return; + } + } +} diff --git a/src/main/java/com/fr/plugin/xx/ltqc/auth/utils/LogUtils.java b/src/main/java/com/fr/plugin/xx/ltqc/auth/utils/LogUtils.java new file mode 100644 index 0000000..02435e7 --- /dev/null +++ b/src/main/java/com/fr/plugin/xx/ltqc/auth/utils/LogUtils.java @@ -0,0 +1,122 @@ +package com.fr.plugin.xx.ltqc.auth.utils; + +import com.fr.log.FineLoggerFactory; +import com.fr.log.FineLoggerProvider; +import com.fr.plugin.context.PluginContexts; +import com.fr.plugin.xx.ltqc.auth.Constants; +import com.fr.plugin.xx.ltqc.auth.conf.AuthSsoConfig; +import com.fr.stable.StringUtils; + +/** + * @author xx + * @since 2021/12/04 + */ +public final class LogUtils { + private static final String DEBUG_PREFIX = "[插件调试] "; + private static String LOG_PREFIX = Constants.PLUGIN_NAME; + private static final String PLUGIN_VERSION; + + private static final FineLoggerProvider LOGGER = FineLoggerFactory.getLogger(); + + static { + String version = PluginContexts.currentContext().getMarker().getVersion(); + if (StringUtils.isNotBlank(version)) { + PLUGIN_VERSION = "[v" + version + "] "; + } else { + PLUGIN_VERSION = "[unknown version] "; + } + + LOG_PREFIX = LOG_PREFIX + PLUGIN_VERSION; + } + + public static void setPrefix(String prefix) { + if (prefix != null) { + LOG_PREFIX = prefix; + } + } + + public static boolean isDebugEnabled() { + return LOGGER.isDebugEnabled(); + } + + public static void debug(String s) { + LOGGER.debug(LOG_PREFIX + s); + } + + public static void debug(String s, Object... objects) { + LOGGER.debug(LOG_PREFIX + s, objects); + } + + public static void debug(String s, Throwable throwable) { + LOGGER.debug(LOG_PREFIX + s, throwable); + } + + public static void debug4plugin(String s) { + if (AuthSsoConfig.getInstance().getDebugSwitch()) { + LOGGER.error(DEBUG_PREFIX + LOG_PREFIX + s); + } else { + LOGGER.debug(LOG_PREFIX + s); + } + } + + public static void debug4plugin(String s, Object... objects) { + if (AuthSsoConfig.getInstance().getDebugSwitch()) { + LOGGER.error(DEBUG_PREFIX + LOG_PREFIX + s, objects); + } else { + LOGGER.debug(LOG_PREFIX + s, objects); + } + } + + public static void debug4plugin(String s, Throwable throwable) { + if (AuthSsoConfig.getInstance().getDebugSwitch()) { + LOGGER.error(DEBUG_PREFIX + LOG_PREFIX + s, throwable); + } else { + LOGGER.debug(LOG_PREFIX + s, throwable); + } + } + + + public static boolean isInfoEnabled() { + return LOGGER.isInfoEnabled(); + } + + public static void info(String s) { + LOGGER.info(LOG_PREFIX + s); + } + + public static void info(String s, Object... objects) { + LOGGER.info(LOG_PREFIX + s, objects); + } + + public static void warn(String s) { + LOGGER.warn(LOG_PREFIX + s); + } + + public static void warn(String s, Object... objects) { + LOGGER.warn(LOG_PREFIX + s, objects); + } + + public static void warn(String s, Throwable throwable) { + LOGGER.warn(LOG_PREFIX + s, throwable); + } + + public static void warn(Throwable throwable, String s, Object... objects) { + LOGGER.warn(throwable, LOG_PREFIX + s, objects); + } + + public static void error(String s) { + LOGGER.error(LOG_PREFIX + s); + } + + public static void error(String s, Object... objects) { + LOGGER.error(LOG_PREFIX + s, objects); + } + + public static void error(String s, Throwable throwable) { + LOGGER.error(LOG_PREFIX + s, throwable); + } + + public static void error(Throwable throwable, String s, Object... objects) { + LOGGER.error(throwable, LOG_PREFIX + s, objects); + } +}