Browse Source

open

master
pioneer 2 years ago
commit
a4cd622966
  1. 6
      README.md
  2. BIN
      doc/JSD-9787-需求确认书V1.docx
  3. BIN
      doc/用户同步和单点配置文档.docx
  4. BIN
      lib/finekit-10.0-20200712.jar
  5. 27
      plugin.xml
  6. 99
      src/main/java/com/fr/plugin/Aesutils.java
  7. 117
      src/main/java/com/fr/plugin/HttpUtils.java
  8. 204
      src/main/java/com/fr/plugin/LogoOutFilter.java
  9. 191
      src/main/java/com/fr/plugin/PLFilter.java
  10. 12
      src/main/java/com/fr/plugin/PLFunction.java
  11. 20
      src/main/java/com/fr/plugin/PLHttpHander.java
  12. 15
      src/main/java/com/fr/plugin/PLLifeCycleMonitor.java
  13. 193
      src/main/java/com/fr/plugin/PLLoginFilter.java
  14. 17
      src/main/java/com/fr/plugin/PLUrlAliasProvider.java
  15. 26
      src/main/java/com/fr/plugin/SafeCheckUtils.java
  16. 93
      src/main/java/com/fr/plugin/ZtgtConfig.java
  17. 198
      src/main/java/com/fr/plugin/handers/AddAppAccountHander.java
  18. 230
      src/main/java/com/fr/plugin/handers/LoginCallBackHandler.java
  19. 116
      src/main/java/com/fr/plugin/handers/SynDepstHander.java
  20. 144
      src/main/java/com/fr/plugin/handers/SynPositionHander.java
  21. 11
      src/main/resources/com/fr/plugin/redirect.html

6
README.md

@ -0,0 +1,6 @@
# open-JSD-9787
JSD-9787 用户同步和单点\
免责说明:该源码为第三方爱好者提供,不保证源码和方案的可靠性,也不提供任何形式的源码教学指导和协助!\
仅作为开发者学习参考使用!禁止用于任何商业用途!\
为保护开发者隐私,开发者信息已隐去!若原开发者希望公开自己的信息,可联系【pioneer】处理。

BIN
doc/JSD-9787-需求确认书V1.docx

Binary file not shown.

BIN
doc/用户同步和单点配置文档.docx

Binary file not shown.

BIN
lib/finekit-10.0-20200712.jar

Binary file not shown.

27
plugin.xml

@ -0,0 +1,27 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<plugin>
<id>com.fr.plugin.paila.sync</id>
<name><![CDATA[用户同步和单点]]></name>
<active>yes</active>
<version>1.2.1</version>
<env-version>10.0</env-version>
<jartime>2018-03-10</jartime>
<vendor>fr.open</vendor>
<description><![CDATA[用户同步和单点]]></description>
<function-recorder class="com.fr.plugin.PLFunction"/>
<change-notes>
<![CDATA[
<p>[2022-03-12]项目启动</p>
]]>
</change-notes>
<main-package>com.fr.plugin</main-package>
<!--插件生命周期接口-->
<lifecycle-monitor class="com.fr.plugin.PLLifeCycleMonitor"/>
<extra-decision>
<!--插件注入HttpHandler-->
<HttpHandlerProvider class="com.fr.plugin.PLHttpHander"/>
<URLAliasProvider class="com.fr.plugin.PLUrlAliasProvider"/>
<GlobalRequestFilterProvider class="com.fr.plugin.PLFilter"/>
</extra-decision>
</plugin>

99
src/main/java/com/fr/plugin/Aesutils.java

@ -0,0 +1,99 @@
package com.fr.plugin;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class Aesutils {
private String sKey = "pcycTTYNUJnhlkjh";//key,可自行修改
private String ivParameter = "1356039203753300";//偏移量,可自行修改
private static Aesutils instance = null;
private Aesutils() {
}
public static Aesutils getInstance() {
if (instance == null)
instance = new Aesutils();
return instance;
}
public static String Encrypt(String encData ,String secretKey,String vector) throws Exception {
if(secretKey == null) {
return null;
}
if(secretKey.length() != 16) {
return null;
}
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] raw = secretKey.getBytes();
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
IvParameterSpec iv = new IvParameterSpec(vector.getBytes());// 使用CBC模式,需要一个向量iv,可增加加密算法的强度
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] encrypted = cipher.doFinal(encData.getBytes("utf-8"));
return new String(Base64.getEncoder().encode(encrypted)) ;// 此处使用BASE64做转码。
}
// 加密
public String encrypt(String sSrc) throws Exception {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] raw = sKey.getBytes();
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());// 使用CBC模式,需要一个向量iv,可增加加密算法的强度
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));
return new String(Base64.getEncoder().encode(encrypted));// 此处使用BASE64做转码。
}
// 解密
public String decrypt(String sSrc) throws Exception {
try {
byte[] raw = sKey.getBytes("ASCII");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
byte[] encrypted1 = Base64.getDecoder().decode(sSrc);// 先用base64解密
byte[] original = cipher.doFinal(encrypted1);
String originalString = new String(original, "utf-8");
return originalString;
} catch (Exception ex) {
return null;
}
}
public String decrypt(String sSrc,String key,String ivs) throws Exception {
try {
byte[] raw = key.getBytes("ASCII");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec iv = new IvParameterSpec(ivs.getBytes());
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
byte[] encrypted1 = Base64.getDecoder().decode(sSrc);// 先用base64解密
byte[] original = cipher.doFinal(encrypted1);
String originalString = new String(original, "utf-8");
return originalString;
} catch (Exception ex) {
return null;
}
}
public static String encodeBytes(byte[] bytes) {
StringBuffer strBuf = new StringBuffer();
for (int i = 0; i < bytes.length; i++) {
strBuf.append((char) (((bytes[i] >> 4) & 0xF) + ((int) 'a')));
strBuf.append((char) (((bytes[i]) & 0xF) + ((int) 'a')));
}
return strBuf.toString();
}
}

117
src/main/java/com/fr/plugin/HttpUtils.java

