commit 2f06ec57a5041b483008558c17c10c48f10451b6 Author: pioneer Date: Thu Nov 24 10:40:05 2022 +0800 open diff --git a/README.md b/README.md new file mode 100644 index 0000000..3ceef71 --- /dev/null +++ b/README.md @@ -0,0 +1,6 @@ +# open-JSD-10117 + +JSD-10117 打开帆软登录页时重定向到客户统一认证平台登录页,输入账号密码登录后,会生成一个token,帆软解析token后获取用户名进行后台登录\ +免责说明:该源码为第三方爱好者提供,不保证源码和方案的可靠性,也不提供任何形式的源码教学指导和协助!\ +仅作为开发者学习参考使用!禁止用于任何商业用途!\ +为保护开发者隐私,开发者信息已隐去!若原开发者希望公开自己的信息,可联系【pioneer】处理。 \ No newline at end of file diff --git a/lib/finekit-10.0-20191216.jar b/lib/finekit-10.0-20191216.jar new file mode 100644 index 0000000..de51b8c Binary files /dev/null and b/lib/finekit-10.0-20191216.jar differ diff --git a/plugin.xml b/plugin.xml new file mode 100644 index 0000000..78d9916 --- /dev/null +++ b/plugin.xml @@ -0,0 +1,31 @@ + + + com.fr.plugin.JSD10117 + + yes + 1.10 + 10.0~11.0 + 2022-01-05 + fr.open + + + + [2022-5-7]项目启动

