commit c394107de647f5f158315b5f7ee042cfb467645e Author: pioneer Date: Tue Dec 6 15:59:34 2022 +0800 open diff --git a/README.md b/README.md new file mode 100644 index 0000000..04bfcd7 --- /dev/null +++ b/README.md @@ -0,0 +1,6 @@ +# open-JSD-10250 + +JSD-10250 OAUTH单点登录集成\ +免责说明:该源码为第三方爱好者提供,不保证源码和方案的可靠性,也不提供任何形式的源码教学指导和协助!\ +仅作为开发者学习参考使用!禁止用于任何商业用途!\ +为保护开发者隐私,开发者信息已隐去!若原开发者希望公开自己的信息,可联系【pioneer】处理。 \ No newline at end of file diff --git a/lib/bamboocloud_Codec-0.0.1.jar b/lib/bamboocloud_Codec-0.0.1.jar new file mode 100644 index 0000000..0f2e63d Binary files /dev/null and b/lib/bamboocloud_Codec-0.0.1.jar differ diff --git a/lib/finekit-10.0.jar b/lib/finekit-10.0.jar new file mode 100644 index 0000000..611c8f5 Binary files /dev/null and b/lib/finekit-10.0.jar differ diff --git a/lib/signtool.jar b/lib/signtool.jar new file mode 100644 index 0000000..9c0a107 Binary files /dev/null and b/lib/signtool.jar differ diff --git a/plugin.xml b/plugin.xml new file mode 100644 index 0000000..cff5919 --- /dev/null +++ b/plugin.xml @@ -0,0 +1,22 @@ + + + com.fr.plugin.third.party.jsdbacfa + + yes + 1.0.11 + 10.0 + 2019-01-01 + fr.open + + + ]]> + + + + + + + + + \ No newline at end of file diff --git a/src/main/java/com/fr/plugin/third/party/jsdbacfa/Utils.java b/src/main/java/com/fr/plugin/third/party/jsdbacfa/Utils.java new file mode 100644 index 0000000..c134d2a --- /dev/null +++ b/src/main/java/com/fr/plugin/third/party/jsdbacfa/Utils.java @@ -0,0 +1,183 @@ +package com.fr.plugin.third.party.jsdbacfa; + +import com.fanruan.api.log.LogKit; +import com.fanruan.api.util.StringKit; +import com.fr.general.IOUtils; +import com.fr.third.org.apache.http.HttpEntity; +import com.fr.third.org.apache.http.HttpStatus; +import com.fr.third.org.apache.http.client.config.RequestConfig; +import com.fr.third.org.apache.http.client.methods.CloseableHttpResponse; +import com.fr.third.org.apache.http.client.methods.HttpGet; +import com.fr.third.org.apache.http.client.methods.HttpPost; +import com.fr.third.org.apache.http.conn.ssl.NoopHostnameVerifier; +import com.fr.third.org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import com.fr.third.org.apache.http.entity.StringEntity; +import com.fr.third.org.apache.http.impl.client.CloseableHttpClient; +import com.fr.third.org.apache.http.impl.client.HttpClients; +import com.fr.third.org.apache.http.ssl.SSLContextBuilder; +import com.fr.third.org.apache.http.ssl.TrustStrategy; +import com.fr.third.org.apache.http.util.EntityUtils; +import com.fr.third.springframework.web.util.UriUtils; + +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.SSLContext; +import javax.servlet.ServletInputStream; +import javax.servlet.http.HttpServletRequest; +import java.io.IOException; +import java.net.URISyntaxException; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; + +public class Utils { + public static String DEFAULT_USER_AGENT = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36"; + public static RequestConfig REQUEST_CONFIG = RequestConfig.custom() + .setConnectionRequestTimeout(30000) + .setSocketTimeout(30000) // 服务端相应超时 + .setConnectTimeout(30000) // 建立socket链接超时时间 + .build(); + + public static CloseableHttpClient createSSLClientDefault() { + try { + SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() { + + @Override + public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { + return true; + } + }).build(); + HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE; + SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier); + return HttpClients.custom().setSSLSocketFactory(sslsf).build(); + } catch (Exception e) { + LogKit.error(e.getMessage(), e); + } + return HttpClients.createDefault(); + } + + public static synchronized CloseableHttpClient createHttpClient(String url) { + CloseableHttpClient httpClient = null; + if (StringKit.isEmpty(url)) { + httpClient = HttpClients.createDefault(); + return httpClient; + } + + if (url.startsWith("https://")) { + httpClient = createSSLClientDefault(); + return httpClient; + } + httpClient = HttpClients.createDefault(); + return httpClient; + } + + public static synchronized String createHttpGetContent(CloseableHttpClient httpClient, String url) throws IOException { + if ((httpClient == null) || (StringKit.isEmpty(url))) { + return ""; + } + + HttpGet httpGet = new HttpGet(url); + httpGet.addHeader("User-Agent", Utils.DEFAULT_USER_AGENT); + httpGet.setConfig(Utils.REQUEST_CONFIG); + CloseableHttpResponse response = httpClient.execute(httpGet); + int statusCode = response.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + response.close(); + LogKit.info("http请求出错,http status:" + statusCode); + return ""; + } + + HttpEntity httpEntity = response.getEntity(); + if (httpEntity == null) { + response.close(); + LogKit.info("http请求出错,http响应内容为空"); + return ""; + } + String responseContent = EntityUtils.toString(httpEntity, "UTF-8"); + response.close(); + if (StringKit.isEmpty(responseContent)) { + LogKit.info("http请求出错,http响应内容为空1"); + return ""; + } + return responseContent; + } + + public static synchronized String createHttpPostContent(CloseableHttpClient httpClient, String url, String bodyContent) throws IOException { + if ((httpClient == null) || (StringKit.isEmpty(url)) || (StringKit.isEmpty(bodyContent))) { + return ""; + } + + HttpPost httpPost = new HttpPost(url); + httpPost.addHeader("User-Agent", Utils.DEFAULT_USER_AGENT); + httpPost.setConfig(Utils.REQUEST_CONFIG); + StringEntity bodyEntity = new StringEntity(bodyContent, "UTF-8"); + httpPost.setEntity(bodyEntity); + CloseableHttpResponse response = httpClient.execute(httpPost); + int statusCode = response.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + response.close(); + LogKit.info("http请求出错,http status:" + statusCode); + return ""; + } + + HttpEntity httpEntity = response.getEntity(); + if (httpEntity == null) { + response.close(); + LogKit.info("http请求出错,http响应内容为空"); + return ""; + } + String responseContent = EntityUtils.toString(httpEntity, "UTF-8"); + response.close(); + if (StringKit.isEmpty(responseContent)) { + LogKit.info("http请求出错,http响应内容为空1"); + return ""; + } + return responseContent; + } + + /** + * 获取请求主体内容 + * @param req + * @return + * @throws IOException + */ + public static String getHttpRequestBody(HttpServletRequest req) throws IOException { + if (req == null) { + return ""; + } + ServletInputStream inputStream = req.getInputStream(); + if (inputStream == null) { + return ""; + } + String content = IOUtils.inputStream2String(inputStream); + if (StringKit.isEmpty(content)) { + return ""; + } + return content; + } + + /** + * 用utf-8按url规则编码 + * + * @param value + * @return + * @throws URISyntaxException + */ + public static String encodeUrlWithUtf8(String value) { + if ((value == null) || (value.length() <= 0)) { + return ""; + } + /*String path = "/" + value; + URI uri = new URI("http", "a", path, null); + String tempValue = uri.toASCIIString(); + String encodedValue = tempValue.substring(9);*/ + String tempValue = ""; + try { + tempValue = UriUtils.encodeQueryParam(value, "UTF-8"); + return tempValue; + } catch (Exception e) { + LogKit.error("Utils.encodeUrlWithUtf8:" + e.getMessage(), e); + tempValue = value; + } + return tempValue; + } + +} diff --git a/src/main/java/com/fr/plugin/third/party/jsdbacfa/config/CustomDataConfig.java b/src/main/java/com/fr/plugin/third/party/jsdbacfa/config/CustomDataConfig.java new file mode 100644 index 0000000..2660be1 --- /dev/null +++ b/src/main/java/com/fr/plugin/third/party/jsdbacfa/config/CustomDataConfig.java @@ -0,0 +1,173 @@ +package com.fr.plugin.third.party.jsdbacfa.config; + + +import com.fr.config.*; +import com.fr.config.holder.Conf; +import com.fr.config.holder.factory.Holders; + +import java.util.HashMap; +import java.util.Map; + +/** + * 配置数据保存 + */ +@Visualization(category = "登录集成配置") +public class CustomDataConfig extends DefaultConfiguration { + public String getNameSpace() { + return this.getClass().getName(); + } + + private static volatile CustomDataConfig config = null; + + public static CustomDataConfig getInstance() { + if (config == null) { + config = ConfigContext.getConfigInstance(CustomDataConfig.class); + } + return config; + } + + private static volatile Map URL_MAP = new HashMap<>(); + + public synchronized static void addMapUrl(String key, String url) { + URL_MAP.put(key, url); + } + + public synchronized static String getMapUrl(String key) { + if (!URL_MAP.containsKey(key)) { + return ""; + } + String url = URL_MAP.get(key); + URL_MAP.remove(key); + return url; + } + + + @Identifier(value = "clientId", name = "应用唯一标识", description = "", status = Status.SHOW) + private Conf clientId = Holders.simple(""); + + @Identifier(value = "clientSecret", name = "应用密钥", description = "", status = Status.SHOW) + private Conf clientSecret = Holders.simple(""); + + @Identifier(value = "authorizeUrl", name = "请求认证地址", description = "", status = Status.SHOW) + private Conf authorizeUrl = Holders.simple("https://xx/profile/oauth2/authorize"); + + @Identifier(value = "accessTokenUrl", name = "请求access_token API地址", description = "", status = Status.SHOW) + private Conf accessTokenUrl = Holders.simple("https://xx/profile/oauth2/accessToken"); + + @Identifier(value = "profileUrl", name = "请求profile API地址", description = "", status = Status.SHOW) + private Conf profileUrl = Holders.simple("https://xx/profile/oauth2/profile"); + + @Identifier(value = "frUrl", name = "报表地址", description = "", status = Status.SHOW) + private Conf frUrl = Holders.simple(""); + + @Identifier(value = "logoutUrl", name = "单点登出地址", description = "", status = Status.SHOW) + private Conf logoutUrl = Holders.simple("https://xx/logout"); + + @Identifier(value = "passwordKey", name = "签名KEY", description = "", status = Status.SHOW) + private Conf passwordKey = Holders.simple(""); + + + + @Identifier(value = "loginTypeNameParameter", name = "登录类型参数名称", description = "", status = Status.HIDE) + private Conf loginTypeNameParameter = Holders.simple("loginType"); + + @Identifier(value = "loginTypeValue", name = "登录类型值", description = "", status = Status.HIDE) + private Conf loginTypeValue = Holders.simple("auth"); + + + public String getClientId() { + return clientId.get(); + } + + public void setClientId(String clientId) { + this.clientId.set(clientId); + } + + public String getClientSecret() { + return clientSecret.get(); + } + + public void setClientSecret(String clientSecret) { + this.clientSecret.set(clientSecret); + } + + public String getAuthorizeUrl() { + return authorizeUrl.get(); + } + + public void setAuthorizeUrl(String authorizeUrl) { + this.authorizeUrl.set(authorizeUrl); + } + + public String getAccessTokenUrl() { + return accessTokenUrl.get(); + } + + public void setAccessTokenUrl(String accessTokenUrl) { + this.accessTokenUrl.set(accessTokenUrl); + } + + public String getProfileUrl() { + return profileUrl.get(); + } + + public void setProfileUrl(String profileUrl) { + this.profileUrl.set(profileUrl); + } + + public String getLogoutUrl() { + return logoutUrl.get(); + } + + public void setLogoutUrl(String logoutUrl) { + this.logoutUrl.set(logoutUrl); + } + + public String getFrUrl() { + return frUrl.get(); + } + + public void setFrUrl(String frUrl) { + this.frUrl.set(frUrl); + } + + public String getPasswordKey() { + return passwordKey.get(); + } + + public void setPasswordKey(String passwordKey) { + this.passwordKey.set(passwordKey); + } + + public String getLoginTypeNameParameter() { + return loginTypeNameParameter.get(); + } + + public void setLoginTypeNameParameter(String loginTypeNameParameter) { + this.loginTypeNameParameter.set(loginTypeNameParameter); + } + + public String getLoginTypeValue() { + return loginTypeValue.get(); + } + + public void setLoginTypeValue(String loginTypeValue) { + this.loginTypeValue.set(loginTypeValue); + } + + @Override + public Object clone() throws CloneNotSupportedException { + CustomDataConfig cloned = (CustomDataConfig) super.clone(); + cloned.frUrl = (Conf) frUrl.clone(); + cloned.passwordKey = (Conf) passwordKey.clone(); + cloned.clientId = (Conf) clientId.clone(); + cloned.clientSecret = (Conf) clientSecret.clone(); + cloned.authorizeUrl = (Conf) authorizeUrl.clone(); + cloned.accessTokenUrl = (Conf) accessTokenUrl.clone(); + cloned.profileUrl = (Conf) profileUrl.clone(); + cloned.logoutUrl = (Conf) logoutUrl.clone(); + cloned.loginTypeNameParameter = (Conf) loginTypeNameParameter.clone(); + cloned.loginTypeValue = (Conf) loginTypeValue.clone(); + return cloned; + } +} diff --git a/src/main/java/com/fr/plugin/third/party/jsdbacfa/config/DataConfigInitializeMonitor.java b/src/main/java/com/fr/plugin/third/party/jsdbacfa/config/DataConfigInitializeMonitor.java new file mode 100644 index 0000000..d0fccf1 --- /dev/null +++ b/src/main/java/com/fr/plugin/third/party/jsdbacfa/config/DataConfigInitializeMonitor.java @@ -0,0 +1,24 @@ +package com.fr.plugin.third.party.jsdbacfa.config; + +import com.fr.intelli.record.Focus; +import com.fr.intelli.record.Original; +import com.fr.plugin.context.PluginContext; +import com.fr.plugin.observer.inner.AbstractPluginLifecycleMonitor; +import com.fr.record.analyzer.EnableMetrics; + +/** + * 配置信息初始化 + */ +@EnableMetrics +public class DataConfigInitializeMonitor extends AbstractPluginLifecycleMonitor { + @Override + @Focus(id = "com.fr.plugin.third.party.jsdbacfa", text = "plugin-jsdbacfa", source = Original.PLUGIN) + public void afterRun(PluginContext pluginContext) { + CustomDataConfig.getInstance(); + } + + @Override + public void beforeStop(PluginContext pluginContext) { + + } +} \ No newline at end of file diff --git a/src/main/java/com/fr/plugin/third/party/jsdbacfa/http/CustomConfigHttpHandler.java b/src/main/java/com/fr/plugin/third/party/jsdbacfa/http/CustomConfigHttpHandler.java new file mode 100644 index 0000000..a9cb772 --- /dev/null +++ b/src/main/java/com/fr/plugin/third/party/jsdbacfa/http/CustomConfigHttpHandler.java @@ -0,0 +1,45 @@ +package com.fr.plugin.third.party.jsdbacfa.http; + +import com.fr.decision.fun.impl.BaseHttpHandler; +import com.fr.json.JSONObject; +import com.fr.plugin.third.party.jsdbacfa.Utils; +import com.fr.plugin.third.party.jsdbacfa.config.CustomDataConfig; +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; + +/** + * + */ +public class CustomConfigHttpHandler extends BaseHttpHandler { + + @Override + public RequestMethod getMethod() { + return RequestMethod.GET; + } + + @Override + public String getPath() { + return "/jsdbacfa/oauth/config"; + } + + @Override + public boolean isPublic() { + return true; + } + + @Override + public void handle(HttpServletRequest req, HttpServletResponse res) throws Exception { + res.setContentType("application/json; charset=utf-8"); + String authUrl = CustomDataConfig.getInstance().getFrUrl() + "?" + CustomDataConfig.getInstance().getLoginTypeNameParameter() + "=" + CustomDataConfig.getInstance().getLoginTypeValue(); + String logoutUrl = CustomDataConfig.getInstance().getLogoutUrl() + "?service=" + Utils.encodeUrlWithUtf8(authUrl); + JSONObject json = new JSONObject(); + json.put("logoutUrl", logoutUrl); + //json.put("authUrl", authUrl); + WebUtils.printAsJSON(res, json); + } + + +} diff --git a/src/main/java/com/fr/plugin/third/party/jsdbacfa/http/CustomHttpHandlerProvider.java b/src/main/java/com/fr/plugin/third/party/jsdbacfa/http/CustomHttpHandlerProvider.java new file mode 100644 index 0000000..de9b739 --- /dev/null +++ b/src/main/java/com/fr/plugin/third/party/jsdbacfa/http/CustomHttpHandlerProvider.java @@ -0,0 +1,15 @@ +package com.fr.plugin.third.party.jsdbacfa.http; + +import com.fr.decision.fun.impl.AbstractHttpHandlerProvider; +import com.fr.decision.fun.impl.BaseHttpHandler; +import com.fr.stable.fun.Authorize; + +@Authorize(callSignKey = "com.fr.plugin.third.party.jsdbacfa") +public class CustomHttpHandlerProvider extends AbstractHttpHandlerProvider { + @Override + public BaseHttpHandler[] registerHandlers() { + return new BaseHttpHandler[]{ + new CustomConfigHttpHandler(), + }; + } +} diff --git a/src/main/java/com/fr/plugin/third/party/jsdbacfa/http/CustomURLAliasProvider.java b/src/main/java/com/fr/plugin/third/party/jsdbacfa/http/CustomURLAliasProvider.java new file mode 100644 index 0000000..57d73b7 --- /dev/null +++ b/src/main/java/com/fr/plugin/third/party/jsdbacfa/http/CustomURLAliasProvider.java @@ -0,0 +1,16 @@ +package com.fr.plugin.third.party.jsdbacfa.http; + +import com.fr.decision.fun.impl.AbstractURLAliasProvider; +import com.fr.decision.webservice.url.alias.URLAlias; +import com.fr.decision.webservice.url.alias.URLAliasFactory; + +public class CustomURLAliasProvider extends AbstractURLAliasProvider { + @Override + public URLAlias[] registerAlias() { + return new URLAlias[]{ + URLAliasFactory.createPluginAlias("/jsdbacfa/oauth/config", "/jsdbacfa/oauth/config", true), + + + }; + } +} diff --git a/src/main/java/com/fr/plugin/third/party/jsdbacfa/http/SessionGlobalRequestFilterProvider.java b/src/main/java/com/fr/plugin/third/party/jsdbacfa/http/SessionGlobalRequestFilterProvider.java new file mode 100644 index 0000000..ee416a9 --- /dev/null +++ b/src/main/java/com/fr/plugin/third/party/jsdbacfa/http/SessionGlobalRequestFilterProvider.java @@ -0,0 +1,575 @@ +package com.fr.plugin.third.party.jsdbacfa.http; + +import com.fanruan.api.log.LogKit; +import com.fanruan.api.util.StringKit; +import com.fr.data.NetworkHelper; +import com.fr.decision.authority.AuthorityContext; +import com.fr.decision.authority.data.User; +import com.fr.decision.fun.impl.AbstractGlobalRequestFilterProvider; +import com.fr.decision.mobile.terminal.TerminalHandler; +import com.fr.decision.webservice.utils.WebServiceUtils; +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.general.ComparatorUtils; +import com.fr.json.JSONObject; +import com.fr.plugin.context.PluginContexts; +import com.fr.plugin.third.party.jsdbacfa.Utils; +import com.fr.plugin.third.party.jsdbacfa.config.CustomDataConfig; +import com.fr.stable.StringUtils; +import com.fr.stable.fun.Authorize; +import com.fr.stable.query.QueryFactory; +import com.fr.third.org.apache.commons.codec.digest.DigestUtils; +import com.fr.third.org.apache.http.HttpEntity; +import com.fr.third.org.apache.http.HttpStatus; +import com.fr.third.org.apache.http.NameValuePair; +import com.fr.third.org.apache.http.client.config.RequestConfig; +import com.fr.third.org.apache.http.client.entity.UrlEncodedFormEntity; +import com.fr.third.org.apache.http.client.methods.CloseableHttpResponse; +import com.fr.third.org.apache.http.client.methods.HttpPost; +import com.fr.third.org.apache.http.impl.client.CloseableHttpClient; +import com.fr.third.org.apache.http.message.BasicNameValuePair; +import com.fr.third.org.apache.http.util.EntityUtils; +import com.fr.web.utils.WebUtils; + +import javax.servlet.FilterChain; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.text.SimpleDateFormat; +import java.util.*; + +@Authorize(callSignKey = "com.fr.plugin.third.party.jsdbacfa") +public class SessionGlobalRequestFilterProvider extends AbstractGlobalRequestFilterProvider { + private static String DEFAULT_USER_AGENT = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36"; + + @Override + public String filterName() { + return "com.fr.plugin.third.party.jsdbacfa"; + } + + @Override + public String[] urlPatterns() { + return new String[]{"/decision", "/decision/*"}; + } + + @Override + public void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain filterChain) { + try { + String fullUrl = req.getRequestURL().toString(); + String queryUrl = req.getQueryString(); + if ((queryUrl == null) || "null".equalsIgnoreCase(queryUrl)) { + queryUrl = ""; + } else { + queryUrl = "?" + queryUrl; + } + + String fullUrl1 = fullUrl + queryUrl; + String method = req.getMethod(); + LogKit.info("登录集成,记录访问地址:" + method + " " + fullUrl1); + if (!"GET".equalsIgnoreCase(method)) { + filterChain.doFilter(req, res); + return; + } + + if (fullUrl.indexOf("/remote/") >= 0) { + filterChain.doFilter(req, res); + return; + } + + if (fullUrl.indexOf("terminal=H5") >= 0) { + filterChain.doFilter(req, res); + return; + } + + if (fullUrl.indexOf("__device__=") >= 0) { + filterChain.doFilter(req, res); + return; + } + + if (fullUrl.indexOf("/weixin/") >= 0) { + filterChain.doFilter(req, res); + return; + } + + + if (fullUrl.indexOf("/dingtalk/") >= 0) { + filterChain.doFilter(req, res); + return; + } + + //添加认证 + if (!PluginContexts.currentContext().isAvailable()) { + LogKit.error("登录集成插件试用过期, 请购买许可证"); + filterChain.doFilter(req, res); + return; + } + + + // boolean option = isLogged(req); + //if (option) { + // filterChain.doFilter(req, res); + // return; + //} + String state, reqUrl; + if (isAllowLoginWithParameter(req) || isAllowLoginWithOthers(req)) { + reqUrl = getRequestUrl(req); + state = UUID.randomUUID().toString(); + CustomDataConfig.getInstance().addMapUrl(state, reqUrl); + String tempUrl = getFullAuthorizeUrl(state); + LogKit.info("登录集成,请求认证地址:" + tempUrl); + sendRedirect(res, tempUrl); + return; + } + + String loginUsername = getOauthLoginUsername(req); + if (StringKit.isEmpty(loginUsername)) { + filterChain.doFilter(req, res); + return; + } + LogKit.info("登录集成,用户名:" + loginUsername); + + User user = UserService.getInstance().getUserByUserName(loginUsername); + boolean tipsOption = false; + String tipsContent = ""; + if (user == null) { + tipsOption = true; + LogKit.info("登录集成,用户名:" + loginUsername + "在报表平台不存在"); + tipsContent = "在报表服务器上不存在"; + } else if (!user.isEnable()) { + tipsOption = true; + LogKit.info("登录集成,用户名:" + loginUsername + "在报表平台上被禁用"); + tipsContent = "在报表平台上被禁用"; + } + + if (tipsOption) { + String jumpContent = "\n" + + "\n" + + " \n" + + " 提示\n" + + "\n" + + "\n" + + " \n" + + "
\n" + + " \n" + + "
\n" + + "\n" + + ""; + res.setContentType("text/html;charset=UTF-8"); + WebUtils.printAsString(res, jumpContent); + res.setStatus(200); + return; + } + + loginUsername = user.getUserName(); + LogKit.info("登录集成,报表平台用户名:" + loginUsername); + + + String loginToken = LoginService.getInstance().login(req, res, loginUsername); + req.setAttribute("fine_auth_token", loginToken); + + reqUrl = getRealUrl(req); + if (StringKit.isNotEmpty(reqUrl)) { + LogKit.info("登录集成,报表真实地址:" + reqUrl); + sendRedirect(res, reqUrl); + return; + } + + filterChain.doFilter(req, res); + } catch (Exception e) { + LogKit.error("登录集成出错," + e.getMessage(), e); + } + } + + private String getRealUrl(HttpServletRequest req) { + if (req == null) { + return ""; + } + String state = WebUtils.getHTTPRequestParameter(req, "state"); + if (StringKit.isEmpty(state)) { + return ""; + } + String url = CustomDataConfig.getInstance().getMapUrl(state); + return url; + } + + + private String getFullAuthorizeUrl(String state) { + //请求示例: + //http://127.0.0.1/profile/oauth2/authorize?client_id=xxx&response_type=code&redirect_uri=http%3A%2F%2F127.0.0.1%3A8899%2FparaOsc%2Fcallback&oauth_timestamp=1564640612915 + CustomDataConfig config = CustomDataConfig.getInstance(); + //String tempUrl = URLEncoder.encode(config.getFrUrl(), "UTF-8"); + String tempUrl = config.getFrUrl(); + String url = config.getAuthorizeUrl() + "?client_id=" + config.getClientId() + "&response_type=code&redirect_uri=" + tempUrl + "&state=" + state + "&oauth_timestamp=" + System.currentTimeMillis(); + LogKit.info("登录集成,请求用户授权地址:" + url); + return url; + } + + + private String getOauthLoginUsername(HttpServletRequest req) throws IOException { + if (req == null) { + return ""; + } + String oAuthCode = WebUtils.getHTTPRequestParameter(req, "code"); + if (StringKit.isEmpty(oAuthCode)) { + return ""; + } + LogKit.info("登录集成,OAuth Code:" + oAuthCode); + + RequestConfig requestConfig = RequestConfig.custom() + .setConnectionRequestTimeout(10000) + .setSocketTimeout(10000) // 服务端相应超时 + .setConnectTimeout(10000) // 建立socket链接超时时间 + .build(); + + //获取授权Token + //https://***/profile/oauth2/accessToken + String accessTokenUrl = CustomDataConfig.getInstance().getAccessTokenUrl(); + LogKit.info("登录集成,获取授权Token地址:" + accessTokenUrl); + HttpPost httpPost = new HttpPost(accessTokenUrl); + httpPost.addHeader("User-Agent", DEFAULT_USER_AGENT); + + List params = new ArrayList(); + NameValuePair clientIdNameValuePair = new BasicNameValuePair("client_id", CustomDataConfig.getInstance().getClientId()); + NameValuePair clientSecretNameValuePair = new BasicNameValuePair("client_secret", CustomDataConfig.getInstance().getClientSecret()); + NameValuePair redirectUriNameValuePair = new BasicNameValuePair("redirect_uri", CustomDataConfig.getInstance().getFrUrl()); + NameValuePair codeNameValuePair = new BasicNameValuePair("code", oAuthCode); + NameValuePair grantTypeNameValuePair = new BasicNameValuePair("grant_type", "authorization_code"); + NameValuePair oauthTimestampNameValuePair = new BasicNameValuePair("oauth_timestamp", String.valueOf(System.currentTimeMillis())); + NameValuePair nonceStrNameValuePair = new BasicNameValuePair("nonce_str", getUuid()); + params.add(clientIdNameValuePair); + params.add(clientSecretNameValuePair); + params.add(redirectUriNameValuePair); + params.add(codeNameValuePair); + params.add(grantTypeNameValuePair); + params.add(oauthTimestampNameValuePair); + params.add(nonceStrNameValuePair); + String SignValue = getSignValue(params); + LogKit.info("登录集成,获取授权Token,Sign Value:" + SignValue); + NameValuePair signNameValuePair = new BasicNameValuePair("sign", SignValue); + params.add(signNameValuePair); + + httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); + httpPost.setHeader("Content-type", "application/x-www-form-urlencoded"); + + + httpPost.setConfig(requestConfig); + CloseableHttpClient httpClient = Utils.createHttpClient(accessTokenUrl); + CloseableHttpResponse response = httpClient.execute(httpPost); + int statusCode = response.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + response.close(); + httpClient.close(); + LogKit.info("登录集成,获取授权Token请求出错,http status:" + statusCode); + return ""; + } + + HttpEntity httpEntity = response.getEntity(); + if (httpEntity == null) { + response.close(); + httpClient.close(); + LogKit.info("登录集成,获取授权Token请求出错,http响应内容为空"); + return ""; + } + String responseContent = EntityUtils.toString(httpEntity, "UTF-8"); + response.close(); + if (StringKit.isEmpty(responseContent)) { + httpClient.close(); + LogKit.info("登录集成,获取授权Token请求出错,http响应内容为空1"); + return ""; + } + LogKit.info("登录集成,获取授权Token请求,http响应内容\n" + responseContent); + + String accessToken = getAccessToken(responseContent); + if (StringKit.isEmpty(accessToken)) { + httpClient.close(); + LogKit.info("登录集成,获取授权Token请求出错,授权Token为空"); + return ""; + } + LogKit.info("登录集成,授权Token:" + accessToken); + + //https://***/profile/oauth2/profile + String userUrl = CustomDataConfig.getInstance().getProfileUrl(); + LogKit.info("登录集成,获取用户信息地址:" + userUrl); + httpPost = new HttpPost(userUrl); + httpPost.addHeader("User-Agent", DEFAULT_USER_AGENT); + + params = new ArrayList(); + BasicNameValuePair accessTokenValuePair = new BasicNameValuePair("access_token", accessToken); + oauthTimestampNameValuePair = new BasicNameValuePair("oauth_timestamp", String.valueOf(System.currentTimeMillis())); + nonceStrNameValuePair = new BasicNameValuePair("nonce_str", getUuid()); + params.add(clientIdNameValuePair); + params.add(clientSecretNameValuePair); + params.add(accessTokenValuePair); + params.add(oauthTimestampNameValuePair); + params.add(nonceStrNameValuePair); + SignValue = getSignValue(params); + LogKit.info("登录集成,获取用户信息,Sign Value:" + SignValue); + signNameValuePair = new BasicNameValuePair("sign", SignValue); + params.add(signNameValuePair); + httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); + httpPost.setHeader("Content-type", "application/x-www-form-urlencoded"); + httpPost.setConfig(requestConfig); + response = httpClient.execute(httpPost); + statusCode = response.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + response.close(); + httpClient.close(); + LogKit.info("登录集成,获取用户信息请求出错,http status:" + statusCode); + return ""; + } + + httpEntity = response.getEntity(); + if (httpEntity == null) { + response.close(); + httpClient.close(); + LogKit.info("登录集成,获取用户信息请求出错,http响应内容为空"); + return ""; + } + responseContent = EntityUtils.toString(httpEntity, "UTF-8"); + response.close(); + httpClient.close(); + if (StringKit.isEmpty(responseContent)) { + LogKit.info("登录集成,获取用户信息请求出错,http响应内容为空1"); + return ""; + } + + LogKit.info("登录集成,获取用户信息请求,http响应内容\n" + responseContent); + String uid = getUserId(responseContent); + if (StringKit.isEmpty(uid)) { + LogKit.info("登录集成,,获取用户信息请求出错,uid为空"); + return ""; + } + LogKit.info("登录集成,uid:" + uid); + + return uid; + } + + private String getSignValue(List params) { + if (params == null) { + return ""; + } + String appKeyValue = CustomDataConfig.getInstance().getPasswordKey() + CustomDataConfig.getInstance().getClientSecret(); + Map paramMap = new HashMap<>(); + NameValuePair nameValuePair; + for (int i = 0, max = params.size() - 1; i <= max; i++) { + nameValuePair = params.get(i); + paramMap.put(nameValuePair.getName(), nameValuePair.getValue()); + } + String signValue = getSign(paramMap, appKeyValue); + return signValue; + } + + public static String getSign(Map params, String secret) { + String sign = ""; + StringBuilder sb = new StringBuilder(); + //排序 + Set keyset = params.keySet(); + TreeSet sortSet = new TreeSet(); + sortSet.addAll(keyset); + Iterator it = sortSet.iterator(); + //加密字符串 + while (it.hasNext()) { + String key = it.next(); + String value = params.get(key); + sb.append(key).append(value); + } + sb.append("appkey").append(secret); + String md5Str = sb.toString(); + LogKit.info("登录集成,获取授权Token,sign 待加密字符串:" + md5Str); + try { + sign = DigestUtils.md5Hex(md5Str).toUpperCase(); + } catch (Exception e) { + } + return sign; + } + + private String getUuid() { + String uuid = UUID.randomUUID().toString().replace("-", ""); + return uuid; + } + + + private String getAccessToken(String content) { + if (StringKit.isEmpty(content)) { + return ""; + } + + JSONObject contentJson = new JSONObject(content); + int status = contentJson.getInt("status"); + if (status != 200) { + return ""; + } + String token = contentJson.getString("access_token"); + return token; + } + + private String getUserId(String content) { + if (StringKit.isEmpty(content)) { + return ""; + } + + String loginName; + JSONObject contentJson = new JSONObject(content); + int status = contentJson.getInt("status"); + if (status != 200) { + return ""; + } + loginName = contentJson.getString("id"); + return loginName; + } + + + private String getPasswordValue(String usercode) { + //加密规则:MD5(yyyy+'[关键字]'+mm+'[关键字]'+dd+MD5(usercode)) + //其中:yyyy为当前年,mm为当前月,dd为当天 + + String currentDate = getSysTime(); + String year = currentDate.substring(0, 4); + String month = currentDate.substring(4, 6); + String day = currentDate.substring(6); + + String tempValue = year + CustomDataConfig.getInstance().getPasswordKey() + month + CustomDataConfig.getInstance().getPasswordKey() + day + DigestUtils.md5Hex(usercode); + String value = DigestUtils.md5Hex(tempValue); + LogKit.info("登录集成,计算的加密密码:" + value); + return value; + } + + public synchronized static String getSysTime() { + SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd"); + Date date = new Date(); + String nowData = format.format(date); + return nowData; + } + + private void sendRedirect(HttpServletResponse res, String url) { + res.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY); + res.setHeader("Location", url); + } + + private String getRequestUrl(HttpServletRequest req) { + String fullUrl = req.getRequestURL().toString(); + fullUrl = getRealUrl(fullUrl); + Map paraMap = req.getParameterMap(); + String paraName; + String[] paraValues; + String loginTypeParaName = CustomDataConfig.getInstance().getLoginTypeNameParameter(); + String queryStr = ""; + for (Map.Entry entry : paraMap.entrySet()) { + paraName = entry.getKey(); + if (ComparatorUtils.equals(paraName, loginTypeParaName)) { + continue; + } + if (ComparatorUtils.equals(paraName, "code")) { + continue; + } + paraValues = entry.getValue(); + queryStr = addParaToQuery(queryStr, paraName, paraValues); + } + if (StringKit.isEmpty(queryStr)) { + return fullUrl; + } + fullUrl = fullUrl + "?" + queryStr; + return fullUrl; + } + + private String addParaToQuery(String query, String paraName, String[] paraValues) { + if (StringKit.isEmpty(paraName)) { + return query; + } + String fullQuery = query; + if ((paraValues == null) || (paraValues.length <= 0)) { + if (StringKit.isNotEmpty(fullQuery)) { + fullQuery = fullQuery + "&"; + } + fullQuery = fullQuery + paraName + "="; + return fullQuery; + } + for (int i = 0, max = paraValues.length - 1; i <= max; i++) { + if (StringKit.isNotEmpty(fullQuery)) { + fullQuery = fullQuery + "&"; + } + fullQuery = fullQuery + paraName + "=" + Utils.encodeUrlWithUtf8(paraValues[i]); + } + return fullQuery; + } + + + private boolean isAllowLoginWithParameter(HttpServletRequest req) { + if (req == null) { + return false; + } + String loginTypeNameParameter = CustomDataConfig.getInstance().getLoginTypeNameParameter(); + String loginTypeConfigValue = CustomDataConfig.getInstance().getLoginTypeValue(); + if (StringKit.isEmpty(loginTypeNameParameter) || StringKit.isEmpty(loginTypeConfigValue)) { + return false; + } + String loginTypeValue = WebUtils.getHTTPRequestParameter(req, loginTypeNameParameter); + return ComparatorUtils.equalsIgnoreCase(loginTypeConfigValue, loginTypeValue); + } + + + private String getRealUrl(String url) { + if (StringKit.isEmpty(url)) { + return url; + } + int index = url.indexOf("/decision"); + if (index < 0) { + return url; + } + String tempUrl = CustomDataConfig.getInstance().getFrUrl() + url.substring(index + "/decision".length()); + return tempUrl; + } + + public boolean isLogged(HttpServletRequest req) { + boolean logged = true; + try { + String token = TokenResource.COOKIE.getToken(req); + LoginService.getInstance().loginStatusValid(token, TerminalHandler.getTerminal(req, NetworkHelper.getDevice(req)), WebServiceUtils.getIpInfoFromRequest(req)); + } catch (Exception var4) { + logged = false; + } + return logged; + } + + public boolean isAllowLoginWithOthers(HttpServletRequest req) { + if (req == null) { + return false; + } + + if (!"GET".equalsIgnoreCase(req.getMethod())) { + return false; + } + + if (isLogged(req)) { + return false; + } + + String reqUrl = req.getRequestURL().toString(); + String viewlet = WebUtils.getHTTPRequestParameter(req, "viewlet"); + if (((reqUrl.indexOf("/decision/view/report") > 0) || (reqUrl.indexOf("/decision/view/form") > 0)) && (StringKit.isNotEmpty(viewlet))) { + return true; + } + + if ((reqUrl.indexOf("/entry/access/") > 0)) { + int index = reqUrl.indexOf("/entry/access/"); + String entryId = reqUrl.substring(index + "/entry/access/".length()); + if ((StringKit.isNotEmpty(viewlet)) && (entryId.length() == 36) && (entryId.indexOf("-") > 0)) { + return true; + } + } + return false; + } + +} diff --git a/src/main/java/com/fr/plugin/third/party/jsdbacfa/web/MainFilesComponent.java b/src/main/java/com/fr/plugin/third/party/jsdbacfa/web/MainFilesComponent.java new file mode 100644 index 0000000..b69e722 --- /dev/null +++ b/src/main/java/com/fr/plugin/third/party/jsdbacfa/web/MainFilesComponent.java @@ -0,0 +1,46 @@ +package com.fr.plugin.third.party.jsdbacfa.web; + +import com.fr.web.struct.Component; +import com.fr.web.struct.Filter; +import com.fr.web.struct.browser.RequestClient; +import com.fr.web.struct.category.ScriptPath; +import com.fr.web.struct.category.StylePath; + +public class MainFilesComponent extends Component { + public static final MainFilesComponent KEY = new MainFilesComponent(); + private MainFilesComponent(){} + /** + * 返回需要引入的JS脚本路径 + * @param client 请求客户端描述 + * @return JS脚本路径 + */ + public ScriptPath script(RequestClient client ) { + //如果不需要就直接返回 ScriptPath.EMPTY + return ScriptPath.build("com/fr/plugin/third/party/jsdbacfa/web/main.js"); + } + + /** + * 返回需要引入的CSS样式路径 + * @param client 请求客户端描述 + * @return CSS样式路径 + */ + public StylePath style(RequestClient client ) { + //如果不需要就直接返回 StylePath.EMPTY; + //return StylePath.build("com/fr/plugin/jscssinput/demo/demo.css"); + return StylePath.EMPTY; + } + + /** + * 通过给定的资源过滤器控制是否加载这个资源 + * @return 资源过滤器 + */ + public Filter filter() { + return new Filter(){ + @Override + public boolean accept() { + //任何情况下我们都在平台组件加载时加载我们的组件 + return true; + } + }; + } +} \ No newline at end of file diff --git a/src/main/java/com/fr/plugin/third/party/jsdbacfa/web/MainWebResourceProvider.java b/src/main/java/com/fr/plugin/third/party/jsdbacfa/web/MainWebResourceProvider.java new file mode 100644 index 0000000..e6d3b96 --- /dev/null +++ b/src/main/java/com/fr/plugin/third/party/jsdbacfa/web/MainWebResourceProvider.java @@ -0,0 +1,19 @@ +package com.fr.plugin.third.party.jsdbacfa.web; + +import com.fr.decision.fun.impl.AbstractWebResourceProvider; +import com.fr.decision.web.MainComponent; +import com.fr.web.struct.Atom; + +public class MainWebResourceProvider extends AbstractWebResourceProvider { + @Override + public Atom attach() { + //在平台主组件加载时添加我们自己的组件 + return MainComponent.KEY; + } + + @Override + public Atom client() { + //我们自己要引入的组件 + return MainFilesComponent.KEY; + } +} diff --git a/src/main/resources/com/fr/plugin/third/party/jsdbacfa/web/main.js b/src/main/resources/com/fr/plugin/third/party/jsdbacfa/web/main.js new file mode 100644 index 0000000..da1655b --- /dev/null +++ b/src/main/resources/com/fr/plugin/third/party/jsdbacfa/web/main.js @@ -0,0 +1,25 @@ +$(function () { + var url = Dec.fineServletURL + "/url/jsdbacfa/oauth/config"; + $.get(url, + function (data, status) { + if (status == "success") { + //debugger; + + var logoutUrl = data.logoutUrl; + //var authUrl = data.authUrl; + var a = Dec.Logout; + a = function () { + Dec.Utils.logout((function (e) { + //debugger; + Dec.Utils.clearLoginToken(); + //window.location.href = authUrl; + } + )) + }; + Dec.Logout = function () { + a(); + window.location.href = logoutUrl; + } + } + }, "json"); +}); \ No newline at end of file