@ -0,0 +1,117 @@
package com.fr.plugin;
import com.fr.json.JSONObject;
import javax.net.ssl.*;
import javax.xml.bind.DatatypeConverter;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
public class HttpUtils {
public static String inputStream2String(InputStream inputStream) {
StringBuilder sb = new StringBuilder();
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(inputStream, Charset.defaultCharset()));
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
}
}
}
return sb.toString();
}
static class MyX509TrustManager implements X509TrustManager {
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
public static String https(String requestUrl, String requestMethod, String outputStr) {
String result = null;
StringBuffer buffer = new StringBuffer();
try {
// 创建SSLContext对象,并使用我们指定的信任管理器初始化
TrustManager[] tm = {new MyX509TrustManager()};
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL url = new URL(requestUrl);
HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
httpUrlConn.setSSLSocketFactory(ssf);
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
// 设置请求方式(GET/POST)
httpUrlConn.setRequestMethod(requestMethod);
httpUrlConn.connect();
// 当有数据需要提交时
if (null != outputStr) {
OutputStream outputStream = httpUrlConn.getOutputStream();
// 注意编码格式,防止中文乱码
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
// 将返回的输入流转换成字符串
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
// 释放资源
inputStream.close();
// inputStream = null;
httpUrlConn.disconnect();
result = buffer.toString();
// jsonObject = JSONObject.fromObject(buffer.toString());
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public static JSONObject getSuccessJSONObject() {
return getError("success", 200);
}
public static JSONObject getErrorByCreateRelation() {
return getError("创建职位和部分关联信息失败", 102);
}
public static JSONObject getError(String msg, int code) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("code", code);
jsonObject.put("result", msg);
jsonObject.put("msg", "");
return jsonObject;
}
}

204
src/main/java/com/fr/plugin/LogoOutFilter.java

@ -0,0 +1,204 @@
package com.fr.plugin;
import com.fanruan.api.net.http.HttpKit;
import com.fr.decision.fun.impl.AbstractGlobalRequestFilterProvider;
import com.fr.decision.webservice.v10.login.LoginService;
import com.fr.json.JSONObject;
import com.fr.log.FineLoggerFactory;
import com.fr.stable.StringUtils;
import com.fr.web.utils.WebUtils;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
public class LogoOutFilter extends AbstractGlobalRequestFilterProvider {
@Override
public String filterName() {
return "outfilter";
}
@Override
public String[] urlPatterns() {
return new String[]{
"/decision/logout"
};
}
@Override
public void init(FilterConfig filterConfig) {
ZtgtConfig.getInstance();
super.init(filterConfig);
}
private boolean isLogOut(HttpServletRequest req) {
String url = WebUtils.getOriginalURL(req);
String servletNamePrefix = "/decision/logout";
return url.contains(servletNamePrefix) && req.getMethod().equals("POST");
}
private void delLoginOut(HttpServletRequest req, HttpServletResponse res) {
try {
//执行帆软内部的退出
LoginService.getInstance().logout(req, res);
JSONObject jsonObject = new JSONObject();
ZtgtConfig plConfig = ZtgtConfig.getInstance();
String url = plConfig.getLogoutUrl();
jsonObject.put("data", url);
//调用外部接口注销accessToken
FineLoggerFactory.getLogger().error("登出成功:{} ", url);
//指定退出之后到他们登录页面
WebUtils.printAsJSON(res, jsonObject);
} catch (Exception var4) {
}
}
@Override
public void doFilter(HttpServletRequest request, HttpServletResponse httpServletResponse, FilterChain filterChain) {
try {
FineLoggerFactory.getLogger().info("当前访问的是:{}",WebUtils.getOriginalURL(request));
if (isLogOut(request)) {
FineLoggerFactory.getLogger().error("退出登录当杜处理");
delLoginOut(request, httpServletResponse);
return;
}
} catch (Exception e) {
printException2FrLog(e);
}
}
private String getCodeUrl(HttpServletRequest req) throws Exception {
String originalURL = URLEncoder.encode(WebUtils.getOriginalURL(req), StandardCharsets.UTF_8.name());
ZtgtConfig plConfig = ZtgtConfig.getInstance();
String baseUrl = plConfig.getValAddr();
String clientId = plConfig.getAppId();
String redirect_uri = URLEncoder.encode(plConfig.getFrUrl(), "UTF-8");
return baseUrl + "/authorize?response_type=code&client_id=" + clientId + "&state=xplatform&redirect_uri=" + redirect_uri + "&oauth_timestamp=" + System.currentTimeMillis() + "&target_uri=" + originalURL;
}
private String getUsername(String code) {
Token token = getAccessToken(code);
ZtgtConfig plConfig = ZtgtConfig.getInstance();
String baseUrl = plConfig.getValAddr();
String clientId = plConfig.getAppId();
String clientSecret = plConfig.getClientSecret();
String url = baseUrl + "/profile?access_token=" + token.getContent() + "&client_id=" + clientId + "&client_secret=" + clientSecret + "&oauth_timestamp=" + System.currentTimeMillis();
try {
String s = HttpKit.get(url);
JSONObject jsonObject = new JSONObject(s);
return jsonObject.getString("id");
} catch (Exception e) {
}
return StringUtils.EMPTY;
}
private synchronized Token getAccessToken(String code) {
try {
token = getNewToken(code);
} catch (Exception e) {
}
return token;
}
private static Token token = null;
private class Token {
private String content = StringUtils.EMPTY;
private long expires_in = 0L;
private long timestamp = 0L;
public Token(String content, long expires_in) {
Token.this.content = content;
Token.this.expires_in = expires_in;
Token.this.timestamp = System.currentTimeMillis();
}
public String getContent() {
return content;
}
public long getExpiresIn() {
return expires_in;
}
public boolean isTimeout() {
//考虑到网络传输,有效期我们只算90%
return System.currentTimeMillis() - timestamp > expires_in * 900;
}
public boolean needRefresh() {
//在70%到90%有效期期间进行刷新
return System.currentTimeMillis() - timestamp > expires_in * 700;
}
}
private Token getNewToken(String code) throws Exception {
ZtgtConfig plConfig = ZtgtConfig.getInstance();
String baseUrl = plConfig.getValAddr();
String clientId = plConfig.getAppId();
String clientSecret = plConfig.getClientSecret();
String redirect_uri = URLEncoder.encode(plConfig.getFrUrl(), "UTF-8");
String url = baseUrl + "/accessToken?client_id=" + clientId + "&client_secret=" + clientSecret + "&grant_type=authorization_code&code=" + code + "&redirect_uri=" + redirect_uri;
String res = HttpKit.post(url, new HashMap<>());
if (StringUtils.isEmpty(res)) {
return null;
}
return parseToken(res);
}
private Token parseToken(String res) throws Exception {
JSONObject entries = new JSONObject(res);
String access_token = entries.getString("access_token");
return new Token(access_token, -1);
}
public static void printException2FrLog(Throwable e) {
StringWriter writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
String s = writer.toString();
FineLoggerFactory.getLogger().error("错误:{}", s);
}
private void sendRedirect(HttpServletResponse res, String url) {
res.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
res.setHeader("Location", url);
}
private void login(HttpServletRequest req, HttpServletResponse res, String username) {
String token = null;
try {
token = LoginService.getInstance().login(req, res, username);
req.setAttribute("fine_auth_token", token);
FineLoggerFactory.getLogger().error("login success");
} catch (Exception e) {
FineLoggerFactory.getLogger().error(e.getMessage(), e);
FineLoggerFactory.getLogger().error("login failed");
}
}
private void writerOurError(HttpServletResponse httpServletResponse) {
try {
WebUtils.writeOutTemplate("/com/fr/plugin/error.html", httpServletResponse, new HashMap());
} catch (IOException e) {
e.printStackTrace();
}
}
private boolean isLogin(HttpServletRequest req) {
return LoginService.getInstance().isLogged(req);
}
}

191
src/main/java/com/fr/plugin/PLFilter.java

@ -0,0 +1,191 @@
package com.fr.plugin;
import com.fanruan.api.decision.store.StateHubManager;
import com.fanruan.api.net.http.HttpKit;
import com.fr.base.TemplateUtils;
import com.fr.data.NetworkHelper;
import com.fr.decision.authority.data.User;
import com.fr.decision.fun.impl.AbstractGlobalRequestFilterProvider;
import com.fr.decision.webservice.utils.DecisionStatusService;
import com.fr.decision.webservice.v10.login.LoginService;
import com.fr.decision.webservice.v10.user.UserService;
import com.fr.json.JSONObject;
import com.fr.log.FineLoggerFactory;
import com.fr.plugin.transform.FunctionRecorder;
import com.fr.stable.StringUtils;
import com.fr.store.StateHubService;
import com.fr.web.utils.WebUtils;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
@FunctionRecorder(localeKey = "zkkd")
public class PLFilter extends AbstractGlobalRequestFilterProvider {
@Override
public String filterName() {
return "alfidfdkter";
}
@Override
public String[] urlPatterns() {
return new String[]{
"/*"
};
}
@Override
public void init(FilterConfig filterConfig) {
ZtgtConfig.getInstance();
FineLoggerFactory.getLogger().error("拦截器启动");
super.init(filterConfig);
}
private boolean isLogOut(HttpServletRequest req) {
String url = WebUtils.getOriginalURL(req);
String servletNamePrefix = "/decision/logout";
return url.contains(servletNamePrefix) && req.getMethod().equals("POST");
}
private void delLoginOut(HttpServletRequest req, HttpServletResponse res) {
try {
//执行帆软内部的退出
User users = UserService.getInstance().getUserByRequestCookie(req);
LoginService.getInstance().logout(req, res);
if (users != null) {
FineLoggerFactory.getLogger().error("{} 登出成功 ", users.getUserName());
}
JSONObject jsonObject = new JSONObject();
ZtgtConfig plConfig = ZtgtConfig.getInstance();
String url = plConfig.getLogoutUrl();
jsonObject.put("data", url);
//调用外部接口注销accessToken
//指定退出之后到他们登录页面
com.fr.web.utils.WebUtils.printAsJSON(res, jsonObject);
} catch (Exception var4) {
}
}
private boolean needFilter(HttpServletRequest request) {
String requestURI = request.getRequestURI();
String isAdmin = request.getParameter("isAdmin");
if (StringUtils.equals(isAdmin, "1")) {
return false;
}
if (StringUtils.isNotBlank(requestURI) && request.getMethod().equals("GET")) {
if (requestURI.endsWith("decision")) {
return true;
}
if (requestURI.endsWith("/view/form") || requestURI.endsWith("/view/report")) {
if (StringUtils.isNotBlank(request.getParameter("viewlet"))) {
return true;
}
}
if (requestURI.contains("/v10/entry/access/") && request.getMethod().equals("GET")) {
return true;
}
if (requestURI.contains("/v5/design/report") && (requestURI.endsWith("/edit") || requestURI.endsWith("/view"))) {
return true;
}
}
return false;
}
public String getOriginalUrlIgnoreCode(HttpServletRequest request) throws Exception {
StringBuffer url = new StringBuffer(request.getRequestURI());
Map parameterMap = request.getParameterMap();
Iterator iterator = parameterMap.entrySet().iterator();
boolean notFirst = url.toString().indexOf("?") == -1;
while (iterator.hasNext()) {
Map.Entry entry = (Map.Entry) iterator.next();
if (StringUtils.equals("code", entry.getKey().toString())) {
continue;
}
if (notFirst) {
url.append('?');
notFirst = false;
} else {
url.append('&');
}
url.append(entry.getKey().toString());
url.append('=');
url.append( URLEncoder.encode(request.getParameter(entry.getKey().toString()),"utf-8"));
}
FineLoggerFactory.getLogger().info("重定向到:" + url.toString());
return url.toString();
}
@Override
public void doFilter(HttpServletRequest request, HttpServletResponse httpServletResponse, FilterChain filterChain) {
try {
if (isLogOut(request)) {
delLoginOut(request, httpServletResponse);
return;
}
if (needFilter(request) && !isLogin(request)) {
//跳转到登录界面
setCookie(httpServletResponse, "loginCallBack", getOriginalUrlIgnoreCode(request));
sendRedirect(httpServletResponse, getCodeUrl(request));
return;
}
filterChain.doFilter(request, httpServletResponse);
} catch (IOException e) {
printException2FrLog(e);
} catch (ServletException e) {
printException2FrLog(e);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void setCookie(HttpServletResponse response, String name, String value) {
Cookie cookie = new Cookie(name, value);
cookie.setPath("/");
response.addCookie(cookie);
}
private void sendRedirect(HttpServletResponse res, String url) throws IOException {
Map<String, String> params = new HashMap<>();
params.put("callBack", url);
WebUtils.writeOutTemplate("com/fr/plugin/redirect.html", res, params);
}
private String getCodeUrl(HttpServletRequest req) throws Exception {
String originalURL = URLEncoder.encode(getOriginalUrlIgnoreCode(req), StandardCharsets.UTF_8.name());
ZtgtConfig plConfig = ZtgtConfig.getInstance();
String baseUrl = plConfig.getValAddr();
String clientId = plConfig.getAppId();
String redirect_uri = URLEncoder.encode(plConfig.getFrUrl()+"/url/loginCallback", "UTF-8");
return baseUrl + "/authorize?response_type=code&client_id=" + clientId + "&state=xplatform&redirect_uri=" + redirect_uri + "&oauth_timestamp=" + System.currentTimeMillis() + "&target_uri=" + originalURL;
}
public static void printException2FrLog(Throwable e) {
StringWriter writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
String s = writer.toString();
FineLoggerFactory.getLogger().error("错误:{}", s);
}
private boolean isLogin(HttpServletRequest req) {
return LoginService.getInstance().isLogged(req);
}
}

12
src/main/java/com/fr/plugin/PLFunction.java

@ -0,0 +1,12 @@
package com.fr.plugin;
import com.fr.plugin.transform.ExecuteFunctionRecord;
import com.fr.plugin.transform.FunctionRecorder;
@FunctionRecorder(localeKey = "pase")
public class PLFunction {
@ExecuteFunctionRecord
public String name() {
return "功能点检测";
}
}

20
src/main/java/com/fr/plugin/PLHttpHander.java

@ -0,0 +1,20 @@
package com.fr.plugin;
import com.fr.decision.fun.HttpHandler;
import com.fr.decision.fun.impl.AbstractHttpHandlerProvider;
import com.fr.plugin.handers.*;
public class PLHttpHander extends AbstractHttpHandlerProvider {
HttpHandler[] actions = new HttpHandler[]{
new AddAppAccountHander(),
new SynPositionHander(),
new SynDepstHander(),
new LoginCallBackHandler()
};
@Override
public HttpHandler[] registerHandlers() {
return actions;
}
}

15
src/main/java/com/fr/plugin/PLLifeCycleMonitor.java

@ -0,0 +1,15 @@
package com.fr.plugin;
import com.fr.plugin.context.PluginContext;
import com.fr.plugin.observer.inner.AbstractPluginLifecycleMonitor;
public class PLLifeCycleMonitor extends AbstractPluginLifecycleMonitor {
@Override
public void afterRun(PluginContext pluginContext) {
}
@Override
public void beforeStop(PluginContext pluginContext) {
}
}

193
src/main/java/com/fr/plugin/PLLoginFilter.java

@ -0,0 +1,193 @@
package com.fr.plugin;
import com.fanruan.api.net.http.HttpKit;
import com.fr.decision.fun.impl.AbstractGlobalRequestFilterProvider;
import com.fr.decision.webservice.v10.login.LoginService;
import com.fr.general.ComparatorUtils;
import com.fr.json.JSONObject;
import com.fr.log.FineLoggerFactory;
import com.fr.plugin.transform.FunctionRecorder;
import com.fr.stable.StringUtils;
import com.fr.web.utils.WebUtils;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
@FunctionRecorder(localeKey = "zyfilter")
public class PLLoginFilter extends AbstractGlobalRequestFilterProvider {
@Override
public String filterName() {
return "ffrrww";
}
@Override
public String[] urlPatterns() {
return new String[]{
"/decision/login"
};
}
@Override
public void init(FilterConfig filterConfig) {
super.init(filterConfig);
}
@Override
public void doFilter(HttpServletRequest request, HttpServletResponse httpServletResponse, FilterChain filterChain) {
try {
if (request.getMethod().equals("GET")) {
String isAdmin = request.getParameter("isAdmin");
if (ComparatorUtils.equals(isAdmin, "1")) {
filterChain.doFilter(request, httpServletResponse);
return;
}
FineLoggerFactory.getLogger().info("来源:{}访问了登陆",request.getHeader("referer"));
sendRedirect(httpServletResponse, getCodeUrl(request));
} else {
filterChain.doFilter(request, httpServletResponse);
}
} catch (IOException e) {
printException2FrLog(e);
} catch (ServletException e) {
printException2FrLog(e);
} catch (Exception e) {
e.printStackTrace();
}
}
private String getCodeUrl(HttpServletRequest req) throws Exception {
ZtgtConfig plConfig = ZtgtConfig.getInstance();
String baseUrl = plConfig.getValAddr();
String clientId = plConfig.getAppId();
String redirect_uri = URLEncoder.encode(plConfig.getFrUrl(), "UTF-8");
String originalURL = URLEncoder.encode(WebUtils.getOriginalURL(req), StandardCharsets.UTF_8.name());
return baseUrl + "/authorize?response_type=code&client_id=" + clientId + "&state=xplatform&redirect_uri=" + redirect_uri + "&oauth_timestamp=" + System.currentTimeMillis() + "&target_uri=" + originalURL;
}
private String getUsername(String code) {
Token token = getAccessToken(code);
ZtgtConfig plConfig = ZtgtConfig.getInstance();
String baseUrl = plConfig.getValAddr();
String clientId = plConfig.getAppId();
String clientSecret = plConfig.getClientSecret();
String url = baseUrl + "/profile?access_token=" + token.getContent() + "&client_id=" + clientId + "&client_secret=" + clientSecret + "&oauth_timestamp=" + System.currentTimeMillis();
try {
String s = HttpKit.get(url);
JSONObject jsonObject = new JSONObject(s);
return jsonObject.getString("id");
} catch (Exception e) {
}
return StringUtils.EMPTY;
}
private synchronized Token getAccessToken(String code) {
try {
token = getNewToken(code);
} catch (Exception e) {
}
return token;
}
private static Token token = null;
private class Token {
private String content = StringUtils.EMPTY;
private long expires_in = 0L;
private long timestamp = 0L;
public Token(String content, long expires_in) {
Token.this.content = content;
Token.this.expires_in = expires_in;
Token.this.timestamp = System.currentTimeMillis();
}
public String getContent() {
return content;
}
public long getExpiresIn() {
return expires_in;
}
public boolean isTimeout() {
//考虑到网络传输,有效期我们只算90%
return System.currentTimeMillis() - timestamp > expires_in * 900;
}
public boolean needRefresh() {
//在70%到90%有效期期间进行刷新
return System.currentTimeMillis() - timestamp > expires_in * 700;
}
}
private Token getNewToken(String code) throws Exception {
ZtgtConfig plConfig = ZtgtConfig.getInstance();
String baseUrl = plConfig.getValAddr();
String clientId = plConfig.getAppId();
String redirect_uri = URLEncoder.encode(plConfig.getFrUrl(), "UTF-8");
String clientSecret = plConfig.getClientSecret();
String url = baseUrl + "/accessToken?client_id=" + clientId + "&client_secret=" + clientSecret + "&grant_type=authorization_code&code=" + code + "&redirect_uri=" + redirect_uri;
String res = HttpKit.post(url, new HashMap<>());
if (StringUtils.isEmpty(res)) {
return null;
}
return parseToken(res);
}
private Token parseToken(String res) throws Exception {
JSONObject entries = new JSONObject(res);
String access_token = entries.getString("access_token");
return new Token(access_token, -1);
}
public static void printException2FrLog(Throwable e) {
StringWriter writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
String s = writer.toString();
FineLoggerFactory.getLogger().error("错误:{}", s);
}
private void sendRedirect(HttpServletResponse res, String url) {
res.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
res.setHeader("Location", url);
}
private void login(HttpServletRequest req, HttpServletResponse res, String username) {
String token = null;
try {
token = LoginService.getInstance().login(req, res, username);
req.setAttribute("fine_auth_token", token);
FineLoggerFactory.getLogger().error("login success");
} catch (Exception e) {
FineLoggerFactory.getLogger().error(e.getMessage(), e);
FineLoggerFactory.getLogger().error("login failed");
}
}
private void writerOurError(HttpServletResponse httpServletResponse) {
try {
WebUtils.writeOutTemplate("/com/fr/plugin/error.html", httpServletResponse, new HashMap());
} catch (IOException e) {
e.printStackTrace();
}
}
private boolean isLogin(HttpServletRequest req) {
return LoginService.getInstance().isLogged(req);
}
}

17
src/main/java/com/fr/plugin/PLUrlAliasProvider.java

@ -0,0 +1,17 @@
package com.fr.plugin;
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 PLUrlAliasProvider extends AbstractURLAliasProvider {
@Override
public URLAlias[] registerAlias() {
return new URLAlias[]{
URLAliasFactory.createPluginAlias("/sync/accounts", "/accounts", true),
URLAliasFactory.createPluginAlias("/sync/positions", "/positions", true),
URLAliasFactory.createPluginAlias("/sync/deps", "/deps", true),
URLAliasFactory.createPluginAlias("/loginCallback", "/loginCallback", true),
};
}
}

26
src/main/java/com/fr/plugin/SafeCheckUtils.java

@ -0,0 +1,26 @@
package com.fr.plugin;
import com.fr.third.springframework.util.DigestUtils;
import com.fr.third.springframework.util.StringUtils;
import java.nio.charset.StandardCharsets;
public class SafeCheckUtils {
public static boolean checkSafe(String body, String appId, String time, String key) {
ZtgtConfig ztgtConfig = ZtgtConfig.getInstance();
String tmp = body + time + appId + ztgtConfig.getSynKey();
String md5 = DigestUtils.md5DigestAsHex(tmp.getBytes(StandardCharsets.UTF_8));
if (StringUtils.endsWithIgnoreCase(md5, key)) {
long d = Long.parseLong(time);
long left = System.currentTimeMillis() + 30000;
long right = System.currentTimeMillis() - 30000;
if (d <= left && d >= right) {
return true;
}
}
return false;
}
}

93
src/main/java/com/fr/plugin/ZtgtConfig.java

@ -0,0 +1,93 @@
package com.fr.plugin;
import com.fr.config.*;
import com.fr.config.holder.Conf;
import com.fr.config.holder.factory.Holders;
@Visualization(category = "用户同步和单点配置")
public class ZtgtConfig extends DefaultConfiguration {
private static volatile ZtgtConfig config = null;
public static ZtgtConfig getInstance() {
if (config == null) {
config = ConfigContext.getConfigInstance(ZtgtConfig.class);
}
return config;
}
@Identifier(value = "valAddr", name = "接口地址", description = "接口地址", status = Status.SHOW)
private Conf<String> valAddr = Holders.simple("http://xxx.cn/profile/oauth2");
@Identifier(value = "frUrl", name = "报表地址", description = "报表地址", status = Status.SHOW)
private Conf<String> frUrl = Holders.simple("http://localhost:8075/webroot/decision");
@Identifier(value = "appId", name = "clientId", description = "clientId", status = Status.SHOW)
private Conf<String> appId = Holders.simple("");
@Identifier(value = "clientSecret", name = "clientSecret", description = "clientSecret", status = Status.SHOW)
private Conf<String> clientSecret = Holders.simple("");
@Identifier(value = "logoutUrl", name = "统一认证登出地址", description = "统一认证登出地址", status = Status.SHOW)
private Conf<String> logoutUrl = Holders.simple("http://xxx/logout");
@Identifier(value = "synKey", name = "用户同步秘钥", description = "", status = Status.HIDE)
private Conf<String> synKey = Holders.simple("");
public String getFrUrl() {
return frUrl.get();
}
public String getSynKey() {
return synKey.get();
}
public void setSynKey(String synKey) {
this.synKey.set(synKey);
}
public void setFrUrl(String frUrl) {
this.frUrl.set(frUrl);
}
public String getAppId() {
return appId.get();
}
public void setAppId(String appId) {
this.appId.set(appId);
}
public String getClientSecret() {
return clientSecret.get();
}
public void setClientSecret(String clientSecret) {
this.clientSecret.set(clientSecret);
}
public String getValAddr() {
return valAddr.get();
}
public String getLogoutUrl() {
return logoutUrl.get();
}
public void setLogoutUrl(String logoutUrl) {
this.logoutUrl.set(logoutUrl);
;
}
public void setValAddr(String valAddr) {
this.valAddr.set(valAddr);
}
@Override
public Object clone() throws CloneNotSupportedException {
ZtgtConfig cloned = (ZtgtConfig) super.clone();
cloned.valAddr = (Conf<String>) valAddr.clone();
cloned.appId = (Conf<String>) appId.clone();
cloned.synKey = (Conf<String>) synKey.clone();
cloned.clientSecret = (Conf<String>) clientSecret.clone();
cloned.frUrl = (Conf<String>) frUrl.clone();
cloned.logoutUrl = (Conf<String>) logoutUrl.clone();
return cloned;
}
}

198
src/main/java/com/fr/plugin/handers/AddAppAccountHander.java

@ -0,0 +1,198 @@
package com.fr.plugin.handers;
import com.fr.collections.FineCollections;
import com.fr.collections.api.FineLock;
import com.fr.decision.authority.AuthorityContext;
import com.fr.decision.authority.base.constant.type.operation.ManualOperationType;
import com.fr.decision.authority.controller.DepartmentController;
import com.fr.decision.authority.controller.PostController;
import com.fr.decision.authority.controller.UserController;
import com.fr.decision.authority.data.Department;
import com.fr.decision.authority.data.Post;
import com.fr.decision.authority.data.User;
import com.fr.decision.fun.impl.BaseHttpHandler;
import com.fr.decision.privilege.encrpt.PasswordValidator;
import com.fr.decision.webservice.utils.UserSourceFactory;
import com.fr.decision.webservice.v10.user.UserService;
import com.fr.json.JSONArray;
import com.fr.json.JSONObject;
import com.fr.log.FineLoggerFactory;
import com.fr.plugin.Aesutils;
import com.fr.plugin.HttpUtils;
import com.fr.plugin.SafeCheckUtils;
import com.fr.plugin.transform.ExecuteFunctionRecord;
import com.fr.plugin.transform.FunctionRecorder;
import com.fr.stable.StringUtils;
import com.fr.stable.query.QueryFactory;
import com.fr.stable.query.restriction.RestrictionFactory;
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.PrintWriter;
import java.io.StringWriter;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
@FunctionRecorder
public class AddAppAccountHander extends BaseHttpHandler {
@Override
public RequestMethod getMethod() {
return null;
}
@Override
public String getPath() {
return "/accounts";
}
@Override
public boolean isPublic() {
return true;
}
@Override
@ExecuteFunctionRecord
public void handle(HttpServletRequest req, HttpServletResponse httpServletResponse) throws Exception {
String body = HttpUtils.inputStream2String(req.getInputStream());
if (StringUtils.isNotBlank(body)) {
String xtime = req.getHeader("xtime");
String xsign = req.getHeader("xkey");
FineLoggerFactory.getLogger().info("addAppAccount: 请求参数 {}", body);
JSONObject jsonObject = new JSONObject(body);
if (jsonObject.has("account")) {
UserService userService = UserService.getInstance();
String account = jsonObject.getString("account");
FineLock lock = FineCollections.getInstance().getClient().getLock("syncuser", "lockedname" + account);
if (lock.tryLock(500L, TimeUnit.MILLISECONDS)) {
try {
User user = userService.getUserByUserName(account);
boolean iscreate = false;
if (user == null) {
iscreate = true;
user = new User();
}
String password = jsonObject.getString("password");
JSONObject person_info = jsonObject.getJSONObject("person_info");
// JSONObject person_info = new JSONObject(pp_info);
String name = person_info.getString("name");
String email = person_info.getString("email");
String mobile = person_info.getString("mobile");
String status = person_info.getString("status");//0启用 1禁用
if(iscreate){
user.setId(account);
}
String userUid = user.getId();
user.setRealName(name);
user.setUserName(account);
user.setEmail(email);
user.setEnable(true);
user.setCreationType(ManualOperationType.KEY);
user.setMobile(mobile);
PasswordValidator passwordValidator = UserSourceFactory.getInstance().getUserSource(ManualOperationType.KEY).getPasswordValidator();
String pwd;
if (StringUtils.isBlank(password)) {
pwd = "frapp.X";
} else {
pwd = Aesutils.getInstance().decrypt(password);
}
UserController userController = AuthorityContext.getInstance().getUserController();
if (iscreate) {
try {
user.setPassword(passwordValidator.encode(account, pwd));
userController.add(user);
} catch (Exception e) {
}
} else {
userController.update(user);
}
DepartmentController departmentController = AuthorityContext.getInstance().getDepartmentController();
JSONArray groups = person_info.getJSONArray("groups");
//先将用户移除原来部门
PostController postController = AuthorityContext.getInstance().getPostController();
List<Post> posts = postController.findByUser(userUid, QueryFactory.create());
//把用户从原来岗位移除
for (Post post : posts) {
//先查到职位,再查职位关联的部门
List<Department> departments = departmentController.findByPost(post.getId(), QueryFactory.create());
for (Department de : departments) {
userController.removeUserFromDepartmentAndPost(userUid, de.getId(), post.getId());
}
}
for (int i = 0; i < groups.length(); i++) {
JSONObject postions = groups.getJSONObject(i);
String orgName = postions.getString("orgName");
String orgId = postions.getString("orgId");
String orgPid = postions.getString("orgPid");
Department department = departmentController.findOne(QueryFactory.create().addRestriction(RestrictionFactory.eq("id", orgId)));
if (department == null) {
department = new Department();
department.setName(orgName);
if (StringUtils.equals(orgPid, "0")) {
orgPid = null;
}
department.setId(orgId);
department.setParentId(orgPid);
department.setEnable(true);
departmentController.add(department);
}
String positionId = postions.getString("positionId");
String positionName = postions.getString("positionName");
Post post = postController.findOne(QueryFactory.create().addRestriction(RestrictionFactory.eq("id", positionId)));
if (post == null) {
post = new Post();
post.setName(positionName);
post.setId(positionId);
post.setEnable(true);
postController.add(post);
try {
postController.addPostToDepartment(positionId, orgId);
} catch (Exception e) {
printException2FrLog(e);
}
}
//检查职务和部门是否存在关联关系
List<Department> departments = departmentController.findByPost(post.getId(), QueryFactory.create());
boolean postindeps = false;
for (Department department1 : departments) {
if (StringUtils.equals(department1.getId(), orgId)) {
postindeps = true;
break;
}
}
if (!postindeps) {
try {
postController.addPostToDepartment(positionId, orgId);
} catch (Exception e) {
printException2FrLog(e);
}
}
try {
userController.addUserToDepartmentAndPost(userUid, orgId, positionId);
} catch (Exception e) {
FineLoggerFactory.getLogger().error("将用户添加到职位失败:", e);
WebUtils.printAsJSON(httpServletResponse, HttpUtils.getErrorByCreateRelation());
return;
}
}
} catch (Exception e) {
printException2FrLog(e);
} finally {
lock.unlock();
}
}
}
}
WebUtils.printAsJSON(httpServletResponse, HttpUtils.getSuccessJSONObject());
}
public static void printException2FrLog(Throwable e) {
StringWriter writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
String s = writer.toString();
FineLoggerFactory.getLogger().error("错误:{}", s);
}
}

230
src/main/java/com/fr/plugin/handers/LoginCallBackHandler.java

@ -0,0 +1,230 @@
package com.fr.plugin.handers;
import com.fanruan.api.log.LogKit;
import com.fanruan.api.net.http.HttpKit;
import com.fr.decision.authority.data.User;
import com.fr.decision.fun.impl.BaseHttpHandler;
import com.fr.decision.webservice.utils.DecisionStatusService;
import com.fr.decision.webservice.v10.login.LoginService;
import com.fr.decision.webservice.v10.user.UserService;
import com.fr.json.JSONObject;
import com.fr.log.FineLoggerFactory;
import com.fr.plugin.PLFilter;
import com.fr.plugin.ZtgtConfig;
import com.fr.plugin.transform.ExecuteFunctionRecord;
import com.fr.stable.StringUtils;
import com.fr.store.StateHubService;
import com.fr.third.springframework.web.bind.annotation.RequestMethod;
import com.fr.web.utils.WebUtils;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
public class LoginCallBackHandler extends BaseHttpHandler {
@Override
public RequestMethod getMethod() {
return null;
}
@Override
public String getPath() {
return "/loginCallback";
}
@Override
public boolean isPublic() {
return true;
}
@Override
@ExecuteFunctionRecord
public void handle(HttpServletRequest req, HttpServletResponse httpServletResponse) throws Exception {
String rfToken = req.getParameter("code");
if (StringUtils.isNotBlank(rfToken)) {
String username = getUsername(rfToken);
User user = UserService.getInstance().getUserByUserName(username);
if (user != null) {
login(req, httpServletResponse, username);
String loginCallBack1 = getCookieByKey(req, "loginCallBack");
if (StringUtils.isNotBlank(loginCallBack1)) {
deleteCookieByName( req, httpServletResponse,"loginCallBack");
sendRedirect(httpServletResponse, loginCallBack1);
return;
}
ZtgtConfig plConfig = ZtgtConfig.getInstance();
sendRedirect(httpServletResponse, plConfig.getFrUrl());
return;
} else {
WebUtils.printAsString(httpServletResponse, username + "用户不存在");
return;
}
}
sendRedirect(httpServletResponse, getCodeUrl(req));
}
/**
* 根据key获取cookie
* @param req
* @return
*/
public static String getCookieByKey(HttpServletRequest req,String key){
Cookie[] cookies = req.getCookies();
String cookie = "";
if(cookies == null || cookies.length <=0){
return "";
}
for(int i = 0; i < cookies.length; i++) {
Cookie item = cookies[i];
if (item.getName().equalsIgnoreCase(key)) {
cookie = item.getValue();
}
}
LogKit.info("cookie:"+cookie);
return cookie;
}
private String deleteCookieByName(HttpServletRequest request, HttpServletResponse response,String name ) {
Cookie[] cookies = request.getCookies();
if (null == cookies) {
FineLoggerFactory.getLogger().debug("没有cookie");
} else {
for (Cookie cookie : cookies) {
if (cookie.getName().equals(name)) {
String cookieValue = cookie.getValue();
//设置值为null
cookie.setValue(null);
//立即销毁cookie
cookie.setMaxAge(0);
cookie.setPath("/");
FineLoggerFactory.getLogger().debug("被删除的cookie名字为:{}", cookie.getName(), cookieValue);
response.addCookie(cookie);
return cookieValue;
}
}
}
return "";
}
private String getCodeUrl(HttpServletRequest req) throws Exception {
ZtgtConfig plConfig = ZtgtConfig.getInstance();
String originalURL = URLEncoder.encode(plConfig.getFrUrl() , StandardCharsets.UTF_8.name());
String baseUrl = plConfig.getValAddr();
String clientId = plConfig.getAppId();
String redirect_uri = URLEncoder.encode(plConfig.getFrUrl()+"/url/loginCallback", "UTF-8");
return baseUrl + "/authorize?response_type=code&client_id=" + clientId + "&state=xplatform&redirect_uri=" + redirect_uri + "&oauth_timestamp=" + System.currentTimeMillis() + "&target_uri=" + originalURL;
}
private class Token {
private String content = StringUtils.EMPTY;
private long expires_in = 0L;
private long timestamp = 0L;
public Token(String content, long expires_in) {
Token.this.content = content;
Token.this.expires_in = expires_in;
Token.this.timestamp = System.currentTimeMillis();
}
public String getContent() {
return content;
}
public long getExpiresIn() {
return expires_in;
}
public boolean isTimeout() {
//考虑到网络传输,有效期我们只算90%
return System.currentTimeMillis() - timestamp > expires_in * 900;
}
public boolean needRefresh() {
//在70%到90%有效期期间进行刷新
return System.currentTimeMillis() - timestamp > expires_in * 700;
}
@Override
public String toString() {
return "Token{" +
"content='" + content + '\'' +
", expires_in=" + expires_in +
", timestamp=" + timestamp +
'}';
}
}
private void sendRedirect(HttpServletResponse res, String url) throws IOException {
Map<String, String> params = new HashMap<>();
params.put("callBack", url);
WebUtils.writeOutTemplate("com/fr/plugin/redirect.html", res, params);
}
private void login(HttpServletRequest req, HttpServletResponse res, String username) {
String token = null;
try {
token = LoginService.getInstance().login(req, res, username);
req.setAttribute("fine_auth_token", token);
FineLoggerFactory.getLogger().error("{} login success from ticket", username);
} catch (Exception e) {
FineLoggerFactory.getLogger().error(e.getMessage(), e);
FineLoggerFactory.getLogger().error("login failed");
}
}
private String getUsername(String code) {
Token token = getAccessToken(code);
ZtgtConfig plConfig = ZtgtConfig.getInstance();
String baseUrl = plConfig.getValAddr();
String clientId = plConfig.getAppId();
String clientSecret = plConfig.getClientSecret();
String url = baseUrl + "/profile?access_token=" + token.getContent() + "&client_id=" + clientId + "&client_secret=" + clientSecret + "&oauth_timestamp=" + System.currentTimeMillis();
try {
String s = HttpKit.get(url);
LogKit.info("token {} get user info from {} profile {}",token,url, s);
JSONObject jsonObject = new JSONObject(s);
return jsonObject.getString("accountId");
} catch (Exception e) {
}
return StringUtils.EMPTY;
}
private synchronized Token getAccessToken(String code) {
try {
token = getNewToken(code);
} catch (Exception e) {
}
return token;
}
private static Token token = null;
private Token getNewToken(String code) throws Exception {
ZtgtConfig plConfig = ZtgtConfig.getInstance();
String baseUrl = plConfig.getValAddr();
String clientId = plConfig.getAppId();
String clientSecret = plConfig.getClientSecret();
String redirect_uri = URLEncoder.encode(plConfig.getFrUrl(), "UTF-8");
String url = baseUrl + "/accessToken?client_id=" + clientId + "&client_secret=" + clientSecret + "&code=" + code + "&redirect_uri=" + redirect_uri;
String res = HttpKit.get(url, new HashMap<>());
LogKit.info("get token from url: {} resp:{}", url, res);
if (StringUtils.isEmpty(res)) {
return null;
}
return parseToken(res);
}
private Token parseToken(String res) throws Exception {
JSONObject entries = new JSONObject(res);
String access_token = entries.getString("access_token");
return new Token(access_token, -1);
}
}

116
src/main/java/com/fr/plugin/handers/SynDepstHander.java

@ -0,0 +1,116 @@
package com.fr.plugin.handers;
import com.fanruan.api.log.LogKit;
import com.fr.collections.FineCollections;
import com.fr.collections.api.FineLock;
import com.fr.decision.authority.AuthorityContext;
import com.fr.decision.authority.base.constant.type.operation.ManualOperationType;
import com.fr.decision.authority.controller.DepartmentController;
import com.fr.decision.authority.controller.UserController;
import com.fr.decision.authority.data.Department;
import com.fr.decision.authority.data.User;
import com.fr.decision.fun.impl.BaseHttpHandler;
import com.fr.decision.webservice.v10.user.UserService;
import com.fr.json.JSONObject;
import com.fr.log.FineLoggerFactory;
import com.fr.plugin.Aesutils;
import com.fr.plugin.HttpUtils;
import com.fr.plugin.SafeCheckUtils;
import com.fr.plugin.transform.ExecuteFunctionRecord;
import com.fr.plugin.transform.FunctionRecorder;
import com.fr.stable.StringUtils;
import com.fr.stable.query.QueryFactory;
import com.fr.stable.query.restriction.RestrictionFactory;
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.util.concurrent.TimeUnit;
@FunctionRecorder
public class SynDepstHander extends BaseHttpHandler {
@Override
public RequestMethod getMethod() {
return null;
}
@Override
public String getPath() {
return "/deps";
}
@Override
public boolean isPublic() {
return true;
}
@Override
@ExecuteFunctionRecord
public void handle(HttpServletRequest req, HttpServletResponse httpServletResponse) throws Exception {
String body = HttpUtils.inputStream2String(req.getInputStream());
if (StringUtils.isNotBlank(body)) {
String xtime = req.getHeader("xtime");
String xsign = req.getHeader("xkey");
// if (!SafeCheckUtils.checkSafe(body, "", xtime, xsign)) {
// FineLoggerFactory.getLogger().error("deps: 验证失败");
// JSONObject successJSONObject = HttpUtils.getError("签名验证失败", 101);
// WebUtils.printAsJSON(httpServletResponse, successJSONObject);
// return;
// }
FineLoggerFactory.getLogger().info("deps: 请求参数 {}", body);
DepartmentController departmentController = AuthorityContext.getInstance().getDepartmentController();
JSONObject jsonObject = new JSONObject(body);
if (jsonObject.has("deps_info")) {
JSONObject entries = jsonObject.getJSONObject("deps_info");
String orgId = entries.getString("id");
FineLock lock = FineCollections.getInstance().getClient().getLock("syncuser", "lockeddep" + orgId);
try {
if (lock.tryLock(1L, 20L, TimeUnit.SECONDS)) {
String status = entries.getString("status");
Department department = departmentController.findOne(QueryFactory.create().addRestriction(RestrictionFactory.eq("id", orgId)));
boolean enable = true;
if (StringUtils.equals(status, "1")) {
enable = false;
}
String pid = entries.getString("pid");
if (StringUtils.equals(pid, "0")) {
pid = null;
}
if (department == null) {
department = new Department();
department.setName(entries.getString("name"));
department.setId(orgId);
department.setParentId(pid);
department.setEnable(enable);
department.setCreationType(ManualOperationType.KEY);
try {
departmentController.add(department);
} catch (Exception e) {
}
} else {
department.setName(entries.getString("name"));
department.setParentId(pid);
department.setEnable(enable);
department.setCreationType(ManualOperationType.KEY);
departmentController.update(department);
}
} else {
FineLoggerFactory.getLogger().info("获取部门同步锁失败:{}", orgId);
WebUtils.printAsJSON(httpServletResponse, HttpUtils.getError("获取部门同步锁失败", 111));
return;
}
} catch (Exception e) {
LogKit.error("同步部门异常:{}", e);
} finally {
try {
lock.unlock();
}catch (Exception e){
}
}
}
}
WebUtils.printAsJSON(httpServletResponse, HttpUtils.getSuccessJSONObject());
}
}

144
src/main/java/com/fr/plugin/handers/SynPositionHander.java

@ -0,0 +1,144 @@
package com.fr.plugin.handers;
import com.fanruan.api.log.LogKit;
import com.fr.collections.FineCollections;
import com.fr.collections.api.FineLock;
import com.fr.decision.authority.AuthorityContext;
import com.fr.decision.authority.base.constant.type.operation.ManualOperationType;
import com.fr.decision.authority.controller.DepartmentController;
import com.fr.decision.authority.controller.PostController;
import com.fr.decision.authority.controller.UserController;
import com.fr.decision.authority.data.Department;
import com.fr.decision.authority.data.Post;
import com.fr.decision.authority.data.User;
import com.fr.decision.fun.impl.BaseHttpHandler;
import com.fr.json.JSONObject;
import com.fr.log.FineLoggerFactory;
import com.fr.plugin.HttpUtils;
import com.fr.plugin.SafeCheckUtils;
import com.fr.plugin.transform.ExecuteFunctionRecord;
import com.fr.plugin.transform.FunctionRecorder;
import com.fr.stable.StringUtils;
import com.fr.stable.query.QueryFactory;
import com.fr.stable.query.data.DataList;
import com.fr.stable.query.restriction.RestrictionFactory;
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.util.List;
import java.util.concurrent.TimeUnit;
@FunctionRecorder
public class SynPositionHander extends BaseHttpHandler {
@Override
public RequestMethod getMethod() {
return null;
}
@Override
public String getPath() {
return "/positions";
}
@Override
public boolean isPublic() {
return true;
}
@Override
@ExecuteFunctionRecord
public void handle(HttpServletRequest req, HttpServletResponse httpServletResponse) throws Exception {
String body = HttpUtils.inputStream2String(req.getInputStream());
if (StringUtils.isNotBlank(body)) {
String xtime = req.getHeader("xtime");
String xsign = req.getHeader("xkey");
// if (!SafeCheckUtils.checkSafe(body, "", xtime, xsign)) {
// FineLoggerFactory.getLogger().error("SynPositionHander: 验证失败");
// JSONObject successJSONObject = HttpUtils.getError("签名验证失败", 101);
// WebUtils.printAsJSON(httpServletResponse, successJSONObject);
// return;
// }
FineLoggerFactory.getLogger().info("SynPositionHander: 请求参数 {}", body);
PostController postController = AuthorityContext.getInstance().getPostController();
JSONObject jsonObject = new JSONObject(body);
if (jsonObject.has("position_info")) {
JSONObject entries = jsonObject.getJSONObject("position_info");
String postionId = entries.getString("id");
FineLock lock = FineCollections.getInstance().getClient().getLock("syncuser", "lockedpostion" + postionId);
try {
if (lock.tryLock(1L, 20, TimeUnit.SECONDS)) {
String status = entries.getString("status");
Post post = postController.findOne(QueryFactory.create().addRestriction(RestrictionFactory.eq("id", postionId)));
boolean enable = true;
if (StringUtils.equals(status, "1")) {
enable = false;
}
String dep_id = entries.getString("dep_id");
if (post == null) {
post = new Post();
post.setName(entries.getString("name"));
post.setId(postionId);
post.setEnable(enable);
post.setCreationType(ManualOperationType.KEY);
try {
postController.add(post);
postController.addPostToDepartment(postionId, dep_id);
} catch (Exception e) {
FineLoggerFactory.getLogger().error("添加职位到部门失败:", e);
WebUtils.printAsJSON(httpServletResponse, HttpUtils.getErrorByCreateRelation());
return;
}
} else {
post.setName(entries.getString("name"));
post.setId(postionId);
post.setEnable(enable);
post.setCreationType(ManualOperationType.KEY);
postController.update(post);
DepartmentController departmentController = AuthorityContext.getInstance().getDepartmentController();
List<Department> departments = departmentController.findByPost(post.getId(), QueryFactory.create());
UserController userController = AuthorityContext.getInstance().getUserController();
boolean notneedadd = false;
for (Department de : departments) {
if (StringUtils.equals(de.getId(), dep_id)) {
notneedadd = true;
} else {
DataList<User> users = userController.findByDepartmentAndPost(de.getId(), postionId, QueryFactory.create());
List<User> list = users.getList();
for (User user : list) {
userController.removeUserFromDepartmentAndPost(user.getId(), de.getId(), postionId);
}
postController.removePostFromDepartment(postionId, de.getId());
}
}
if (!notneedadd) {
try {
postController.addPostToDepartment(postionId, dep_id);
} catch (Exception e) {
FineLoggerFactory.getLogger().error("添加职位到部门失败:", e);
WebUtils.printAsJSON(httpServletResponse, HttpUtils.getErrorByCreateRelation());
return;
}
}
}
} else {
WebUtils.printAsJSON(httpServletResponse, HttpUtils.getError("获取职位同步锁失败", 111));
return;
}
}catch (Exception e){
LogKit.error("同步异常:{}",e);
}finally {
try {
lock.unlock();
}catch (Exception e){
}
}
}
}
WebUtils.printAsJSON(httpServletResponse, HttpUtils.getSuccessJSONObject());
}
}

11
src/main/resources/com/fr/plugin/redirect.html

@ -0,0 +1,11 @@
<!doctype html>
<html lang="en">
<head>
<script type="text/javascript">
window.location.href = '${callBack}';
</script>
</head>
<body>
<!--<h3>登陆成功${loginUser},5秒后跳转到:${callBack}</h3>-->
</body>
</html>
Loading…
Cancel
Save