+ ]]> +
+ com.fr.plugin.oauth + + + + + + + + + + + + +
+ diff --git a/src/main/java/com/fr/plugin/oauth/LoginFilter.java b/src/main/java/com/fr/plugin/oauth/LoginFilter.java new file mode 100644 index 0000000..be1cad3 --- /dev/null +++ b/src/main/java/com/fr/plugin/oauth/LoginFilter.java @@ -0,0 +1,143 @@ +package com.fr.plugin.oauth; + +import com.fr.data.NetworkHelper; +import com.fr.decision.fun.impl.AbstractGlobalRequestFilterProvider; +import com.fr.decision.mobile.terminal.TerminalHandler; +import com.fr.decision.webservice.bean.authentication.LoginClientBean; +import com.fr.decision.webservice.v10.login.LoginService; +import com.fr.decision.webservice.v10.login.TokenResource; +import com.fr.log.FineLoggerFactory; +import com.fr.plugin.oauth.utils.HtmlUtils; +import com.fr.plugin.oauth.utils.RedirectUtils; +import com.fr.plugin.transform.ExecuteFunctionRecord; +import com.fr.plugin.transform.FunctionRecorder; +import com.fr.stable.StringUtils; + +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.UnsupportedEncodingException; +import java.net.URLDecoder; +import java.net.URLEncoder; + +@FunctionRecorder +public class LoginFilter extends AbstractGlobalRequestFilterProvider { + + private static final String REDIRECT_URI = "/plugin/public/com.fr.plugin.JSD10117/authLogin"; + + @Override + public void init(FilterConfig filterConfig) { + W2Config.getInstance(); + super.init(filterConfig); + } + + @Override + public String filterName() { + return "loginFilter"; + } + + @ExecuteFunctionRecord + @Override + public String[] urlPatterns() { + return new String[]{ + /*"/decision/login", + "/login.html"*/ + "/*" + }; + } + + + @Override + public void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain filterChain) { + try { + boolean isLoginReq = isLoginReqest(req); + // 约定:放在iframe中的链接带参数iniframe=true + boolean iniframe = Boolean.parseBoolean(req.getParameter("iniframe")); + + boolean sharetoken = Boolean.parseBoolean(req.getParameter("sharetoken")); + + if (isLoginReq || iniframe || sharetoken) { + LoginClientBean bean = isLogined(req); + if (bean == null) { + boolean redirect = req.getMethod().equals("GET"); + if (redirect) { + gotoAuthorize(req, res, iniframe, sharetoken); + return; + } + } else { + // 登录成功,跳转至目标页面 + RedirectUtils.redirect(bean.getUsername(), W2Config.getInstance(), bean.getToken(), res); + return; + } + } + filterChain.doFilter(req, res); + + } catch (Exception e) { + FineLoggerFactory.getLogger().error(e.getMessage()); + } + } + + /** + * 跳转到统一登录页面 + */ + public static void gotoAuthorize(HttpServletRequest req, HttpServletResponse res, boolean inIframe, boolean sharetoken) throws UnsupportedEncodingException { + W2Config w2Config = W2Config.getInstance(); + String callBack = URLEncoder.encode(w2Config.getFrurl() + REDIRECT_URI, "UTF-8"); + if (inIframe) { + callBack = URLEncoder.encode(w2Config.getFrurl() + REDIRECT_URI + "?iframeurl=" + getUrl(req), "UTF-8"); + } else if (sharetoken) { + callBack = URLEncoder.encode(w2Config.getFrurl() + REDIRECT_URI + "?redirecturl=" + getUrl(req), "UTF-8"); + } + + callBack = callBack.replace("sharetoken", "nosharetoken"); + callBack = callBack.replace("iniframe", "noiniframe"); + + String url = ""; + if (sharetoken) { + url = callBack; + } else { + url = w2Config.getIdf() + callBack; + } + HtmlUtils.sendRedirect("", url, res); + } + + private LoginClientBean isLogined(HttpServletRequest req) { + LoginClientBean bean = null; + try { + String token = TokenResource.COOKIE.getToken(req); + bean = LoginService.getInstance().loginStatusValid(token, TerminalHandler.getTerminal(req, NetworkHelper.getDevice(req))); + } catch (Exception e) { + bean = null; + FineLoggerFactory.getLogger().error(e.getMessage()); + } + return bean; + } + + private boolean isLoginReqest(HttpServletRequest req) { + String url = req.getRequestURL().toString(); + if (StringUtils.isNotBlank(url)) { + if (url.endsWith("/decision/login") || url.endsWith("/login.html")) { + return true; + } + } + return false; + } + + private static String getUrl(HttpServletRequest request) { + String url = request.getRequestURL().toString(); + String param = request.getQueryString(); + if (StringUtils.isNotBlank(param)) { + try { + if (request.getCharacterEncoding() != null) { + param = URLDecoder.decode(param, request.getCharacterEncoding()); + } + } catch (Exception e) { + FineLoggerFactory.getLogger().error(e.getMessage()); + } + url = url + "?" + param; + } + return url; + } + +} diff --git a/src/main/java/com/fr/plugin/oauth/LoginOutComponent.java b/src/main/java/com/fr/plugin/oauth/LoginOutComponent.java new file mode 100644 index 0000000..2caf0cd --- /dev/null +++ b/src/main/java/com/fr/plugin/oauth/LoginOutComponent.java @@ -0,0 +1,22 @@ +package com.fr.plugin.oauth; + +import com.fr.web.struct.Component; +import com.fr.web.struct.browser.RequestClient; +import com.fr.web.struct.category.ScriptPath; +import com.fr.web.struct.category.StylePath; + +public class LoginOutComponent extends Component { + public static LoginOutComponent KEY = new LoginOutComponent(); + + + + @Override + public ScriptPath script(RequestClient requestClient) { + return ScriptPath.build("/com/fr/plugin/oauth/web/logout.js"); + } + + @Override + public StylePath style(RequestClient requestClient) { + return StylePath.EMPTY; + } +} diff --git a/src/main/java/com/fr/plugin/oauth/LogoutFilter.java b/src/main/java/com/fr/plugin/oauth/LogoutFilter.java new file mode 100644 index 0000000..e0ad4f6 --- /dev/null +++ b/src/main/java/com/fr/plugin/oauth/LogoutFilter.java @@ -0,0 +1,70 @@ +package com.fr.plugin.oauth; + +import com.fr.decision.fun.impl.AbstractGlobalRequestFilterProvider; +import com.fr.plugin.oauth.utils.CookieUtils; +import com.fr.plugin.oauth.utils.GZipUtil; +import com.fr.plugin.oauth.utils.ResponseWrapper; + +import javax.servlet.FilterChain; +import javax.servlet.ServletOutputStream; +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import static javax.servlet.http.HttpServletResponse.SC_OK; + +public class LogoutFilter extends AbstractGlobalRequestFilterProvider { + @Override + public String filterName() { + return "logoutFilter"; + } + + @Override + public String[] urlPatterns() { + return new String[]{ + "/decision/logout" + }; + } + + @Override + public void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain filterChain) { + try { + ResponseWrapper responseWrapper = new ResponseWrapper(res); + filterChain.doFilter(req, responseWrapper); + + //String newContent = null; + String newContent = "{\"data\":\"https://xx/\"}"; + + byte[] content = responseWrapper.getContent(); + if (content.length > 0 && res.getStatus() == SC_OK) { + String header = res.getHeader("Content-Encoding"); + boolean isGzip = "gzip".equalsIgnoreCase(header); + if (isGzip) { + content = GZipUtil.decompress(content); + } + + + byte[] result = null; + + if (isGzip) { + result = GZipUtil.compress(newContent.getBytes("UTF-8")); + res.setHeader("Content-Encoding", "gzip"); + } else { + result = newContent.getBytes("UTF-8"); + } + //把返回值输出到客户端 + res.setContentLength(-1); + res.setContentType("text/html;charset=UTF-8"); + ServletOutputStream out = res.getOutputStream(); + out.write(result); + out.flush(); + out.close(); + res.flushBuffer(); + } + Cookie cookie = CookieUtils.getLoginPathCookie(req); + CookieUtils.deleteCookie(res, cookie); + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/src/main/java/com/fr/plugin/oauth/MyFunction.java b/src/main/java/com/fr/plugin/oauth/MyFunction.java new file mode 100644 index 0000000..8a3ee15 --- /dev/null +++ b/src/main/java/com/fr/plugin/oauth/MyFunction.java @@ -0,0 +1,38 @@ +package com.fr.plugin.oauth; + +import com.fr.decision.fun.impl.AbstractSystemOptionProvider; +import com.fr.decision.web.MainComponent; +import com.fr.plugin.transform.ExecuteFunctionRecord; +import com.fr.plugin.transform.FunctionRecorder; +import com.fr.web.struct.Atom; + +public class MyFunction extends AbstractSystemOptionProvider { + public MyFunction() { + System.out.println("zc"); + } + + @Override + public String id() { + return "mb"; + } + + @Override + public String displayName() { + return "mb"; + } + + @Override + public int sortIndex() { + return 2; + } + + @Override + public Atom attach() { + return MainComponent.KEY; + } + + @Override + public Atom client() { + return LoginOutComponent.KEY; + } +} diff --git a/src/main/java/com/fr/plugin/oauth/W2Config.java b/src/main/java/com/fr/plugin/oauth/W2Config.java new file mode 100644 index 0000000..9bf0d8b --- /dev/null +++ b/src/main/java/com/fr/plugin/oauth/W2Config.java @@ -0,0 +1,73 @@ +package com.fr.plugin.oauth; + +import com.fr.config.*; +import com.fr.config.holder.Conf; +import com.fr.config.holder.factory.Holders; + + +@Visualization(category = "统一认证单点配置") +public class W2Config extends DefaultConfiguration { + private static volatile W2Config config = null; + + public static W2Config getInstance() { + if (config == null) { + config = ConfigContext.getConfigInstance(W2Config.class); + } + return config; + } + + /** + * 注: + * 更改服务器后,需要修改2个地方地址: + * 1) 这里; + * 2) logout.js + * 3) 对应于验证服务器,需要修改回调地址FANRUAN_HOST+frurl + */ + + // product + private static final String FANRUAN_HOST = "http://xx/fineBi/webroot/"; + + + @Identifier(value = "frurl", name = "当前报表域名", description = "", status = Status.SHOW) + private Conf frurl = Holders.simple(FANRUAN_HOST + "decision"); + + @Identifier(value = "idf", name = "认证中心url", description = "", status = Status.SHOW) + private Conf idf = Holders.simple("http://xx/lckj/pawm-uc/account_login.html?url="); + + @Identifier(value = "userinfo", name = "获取用户信息", description = "", status = Status.SHOW) + + private Conf apiUserInfo = Holders.simple("http://xx/wmuc/loginServer/loginValidateToken"); + + public String getFrurl() { + return frurl.get(); + } + + public void setFrurl(String frurl) { + this.frurl.set(frurl); + } + + public String getIdf() { + return idf.get(); + } + + public void setIdf(Conf idf) { + this.idf = idf; + } + + public String getApiUserInfo() { + return apiUserInfo.get(); + } + + public void setApiUserInfo(String apiUserInfo) { + this.apiUserInfo.set(apiUserInfo); + } + + @Override + public Object clone() throws CloneNotSupportedException { + W2Config cloned = (W2Config) super.clone(); + cloned.frurl = (Conf) frurl.clone(); + cloned.idf = (Conf) idf.clone(); + cloned.apiUserInfo = (Conf) apiUserInfo.clone(); + return cloned; + } +} diff --git a/src/main/java/com/fr/plugin/oauth/http/HttpHandlerProvider.java b/src/main/java/com/fr/plugin/oauth/http/HttpHandlerProvider.java new file mode 100644 index 0000000..c0d996e --- /dev/null +++ b/src/main/java/com/fr/plugin/oauth/http/HttpHandlerProvider.java @@ -0,0 +1,16 @@ +package com.fr.plugin.oauth.http; + +import com.fr.decision.fun.HttpHandler; +import com.fr.decision.fun.impl.AbstractHttpHandlerProvider; + +public class HttpHandlerProvider extends AbstractHttpHandlerProvider { + HttpHandler[] actions = new HttpHandler[]{ + new OauthLoginHandler(), + new OauthLogoutHandler() + }; + + @Override + public HttpHandler[] registerHandlers() { + return actions; + } +} diff --git a/src/main/java/com/fr/plugin/oauth/http/OauthLoginHandler.java b/src/main/java/com/fr/plugin/oauth/http/OauthLoginHandler.java new file mode 100644 index 0000000..4822c17 --- /dev/null +++ b/src/main/java/com/fr/plugin/oauth/http/OauthLoginHandler.java @@ -0,0 +1,157 @@ +package com.fr.plugin.oauth.http; + +import com.fanruan.api.json.JSONKit; +import com.finebi.constant.Constants; +import com.fr.decision.fun.impl.BaseHttpHandler; +import com.fr.decision.webservice.v10.login.LoginService; +import com.fr.json.JSONArray; +import com.fr.json.JSONObject; +import com.fr.log.FineLoggerFactory; +import com.fr.log.FineLoggerProvider; +import com.fr.plugin.oauth.LoginFilter; +import com.fr.plugin.oauth.W2Config; +import com.fr.plugin.oauth.utils.CookieUtils; +import com.fr.plugin.oauth.utils.HtmlUtils; +import com.fr.plugin.oauth.utils.HttpUtils; +import com.fr.plugin.oauth.utils.RedirectUtils; +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 javax.servlet.http.HttpSession; +import java.io.IOException; +import java.util.*; + +public class OauthLoginHandler extends BaseHttpHandler { + FineLoggerProvider logger = FineLoggerFactory.getLogger(); + + @Override + public RequestMethod getMethod() { + return RequestMethod.GET; + } + + @Override + public String getPath() { + return "/authLogin"; + } + + @Override + public boolean isPublic() { + return true; + } + + @Override + public void handle(HttpServletRequest req, HttpServletResponse resp) throws Exception { + W2Config w2Config = W2Config.getInstance(); + + String accessToken = req.getParameter("ssoTokenId"); + if (StringUtils.isBlank(accessToken)) { + WebUtils.printAsString(resp, new String("未能获取token,登陆失败!".getBytes("gbk"), "utf-8")); + return; + } + + String userName = getUserName(accessToken); + String token = login(req, resp, userName); + + if (StringUtils.isBlank(token)) { + WebUtils.printAsString(resp, userName + new String("该用户没有本系统权限".getBytes("gbk"), "utf-8")); + return; + } + + CookieUtils.setLoginCookie(resp); + + String iframeUrl = req.getParameter("iframeurl"); + String redirecturl = req.getParameter("redirecturl"); + if (StringUtils.isNotBlank(iframeUrl)) { + // 跳转至报表链接 + gotoFormLink(req, resp, iframeUrl); + } else if (StringUtils.isNotBlank(redirecturl)) { + HtmlUtils.sendRedirect(userName, redirecturl, token, resp, "/com/fr/plugin/oauth/web/redirectbyrole.html"); + } else { + // 跳转至报表管理平台 + RedirectUtils.redirect(userName, w2Config, token, resp); + } + //RedirectUtils.redirect(userName, w2Config, token, resp); + } + + + private String getUserName(String accessToken) { + //String url = String.format(API_GET_USERINFO, W2Config.getInstance().getIdf()); + String url = String.format(W2Config.getInstance().getApiUserInfo(), W2Config.getInstance().getIdf()); + Map params = new HashMap<>(); + params.put("tokenId", accessToken); + String json = null; + try { + //json = HttpKit.get(url, params); + json = HttpUtils.get(url, params); + logger.info("get user info response:" + json); + JSONObject jsonObject = JSONKit.create(json); + if (jsonObject != null && StringUtils.equals(jsonObject.getString("responseCode"), "000000")) { + JSONObject user = jsonObject.getJSONObject("data"); + String um = user.getString("umAccount"); + FineLoggerFactory.getLogger().info("have got user name :" + um); + if (StringUtils.isNotBlank(um)) { + return um.toUpperCase(); + } + } + + FineLoggerFactory.getLogger().info("have not got user name"); + return ""; + } catch (Exception e) { + FineLoggerFactory.getLogger().error(e.getMessage()); + } + return ""; + } + + /** + * 后台登录方法 + */ + private String login(HttpServletRequest req, HttpServletResponse res, String username) { + HttpSession session = req.getSession(true); + try { + return LoginService.getInstance().login(req, res, username); +// session.removeAttribute(DecisionServiceConstants.FINE_AUTH_TOKEN_NAME); + } catch (Exception e) { + FineLoggerFactory.getLogger().error(e.getMessage(), e); + FineLoggerFactory.getLogger().error("login failed"); + } +// session.setAttribute(DecisionServiceConstants.FINE_AUTH_TOKEN_NAME, token); + return ""; + } + + /** + * 跳转至报表链接 + * 该链接放在iframe中,为了写入cookie,需要特殊处理 + */ + private void gotoFormLink(HttpServletRequest req, HttpServletResponse resp, String url) { + boolean resetCookie = false; + String userAgent = req.getHeader("User-Agent"); + if (StringUtils.isNotBlank(userAgent) && userAgent.contains("Chrome")) { + resetCookie = true; + } + + Collection collection = resp.getHeaders("Set-Cookie"); + if (collection != null && collection.size() > 0) { + HashMap hashMap = new HashMap(); + String cookies = ""; + if (resetCookie) { + for (String c : collection) { + cookies = cookies + c + ";Secure;SameSite=None;@@"; + } + } + hashMap.put("cookies", cookies); + hashMap.put("callBack", url); + + try { + WebUtils.writeOutTemplate("/com/fr/plugin/oauth/web/redirectcook.html", resp, hashMap); + } catch (IOException e) { + FineLoggerFactory.getLogger().error(e.getMessage()); + } + } else { + FineLoggerFactory.getLogger().error("login failed, there must be cookies"); + } + } + +} diff --git a/src/main/java/com/fr/plugin/oauth/http/OauthLogoutHandler.java b/src/main/java/com/fr/plugin/oauth/http/OauthLogoutHandler.java new file mode 100644 index 0000000..b047e47 --- /dev/null +++ b/src/main/java/com/fr/plugin/oauth/http/OauthLogoutHandler.java @@ -0,0 +1,38 @@ +package com.fr.plugin.oauth.http; + +import com.fr.decision.fun.impl.BaseHttpHandler; +import com.fr.decision.webservice.v10.login.LoginService; +import com.fr.plugin.oauth.W2Config; +import com.fr.plugin.oauth.utils.HtmlUtils; +import com.fr.third.springframework.web.bind.annotation.RequestMethod; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +/** + * 这个类可能用不上,暂时留着看 + */ +public class OauthLogoutHandler extends BaseHttpHandler { + // 这个接口会导致竹云所有账号都退出 + private static final String API_GLO = "%s/idp/profile/OAUTH2/Redirect/GLO?redirctToUrl=%s&redirectToLogin=true&entityId=%s"; + + @Override + public RequestMethod getMethod() { + return RequestMethod.GET; + } + + @Override + public String getPath() { + return "/authLogout"; + } + + @Override + public boolean isPublic() { + return true; + } + + @Override + public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception { + + } +} \ No newline at end of file diff --git a/src/main/java/com/fr/plugin/oauth/utils/CookieUtils.java b/src/main/java/com/fr/plugin/oauth/utils/CookieUtils.java new file mode 100644 index 0000000..fb34b54 --- /dev/null +++ b/src/main/java/com/fr/plugin/oauth/utils/CookieUtils.java @@ -0,0 +1,50 @@ +package com.fr.plugin.oauth.utils; + +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +public class CookieUtils { + + public static final String COOKIE_LOGINPATH_NAME = "loginpath"; + public static final String COOKIE_LOGINPATH_VALUE = "sso"; + + public static void setLoginCookie(HttpServletResponse res) { + Cookie cookie = new Cookie(COOKIE_LOGINPATH_NAME, COOKIE_LOGINPATH_VALUE); + cookie.setPath("/"); + res.addCookie(cookie); + } + + public static boolean isLoginFromSSO(HttpServletRequest req) { + Cookie[] cookies = req.getCookies(); + for (Cookie cookie : cookies) { + if (COOKIE_LOGINPATH_NAME.equals(cookie.getName())) { + if (COOKIE_LOGINPATH_VALUE.equals(cookie.getValue())) { + return true; + } + } + } + return false; + } + + public static Cookie getCookie(HttpServletRequest req, String name) { + Cookie[] cookies = req.getCookies(); + for (Cookie cookie : cookies) { + if (name.equals(cookie.getName())) { + return cookie; + } + } + return null; + } + + public static Cookie getLoginPathCookie(HttpServletRequest req) { + return getCookie(req, COOKIE_LOGINPATH_NAME); + } + + public static void deleteCookie(HttpServletResponse res, Cookie cookie) { + if (cookie != null){ + cookie.setMaxAge(0); + res.addCookie(cookie); + } + } +} diff --git a/src/main/java/com/fr/plugin/oauth/utils/GZipUtil.java b/src/main/java/com/fr/plugin/oauth/utils/GZipUtil.java new file mode 100644 index 0000000..b62e481 --- /dev/null +++ b/src/main/java/com/fr/plugin/oauth/utils/GZipUtil.java @@ -0,0 +1,62 @@ +package com.fr.plugin.oauth.utils; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.zip.GZIPInputStream; +import java.util.zip.GZIPOutputStream; + +public class GZipUtil { + public static final int BUFFER = 1024; + + /** + * 数据压缩 + */ + public static void compress(InputStream is, OutputStream os) throws Exception { + GZIPOutputStream gos = new GZIPOutputStream(os); + int count; + byte data[] = new byte[BUFFER]; + while ((count = is.read(data, 0, BUFFER)) != -1) { + gos.write(data, 0, count); + } + gos.finish(); + gos.flush(); + gos.close(); + } + + public static byte[] compress(byte[] data) throws Exception { + ByteArrayInputStream bais = new ByteArrayInputStream(data); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + compress(bais, baos); + byte[] output = baos.toByteArray(); + baos.flush(); + baos.close(); + bais.close(); + return output; + } + + /** + * 数据解压 + */ + public static void decompress(InputStream is, OutputStream os) throws Exception { + GZIPInputStream gis = new GZIPInputStream(is); + int count; + byte data[] = new byte[BUFFER]; + while ((count = gis.read(data, 0, BUFFER)) != -1) { + os.write(data, 0, count); + } + gis.close(); + } + + public static byte[] decompress(byte[] data) throws Exception { + ByteArrayInputStream bais = new ByteArrayInputStream(data); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + decompress(bais, baos); + byte[] output = baos.toByteArray(); + baos.flush(); + baos.close(); + bais.close(); + return output; + } +} \ No newline at end of file diff --git a/src/main/java/com/fr/plugin/oauth/utils/HtmlUtils.java b/src/main/java/com/fr/plugin/oauth/utils/HtmlUtils.java new file mode 100644 index 0000000..68a89f9 --- /dev/null +++ b/src/main/java/com/fr/plugin/oauth/utils/HtmlUtils.java @@ -0,0 +1,33 @@ +package com.fr.plugin.oauth.utils; + +import com.fr.web.utils.WebUtils; + +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.HashMap; + +public class HtmlUtils { + public static void sendRedirect(String userName,String url, HttpServletResponse httpServletResponse) { + HashMap hashMap = new HashMap(); + hashMap.put("loginUser", userName); + hashMap.put("callBack", url); + try { + WebUtils.writeOutTemplate("/com/fr/plugin/oauth/web/redirect.html", httpServletResponse, hashMap); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public static void sendRedirect(String userName,String url, String token, HttpServletResponse httpServletResponse, String html) { + HashMap hashMap = new HashMap(); + hashMap.put("loginUser", userName); + hashMap.put("callBack", url); + hashMap.put("accessToken", token); + try { + WebUtils.writeOutTemplate(html, httpServletResponse, hashMap); + } catch (IOException e) { + e.printStackTrace(); + } + } + +} diff --git a/src/main/java/com/fr/plugin/oauth/utils/HttpUtils.java b/src/main/java/com/fr/plugin/oauth/utils/HttpUtils.java new file mode 100644 index 0000000..a67b1a5 --- /dev/null +++ b/src/main/java/com/fr/plugin/oauth/utils/HttpUtils.java @@ -0,0 +1,199 @@ +package com.fr.plugin.oauth.utils; + +import com.fr.base.ServerConfig; +import com.fr.json.JSONObject; +import com.fr.third.fasterxml.jackson.core.JsonParseException; +import com.fr.third.fasterxml.jackson.databind.DeserializationFeature; +import com.fr.third.fasterxml.jackson.databind.JsonMappingException; +import com.fr.third.fasterxml.jackson.databind.ObjectMapper; + +import javax.net.ssl.HttpsURLConnection; +import javax.servlet.http.HttpServletRequest; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.URLEncoder; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + +public class HttpUtils { + private static ObjectMapper mapper = new ObjectMapper(); + + static { + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + } + + public static String getRequestPayload(HttpServletRequest req) { + StringBuilder sb = new StringBuilder(); + try (BufferedReader reader = req.getReader();) { + char[] buff = new char[1024]; + int len; + while ((len = reader.read(buff)) != -1) { + sb.append(buff, 0, len); + } + } catch (IOException e) { + e.printStackTrace(); + } + return sb.toString(); + } + + public static T json2Object(String json, Class typeRef) { + try { + return (T) mapper.readValue(json, typeRef); + } catch (JsonParseException e) { + e.printStackTrace(); + } catch (JsonMappingException e) { + e.printStackTrace(); + } catch (IOException e) { + } + return null; + } + + public static String object2Json(Object ok) { + try { + return mapper.writeValueAsString(ok); + } catch (JsonParseException e) { + } catch (JsonMappingException e) { + } catch (IOException e) { + } + return ""; + } + + public JSONObject createResp(String uid, String reqId) { + JSONObject json = new JSONObject(); + json.put("uid", uid); + json.put("bimRequestId", reqId); + json.put("resultCode", "0"); + json.put("message", "success"); + return json; + } + + + private static String getParam(Map var0, String enc) { + String var1 = ""; + Set var2 = var0.keySet(); + Iterator var3 = var2.iterator(); + + while (var3.hasNext()) { + String var4 = (String) var3.next(); + String var5 = var0.get(var4) + ""; + + try { + var1 = var1 + (var1.length() == 0 ? "" : "&") + URLEncoder.encode(var4, enc) + "=" + URLEncoder.encode(var5, enc); + } catch (Exception var7) { + ; + } + } + + return var1; + } + + public static boolean isHttps(URL url) { + return url.getProtocol().toLowerCase().equals("https"); + } + + public static String get(String path, Map param) { + String paramStr = getParam(param, ServerConfig.getInstance().getServerCharset()); + BufferedReader input = null; + StringBuilder sb = null; + URL url = null; + HttpURLConnection con = null; + try { + url = new URL(path + (paramStr.length() > 0 ? "?" + paramStr.toString() : "")); + if (isHttps(url)) { + HttpsUtils.trustAllHosts(); + HttpsURLConnection httpsCon = (HttpsURLConnection) url.openConnection(); + httpsCon.setHostnameVerifier(HttpsUtils.DO_NOT_VERIFY); + con = httpsCon; + } else { + con = (HttpURLConnection) url.openConnection(); + } + + con.setRequestProperty("accept", "*/*"); + con.setRequestMethod("GET"); + con.setRequestProperty("Accept-Charset", "UTF-8"); + + input = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8")); + sb = new StringBuilder(); + String s; + while ((s = input.readLine()) != null) { + sb.append(s).append("\n"); + } + } catch (Exception e) { + e.printStackTrace(); + } finally { + // close buffered + if (input != null) { + try { + input.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + // disconnecting releases the timescroller held by a connection so they may be closed or reused + if (con != null) { + con.disconnect(); + } + } + return sb == null ? null : sb.toString(); + } + + + public static String post(String path, Map param) { + String paramStr = getParam(param, ServerConfig.getInstance().getServerCharset()); + PrintWriter writer = null; + BufferedReader reader = null; + HttpURLConnection con = null; + String result = ""; + + try { + URL url = new URL(path); + if (isHttps(url)) { + HttpsUtils.trustAllHosts(); + HttpsURLConnection httpsCon = (HttpsURLConnection) url.openConnection(); + httpsCon.setHostnameVerifier(HttpsUtils.DO_NOT_VERIFY); + con = httpsCon; + } else { + con = (HttpURLConnection) url.openConnection(); + } + + con.setRequestProperty("accept", "*/*"); + con.setRequestProperty("connection", "Keep-Alive"); + //con.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); +// var8.setRequestProperty("Accept-Charset", "UTF-8"); + con.setRequestMethod("POST"); + con.setDoOutput(true); + con.setDoInput(true); + writer = new PrintWriter(con.getOutputStream()); + writer.print(paramStr); + writer.flush(); + + String line; + for (reader = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8")); (line = reader.readLine()) != null; result = result + line) { + ; + } + } catch (Exception e) { + e.printStackTrace(); + } finally { + try { + if (writer != null) { + writer.close(); + } + + if (reader != null) { + reader.close(); + } + } catch (Exception var17) { + ; + } + + } + + return result; + } +} diff --git a/src/main/java/com/fr/plugin/oauth/utils/HttpsUtils.java b/src/main/java/com/fr/plugin/oauth/utils/HttpsUtils.java new file mode 100644 index 0000000..783cd85 --- /dev/null +++ b/src/main/java/com/fr/plugin/oauth/utils/HttpsUtils.java @@ -0,0 +1,52 @@ +package com.fr.plugin.oauth.utils; + +import com.fr.log.FineLoggerFactory; + +import javax.net.ssl.*; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; + +public class HttpsUtils { + final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() { + public boolean verify(String hostname, SSLSession session) { + return true; + } + }; + + // Create a trust manager that does not validate certificate chains + static TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() { + public java.security.cert.X509Certificate[] getAcceptedIssuers() { + return new java.security.cert.X509Certificate[]{}; + } + + public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { + FineLoggerFactory.getLogger().error("checkClientTrusted"); + } + + public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { + FineLoggerFactory.getLogger().error("checkServerTrusted"); + } + }}; + + static SSLContext sc; + + static { + trustAllHosts(); + } + + /** + * Trust every server - dont check for any certificate + */ + public static void trustAllHosts() { + // Install the all-trusting trust manager + try { + if (sc == null) { + sc = SSLContext.getInstance("TLS"); + sc.init(null, trustAllCerts, new java.security.SecureRandom()); + } + HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); + } catch (Exception e) { + FineLoggerFactory.getLogger().error(e.getMessage()); + } + } +} diff --git a/src/main/java/com/fr/plugin/oauth/utils/RedirectUtils.java b/src/main/java/com/fr/plugin/oauth/utils/RedirectUtils.java new file mode 100644 index 0000000..5ccaf16 --- /dev/null +++ b/src/main/java/com/fr/plugin/oauth/utils/RedirectUtils.java @@ -0,0 +1,101 @@ +package com.fr.plugin.oauth.utils; + +import com.fr.io.utils.ResourceIOUtils; +import com.fr.plugin.oauth.W2Config; + +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.io.InputStream; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.util.Properties; + +public class RedirectUtils { + + public static String ORACLE; + public static String USER_NAME; + public static String PASSWORD; + + public static Properties getProperties() throws IOException { + InputStream is = ResourceIOUtils.read("/resources/oauth2095.properties"); + Properties prop = new Properties(); + prop.load(is); + + ORACLE = prop.getProperty("oracle", "jdbc:oracle:thin:@1xx:xx:xx"); + USER_NAME = prop.getProperty("username", "xx"); + PASSWORD = prop.getProperty("password", "xx"); + + return prop; + } + + /** + * 登录成功,跳转至目标页面 + */ + public static void redirect(String userName, W2Config config, String token, HttpServletResponse resp) throws IOException { + String url = config.getFrurl(); + + HtmlUtils.sendRedirect(userName, url, token, resp, "/com/fr/plugin/oauth/web/redirectbyrole.html"); + } + + private static String getRole(String userName) { + String role = ""; + Connection con = null; + PreparedStatement pre = null; + ResultSet result = null; + + try { + Class.forName("oracle.jdbc.driver.OracleDriver"); + + String _result = ORACLE; + String us = USER_NAME; + String pw = PASSWORD; + con = DriverManager.getConnection(_result, us, pw); + String sql = "SELECT ORG_LEVEL FROM HR_MANAGEMENT WHERE USERNAME = ?"; + pre = con.prepareStatement(sql); + pre.setString(1, userName); + result = pre.executeQuery(); + if (result.next()) { + role = result.getString("ORG_LEVEL"); + } + } catch (Exception e) { + e.printStackTrace(); + + try { + if (result != null) { + result.close(); + } + + if (pre != null) { + pre.close(); + } + + if (con != null) { + con.close(); + } + } catch (Exception var19) { + var19.printStackTrace(); + } + } finally { + try { + if (result != null) { + result.close(); + } + + if (pre != null) { + pre.close(); + } + + if (con != null) { + con.close(); + } + } catch (Exception e) { + e.printStackTrace(); + } + + } + + return role; + } +} diff --git a/src/main/java/com/fr/plugin/oauth/utils/ResponseWrapper.java b/src/main/java/com/fr/plugin/oauth/utils/ResponseWrapper.java new file mode 100644 index 0000000..db007fe --- /dev/null +++ b/src/main/java/com/fr/plugin/oauth/utils/ResponseWrapper.java @@ -0,0 +1,61 @@ +package com.fr.plugin.oauth.utils; + +import javax.servlet.ServletOutputStream; +import javax.servlet.WriteListener; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpServletResponseWrapper; +import java.io.ByteArrayOutputStream; +import java.io.IOException; + +public class ResponseWrapper extends HttpServletResponseWrapper { + + private ByteArrayOutputStream buffer; + private ServletOutputStream out; + + public ResponseWrapper(HttpServletResponse httpServletResponse) { + super(httpServletResponse); + buffer = new ByteArrayOutputStream(); + out = new WrapperOutputStream(buffer); + } + + @Override + public ServletOutputStream getOutputStream() throws IOException { + return out; + } + + @Override + public void flushBuffer() throws IOException { + if (out != null) { + out.flush(); + } + } + + public byte[] getContent() throws IOException { + flushBuffer(); + return buffer.toByteArray(); + } + + class WrapperOutputStream extends ServletOutputStream { + private ByteArrayOutputStream bos; + + public WrapperOutputStream(ByteArrayOutputStream bos) { + this.bos = bos; + } + + @Override + public void write(int b) throws IOException { + bos.write(b); + } + + @Override + public boolean isReady() { + return false; + } + + @Override + public void setWriteListener(WriteListener arg0) { + + } + } + +} diff --git a/src/main/resources/com/fr/plugin/oauth/web/logout.js b/src/main/resources/com/fr/plugin/oauth/web/logout.js new file mode 100644 index 0000000..bac3a57 --- /dev/null +++ b/src/main/resources/com/fr/plugin/oauth/web/logout.js @@ -0,0 +1,12 @@ +;(function () { + Dec.Logout = function() { + Dec.Utils.logout(function(e) { + BI.Cache.deleteCookie(DecCst.Cookie.TOKEN, Dec.system.cookiePath); + setTimeout(function () { + + window.location.href = "http://xx/fineBi/webroot/decision"; + + },300); + }) + } +})(); diff --git a/src/main/resources/com/fr/plugin/oauth/web/redirect.html b/src/main/resources/com/fr/plugin/oauth/web/redirect.html new file mode 100644 index 0000000..c6a0e90 --- /dev/null +++ b/src/main/resources/com/fr/plugin/oauth/web/redirect.html @@ -0,0 +1,11 @@ + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/com/fr/plugin/oauth/web/redirectbyrole.html b/src/main/resources/com/fr/plugin/oauth/web/redirectbyrole.html new file mode 100644 index 0000000..1c727da --- /dev/null +++ b/src/main/resources/com/fr/plugin/oauth/web/redirectbyrole.html @@ -0,0 +1,32 @@ + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/com/fr/plugin/oauth/web/redirectcook.html b/src/main/resources/com/fr/plugin/oauth/web/redirectcook.html new file mode 100644 index 0000000..426a7a9 --- /dev/null +++ b/src/main/resources/com/fr/plugin/oauth/web/redirectcook.html @@ -0,0 +1,18 @@ + + + + + + + + +