Browse Source

提交开源任务材料

10.0
LAPTOP-SB56SG4Q\86185 3 years ago
parent
commit
1e69d7aedc
  1. 5
      README.md
  2. 44
      plugin.xml
  3. 95
      src/main/java/com/fr/plugin/sxka/sso/CustomLogInOutEventProvider.java
  4. 74
      src/main/java/com/fr/plugin/sxka/sso/RoleDBAccessProvider.java
  5. 703
      src/main/java/com/fr/plugin/sxka/sso/SsoFilter.java
  6. 101
      src/main/java/com/fr/plugin/sxka/sso/SxKaPerformanceMonitor.java
  7. 13
      src/main/java/com/fr/plugin/sxka/sso/beans/DecryptParamBean.java
  8. 23
      src/main/java/com/fr/plugin/sxka/sso/beans/SxkaConfigBean.java
  9. 50
      src/main/java/com/fr/plugin/sxka/sso/beans/UserRoleTypeParamBean.java
  10. 96
      src/main/java/com/fr/plugin/sxka/sso/conf/RoleConfigBean.java
  11. 74
      src/main/java/com/fr/plugin/sxka/sso/conf/RoleXmlConfigReader.java
  12. 49
      src/main/java/com/fr/plugin/sxka/sso/conf/UrlFilterConfigReader.java
  13. 9
      src/main/java/com/fr/plugin/sxka/sso/conf/aaa.xml
  14. 389
      src/main/java/com/fr/plugin/sxka/sso/controller/SxKaController.java
  15. 12
      src/main/java/com/fr/plugin/sxka/sso/controller/SxKaControllerProvider.java
  16. 41
      src/main/java/com/fr/plugin/sxka/sso/dao/FineLogRegisterDao.java
  17. 21
      src/main/java/com/fr/plugin/sxka/sso/dao/UserInfoDao.java
  18. 78
      src/main/java/com/fr/plugin/sxka/sso/dao/UserRoleTypeDao.java
  19. 132
      src/main/java/com/fr/plugin/sxka/sso/entity/FineLogRegisterEntity.java
  20. 310
      src/main/java/com/fr/plugin/sxka/sso/entity/UserInfoEntity.java
  21. 108
      src/main/java/com/fr/plugin/sxka/sso/entity/UserRoleTypeDBAUtil.java
  22. 45
      src/main/java/com/fr/plugin/sxka/sso/entity/UserRoleTypeEntity.java
  23. 54
      src/main/java/com/fr/plugin/sxka/sso/js/FileDef.java
  24. 25
      src/main/java/com/fr/plugin/sxka/sso/js/JSCSSBridge.java
  25. 57
      src/main/java/com/fr/plugin/sxka/sso/service/UserRoleTypeService.java
  26. 1
      src/main/resources/com/fr/plugin/sxka/sso/registe/css/app.24a019f4.css
  27. 1
      src/main/resources/com/fr/plugin/sxka/sso/registe/css/chunk-vendors.a16c4353.css
  28. BIN
      src/main/resources/com/fr/plugin/sxka/sso/registe/favicon.ico
  29. BIN
      src/main/resources/com/fr/plugin/sxka/sso/registe/fonts/element-icons.535877f5.woff
  30. BIN
      src/main/resources/com/fr/plugin/sxka/sso/registe/fonts/element-icons.732389de.ttf
  31. 25
      src/main/resources/com/fr/plugin/sxka/sso/registe/index.html
  32. 2
      src/main/resources/com/fr/plugin/sxka/sso/registe/js/app.6d7e7596.js
  33. 1
      src/main/resources/com/fr/plugin/sxka/sso/registe/js/app.6d7e7596.js.map
  34. 47
      src/main/resources/com/fr/plugin/sxka/sso/registe/js/chunk-vendors.98ebceb7.js
  35. 1
      src/main/resources/com/fr/plugin/sxka/sso/registe/js/chunk-vendors.98ebceb7.js.map
  36. 5
      src/main/resources/com/fr/plugin/sxka/sso/theme.js
  37. 23
      src/main/resources/conf.properties
  38. BIN
      插件交接文档.docx

5
README.md

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

44
plugin.xml

@ -0,0 +1,44 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?><plugin>
<id>com.fr.plugin.sxka.sso</id>
<name><![CDATA[sso]]></name>
<active>yes</active>
<version>1.20</version>
<env-version>10.0</env-version>
<jartime>2018-07-31</jartime>
<vendor>fr.open</vendor>
<description><![CDATA[sso]]></description>
<change-notes><![CDATA[
[2021-05-17]【1.0】初始化交付版本。<br/>
[2021-05-17]【1.1】增加更新用户信息的机制。<br/>
[2021-06-01]【1.2】增加用户信息存储到外置数据库表中(plugin_sxka_user_info)。<br/>
[2021-06-01]【1.3】增加返回到填报页面的参数username,id。<br/>
[2021-06-01]【1.4】增加返回到填报页面的参数op_name。<br/>
[2021-06-01]【1.5】status状态字段类型修改Int。<br/>
[2021-06-01]【1.6】status状态字段修改成String。<br/>
[2021-06-07]【1.7】尝试修改客户单点回传state为空的问题。<br/>
[2021-06-09]【1.8】切换无权限页面为指定报表模板<br/>
[2021-06-09]【1.9】无权限页面增加参数。<br/>
[2021-06-16]【1.10】增加注册时间字段。<br/>
[2021-06-17]【1.11】无权限页面增加参数。<br/>
[2021-06-17]【1.12】增加注册时间默认值。<br/>
[2021-06-25]【1.13】放行无权限模板页面引用的资源。<br/>
[2021-06-30]【1.14】尝试解决多次跳转单点问题。bug<br/>
[2021-06-30]【1.15】放行报表所有资源请求。bug<br/>
[2021-06-30]【1.16】解决多次跳转单点问题。bug<br/>
[2021-08-09]【1.17】修改密码新增为UUID,屏蔽展示ID,新增模板放行。<br/>
[2021-08-16]【1.18】放行登录页面的/login/config和login/slider bug<br/>
[2021-08-16]【1.19】兼容放行登录页面的/login bug<br/>
[2022-01-09]【1.20】增加权限多选<br/>
]]></change-notes>
<extra-decision>
<GlobalRequestFilterProvider class="com.fr.plugin.sxka.sso.SsoFilter"/>
<LogInOutEventProvider class="com.fr.plugin.sxka.sso.CustomLogInOutEventProvider"/>
<WebResourceProvider class="com.fr.plugin.sxka.sso.js.JSCSSBridge"/>
<ControllerRegisterProvider class="com.fr.plugin.sxka.sso.controller.SxKaControllerProvider"/>
</extra-decision>
<extra-core>
<DBAccessProvider class="com.fr.plugin.sxka.sso.RoleDBAccessProvider"/>
</extra-core>
<function-recorder class="com.fr.plugin.sxka.sso.SxKaPerformanceMonitor"/>
<lifecycle-monitor class="com.fr.plugin.sxka.sso.SxKaPerformanceMonitor"/>
</plugin>

95
src/main/java/com/fr/plugin/sxka/sso/CustomLogInOutEventProvider.java

@ -0,0 +1,95 @@
package com.fr.plugin.sxka.sso;
import com.fr.decision.authority.data.User;
import com.fr.decision.fun.impl.AbstractLogInOutEventProvider;
import com.fr.decision.webservice.login.LogInOutResultInfo;
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.general.PropertiesUtils;
import com.fr.log.FineLoggerFactory;
import com.fr.plugin.sxka.sso.dao.UserInfoDao;
import com.fr.plugin.sxka.sso.entity.UserInfoEntity;
import com.fr.stable.db.action.DBAction;
import com.fr.stable.db.dao.DAOContext;
import com.fr.stable.db.dao.DAOProvider;
import com.fr.stable.query.QueryFactory;
import com.fr.stable.query.condition.QueryCondition;
import com.fr.stable.query.restriction.RestrictionFactory;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.net.URLEncoder;
import java.util.List;
/**
* @Author fr.open
* @Date 2021/5/18
* @Description
**/
public class CustomLogInOutEventProvider extends AbstractLogInOutEventProvider {
@Override
public String logoutAction(LogInOutResultInfo result) {
String state = getUserStateFromCookie(result.getRequest());
FineLoggerFactory.getLogger().info("state为:" + state);
if (state != null) {
try {
DecisionStatusService.loginStatusService().delete(state);
} catch (Exception e) {
FineLoggerFactory.getLogger().error(e.getMessage(), e);
}
}
String logout_redirect_uri =URLEncoder.encode(PropertiesUtils.getProperties("conf").getProperty("logout_redirect_uri"));
String currentLoginName = LoginService.getInstance().getCurrentUserNameFromRequestCookie(result.getRequest());
FineLoggerFactory.getLogger().info("当前登录人为:" + currentLoginName);
try {
int count = RoleDBAccessProvider.getDbAccessor().runDMLAction(new DBAction<Integer>() {
@Override
public Integer run(DAOContext daoContext) throws Exception {
UserInfoDao dao = daoContext.getDAO(UserInfoDao.class);
UserInfoEntity byId = dao.getById(currentLoginName);
if(byId == null){
FineLoggerFactory.getLogger().info("当前外置表有0个登陆人");
return 0;
}
else{
FineLoggerFactory.getLogger().info("当前外置表有1个登陆人:"+byId.getAccount_type());
return 1;
}
}
});
if(count == 0){
FineLoggerFactory.getLogger().info("外置表有没这个人了,再去fine_user看下");
User user = UserService.getInstance().getUserByUserName(currentLoginName);
if(user != null){
FineLoggerFactory.getLogger().info("fine_user里有这个人:id="+user.getId());
logout_redirect_uri = logout_redirect_uri+"/webroot/decision/admin/login";
}
}
} catch (Exception e) {
e.printStackTrace();
FineLoggerFactory.getLogger().info("");
}
FineLoggerFactory.getLogger().info("logout_redirect_uri为:" + logout_redirect_uri);
String logout = PropertiesUtils.getProperties("conf").getProperty("logout");
String format = "%s?client_id=%s&callback=%s?state=%s";
String gotoUrl = String.format(format, logout, PropertiesUtils.getProperties("conf").getProperty("client_id"),logout_redirect_uri , state);
FineLoggerFactory.getLogger().info("登出拼接url为:" + gotoUrl);
return gotoUrl;
}
private String getUserStateFromCookie(HttpServletRequest request) {
if (request.getCookies() == null) return null;
for (Cookie cookie : request.getCookies()) {
if ("uid_state".equals(cookie.getName())) return cookie.getValue();
}
return null;
}
}

74
src/main/java/com/fr/plugin/sxka/sso/RoleDBAccessProvider.java

@ -0,0 +1,74 @@
package com.fr.plugin.sxka.sso;
import com.fr.db.fun.impl.AbstractDBAccessProvider;
import com.fr.decision.webservice.bean.user.UserBean;
import com.fr.decision.webservice.v10.user.UserService;
import com.fr.json.JSONObject;
import com.fr.json.revise.EmbedJson;
import com.fr.log.FineLoggerFactory;
import com.fr.plugin.sxka.sso.conf.RoleXmlConfigReader;
import com.fr.plugin.sxka.sso.controller.SxKaController;
import com.fr.plugin.sxka.sso.dao.FineLogRegisterDao;
import com.fr.plugin.sxka.sso.dao.UserInfoDao;
import com.fr.plugin.sxka.sso.dao.UserRoleTypeDao;
import com.fr.plugin.sxka.sso.entity.UserInfoEntity;
import com.fr.plugin.sxka.sso.service.UserRoleTypeService;
import com.fr.security.encryption.transmission.TransmissionEncryptors;
import com.fr.stable.db.accessor.DBAccessor;
import com.fr.stable.db.action.DBAction;
import com.fr.stable.db.dao.BaseDAO;
import com.fr.stable.db.dao.DAOContext;
import com.fr.stable.db.dao.DAOProvider;
import com.fr.third.fasterxml.jackson.databind.DeserializationFeature;
import com.fr.third.fasterxml.jackson.databind.ObjectMapper;
import java.util.Date;
import java.util.UUID;
/**
* @Author fr.open
* @Date 2021/5/13
* @Description
**/
public class RoleDBAccessProvider extends AbstractDBAccessProvider {
private static DBAccessor dbAccessor = null;
public static DBAccessor getDbAccessor() {
return dbAccessor;
}
@Override
public DAOProvider[] registerDAO() {
return new DAOProvider[]{
UserRoleTypeDao.DAO,
FineLogRegisterDao.DAO,
new DAOProvider() {
@Override
public Class getEntityClass() {
return UserInfoEntity.class;
}
@Override
public Class<? extends BaseDAO> getDAOClass() {
return UserInfoDao.class;
}
}
};
}
@Override
public void onDBAvailable(DBAccessor dbAccessor) {
FineLoggerFactory.getLogger().info("RoleDBAccessProvider dbAccessor:"+dbAccessor);
RoleDBAccessProvider.dbAccessor = dbAccessor;
/*
UserInfoEntity entity = new UserInfoEntity();
entity.setGs_name("ssss");
entity.setGs_social_credit_code("22333");
entity.setId("sssdd111");
entity.setOp_name("ss22");
SxKaController.addRegisteLog(entity,"1");
*/
}
}

703
src/main/java/com/fr/plugin/sxka/sso/SsoFilter.java

@ -0,0 +1,703 @@
package com.fr.plugin.sxka.sso;
import com.fr.base.PropertiesUtils;
import com.fr.data.NetworkHelper;
import com.fr.decision.authority.AuthorityContext;
import com.fr.decision.authority.data.CustomRole;
import com.fr.decision.authority.data.User;
import com.fr.decision.fun.impl.AbstractGlobalRequestFilterProvider;
import com.fr.decision.mobile.terminal.TerminalHandler;
import com.fr.decision.webservice.bean.authentication.OriginUrlResponseBean;
import com.fr.decision.webservice.bean.user.UserBean;
import com.fr.decision.webservice.exception.user.UserNotExistException;
import com.fr.decision.webservice.utils.DecisionServiceConstants;
import com.fr.decision.webservice.utils.DecisionStatusService;
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.http.HttpRequest;
import com.fr.general.http.HttpToolbox;
import com.fr.json.JSONObject;
import com.fr.json.revise.EmbedJson;
import com.fr.locale.InterProviderFactory;
import com.fr.log.FineLoggerFactory;
import com.fr.plugin.sxka.sso.conf.UrlFilterConfigReader;
import com.fr.plugin.sxka.sso.controller.SxKaController;
import com.fr.plugin.sxka.sso.dao.UserInfoDao;
import com.fr.plugin.sxka.sso.entity.UserInfoEntity;
import com.fr.plugin.sxka.sso.entity.UserRoleTypeEntity;
import com.fr.plugin.sxka.sso.service.UserRoleTypeService;
import com.fr.plugin.transform.FunctionRecorder;
import com.fr.security.encryption.transmission.TransmissionEncryptors;
import com.fr.stable.StringUtils;
import com.fr.stable.db.action.DBAction;
import com.fr.stable.db.dao.DAOContext;
import com.fr.stable.query.QueryFactory;
import com.fr.stable.query.restriction.RestrictionFactory;
import com.fr.stable.web.Device;
import com.fr.third.fasterxml.jackson.databind.DeserializationFeature;
import com.fr.third.fasterxml.jackson.databind.ObjectMapper;
import com.fr.third.springframework.http.HttpHeaders;
import com.fr.third.springframework.http.MediaType;
import com.fr.third.springframework.util.DigestUtils;
import com.fr.web.controller.decision.api.auth.LoginResource;
import com.fr.web.utils.WebUtils;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
/**
* @Author fr.open
* @Date 2021/5/12
* @Description
**/
//@FunctionRecorder
public class SsoFilter extends AbstractGlobalRequestFilterProvider {
private static String[] notFilter = {
"/login/config",
"/login/slider",
"/system",
"/decision/file",
"/decision/resources",
"/remote",
"/view/report",
"/static",
"/sxka",
"/url/elite/",
"/com.fr.plugin.elite/elite/",
"/preview/info"
};
private static HashMap<String, String> ROLE_MAP;
public SsoFilter() {
}
static {
ROLE_MAP = new HashMap<>();
ROLE_MAP.put("1", "企业管理员");
ROLE_MAP.put("2", "个人用户");
ROLE_MAP.put("3", "企业操作员");
ROLE_MAP.put("4", "政府端用户");
}
@Override
public String filterName() {
return "sxka";
}
@Override
public String[] urlPatterns() {
return new String[]{
"/decision",
"/decision/",
"/decision/login",
"/decision/admin/login"
};
}
@Override
public void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain filterChain) {
String reqUri = req.getRequestURI();
FineLoggerFactory.getLogger().info(getLogMessage("进来的url:"+reqUri));
FineLoggerFactory.getLogger().info(getLogMessage("req.getMethod():"+req.getMethod()));
if (reqUri.endsWith("/admin/login")) { //跳转到决策系统登录界面
try {
String page = new LoginResource().page(req, res);
FineLoggerFactory.getLogger().info(getLogMessage("跳转到决策系统登录界面"));
if (StringUtils.isBlank(page)) {
return;
}
PrintWriter writer = WebUtils.createPrintWriter(res);
writer.println(page);
writer.flush();
writer.close();
} catch (Exception e) {
FineLoggerFactory.getLogger().error(e.getMessage(), e);
}
return;
}
if (isLogin(req) || isAccept(req)) {//如果已经登录过或者/view/*,或者是notFilter中的,或者是css,js都放过去
filter(req, res, filterChain);
return;
}
//登录页面跳转地址拦截
String origin = WebUtils.getHTTPRequestParameter(req, "origin");
FineLoggerFactory.getLogger().info(getLogMessage("origin:"+origin));
if (reqUri.endsWith("decision/login")) {//如果url是决策系统的登录界面,拦截一下
if("get".equalsIgnoreCase(req.getMethod())){
String state = this.getUserStateFromCookie(req, res);//从cookie中获取uid_state的值,如果没有就用UUID创建一个存到cookie中。
try {
if (StringUtils.isNotBlank(origin)) {//把登录前的url存起来
OriginUrlResponseBean path = DecisionStatusService.originUrlStatusService().get(origin);
cacheParam(res, path.getOriginUrl());
}
FineLoggerFactory.getLogger().info("Redirect origin is {}", req.getRequestURL());
FineLoggerFactory.getLogger().info(getLogMessage("如果是登录请求,跳转到认证url上"));
//这里会将请求转到https://www.singlewindow.shaanxi.cn/oauth/authorize上去认证,成功后回到 http://locahost:8075/webroot/decision
String authorizeUrl = buildAuthorizeUrl(state);
FineLoggerFactory.getLogger().info(getLogMessage("认证url为:"+authorizeUrl));
res.sendRedirect(authorizeUrl);
return;
} catch (Exception e) {
FineLoggerFactory.getLogger().error(e.getMessage(), e);
}
}else {
filter(req, res, filterChain);
return;
}
}
//认证成功后回来的请求,检查code
String state = this.getUserStateFromCookie(req, res);
String code = req.getParameter("code");
FineLoggerFactory.getLogger().info(getLogMessage("认证成功后回来的请求,检查code:"+code+",state:"+state));
if (StringUtils.isNotBlank(code)) {
//到https://www.singlewindow.shaanxi.cn/oauth/token上获取token。
JSONObject data = acquireAccessToken(code);
FineLoggerFactory.getLogger().info("get access_token is {}", data);
// 计算过期时间
int expires = Integer.valueOf(data.get("expires_in").toString());
Date expiresTime = new Date(System.currentTimeMillis() + (expires * 1000));
data.put("expires_at", expiresTime);
// 保存关系映射,将data存到DecisionStatusService上,state是key。DecisionStatusService上如果超过了expires_at,就会自动删除
putState(state, data);
}
JSONObject tokenItem = null;
try {
tokenItem = DecisionStatusService.loginStatusService().get(state);
} catch (Exception e) {
FineLoggerFactory.getLogger().error(e.getMessage(), e);
}
if (tokenItem == null) {//如果获取不到state对应的data
try {
String jump = getOrginUrl(req);//req.getRequestURL() + (req.getQueryString() == null ? StringUtils.EMPTY : "?" + req.getQueryString());
cacheParam(res, jump);
FineLoggerFactory.getLogger().info("Redirect origin is {}", jump);
String authorizeUrl = buildAuthorizeUrl(state);
FineLoggerFactory.getLogger().info(getLogMessage("没获取到tokenItem,跳转到认证上去,authorityYrl:"+authorizeUrl));
//跳转到认证上去
res.sendRedirect(authorizeUrl);
return;
} catch (Exception e) {
FineLoggerFactory.getLogger().error(e.getMessage(), e);
}
}
// 检查 access token 是否过期
Date tokenExpiresAt = (Date) tokenItem.get("expires_at");
Date now = new Date();
FineLoggerFactory.getLogger().info(getLogMessage("检查 access token 是否过期"));
if (tokenExpiresAt.before(now)) {
// 使用 refresh token 刷新 access token
String refreshToken = tokenItem.get("refresh_token").toString();
tokenItem = this.refreshToken(refreshToken);
putState(state, tokenItem);
}
String accessToken = tokenItem.get("access_token").toString();
//从https://www.singlewindow.shaanxi.cn/resource/user上获取该access_token对应的用户信息
FineLoggerFactory.getLogger().info(getLogMessage("从https://xxxx/resource/user上获取该access_token对应的用户信息"));
JSONObject userProfile = this.acquireUserInfo(state, accessToken);
try {
String key =userProfile.getString("id");
FineLoggerFactory.getLogger().info("存到缓存里:key:"+key+",userProfile:"+userProfile);
DecisionStatusService.loginStatusService().put(key,userProfile);
} catch (Exception e) {
FineLoggerFactory.getLogger().info("存到缓存里失败");
e.printStackTrace();
}
try {
boolean isFirst = false;
if (!existUser(userProfile.getString("id"))) {//如果决策系统不存在id属性值的用户,那么默认在决策系统中加上这个人。
FineLoggerFactory.getLogger().info("user {} not exist ", userProfile.getString("id"));
isFirst = true;
}
UserInfoEntity infoEntity = recordUserInfo(userProfile);//将用户信息记录到数据库中
//处理用户的角色
if (checkAuth(infoEntity, req, res,isFirst,filterChain)) {
return;
}
} catch (Exception e) {
FineLoggerFactory.getLogger().error(e.getMessage(), e);
}
filter(req, res, filterChain);
}
private void putState(String state, JSONObject data) {
try {
DecisionStatusService.loginStatusService().put(state, data);
} catch (Exception e) {
FineLoggerFactory.getLogger().error(e.getMessage(), e);
}
}
private String getOrginUrl(HttpServletRequest req){
String jump = req.getRequestURL() + (req.getQueryString() == null ? StringUtils.EMPTY : "?" + req.getQueryString());
return jump;
}
private void cacheParam(HttpServletResponse res, String jump) {
String id = UUID.randomUUID().toString();
try {
DecisionStatusService.originUrlStatusService().put(id, new OriginUrlResponseBean(jump));//添加重定向地址
FineLoggerFactory.getLogger().info("save orgin url id:"+id+", orgin:"+jump);
} catch (Exception e) {
FineLoggerFactory.getLogger().info(e.getMessage(), e);
}
Cookie cookie = new Cookie("ORIGIN_URL", id);
cookie.setPath("/");
cookie.setMaxAge(60);
//cookie.setHttpOnly(true);
FineLoggerFactory.getLogger().info("ORIGIN_URL:id="+id);
res.addCookie(cookie);
}
public static void addRole(String userId,String roleName) throws Exception {
UserBean userAccount = UserService.getInstance().getUserAccount(userId);
CustomRole role = AuthorityContext.getInstance().getCustomRoleController().findOne(QueryFactory.create().addRestriction(RestrictionFactory.eq("name", roleName)));
if (role != null) {
//删除以前的角色,增加新角色
List<CustomRole> oldRoleList = AuthorityContext.getInstance().getCustomRoleController().findByUser(userAccount.getId(), QueryFactory.create());
oldRoleList.forEach(e -> {
try {
AuthorityContext.getInstance().getUserController().removeUserFromCustomRole(userAccount.getId(), e.getId());
} catch (Exception exception) {
FineLoggerFactory.getLogger().error(exception.getMessage(), exception);
}
});
FineLoggerFactory.getLogger().info("增加角色,roleName:"+roleName+",userId:"+userId);
AuthorityContext.getInstance().getUserController().addUserToCustomRole(userAccount.getId(), role.getId());
}
}
private boolean checkAuth(UserInfoEntity entity, HttpServletRequest req, HttpServletResponse res,boolean isFirst,FilterChain filterChain) throws Exception {
FineLoggerFactory.getLogger().info(getLogMessage("验证用户角色,status:")+entity.getStatus());
//这里再判断下个人用户,个人用户必须要在权限菜单里有数据才能视为不是第一次
if(entity.getAccount_type().equals("2") == true){
//
FineLoggerFactory.getLogger().info(getLogMessage("个人用户必须要在权限菜单里有数据才能视为不是第一次"));
List<UserRoleTypeEntity> userRoleTypeList = UserRoleTypeService.getInstance().getUserRoleTypeByUserId(entity.getId());
FineLoggerFactory.getLogger().info("个人用户:"+entity.getId()+",此时有的权限个数为:"+userRoleTypeList.size());
if(userRoleTypeList.size() == 0){
isFirst = true;
}
else{
isFirst = false;
}
}
if(isFirst == false){
if (StringUtils.isNotBlank(entity.getStatus()) && entity.getStatus().equalsIgnoreCase("true")) {
//如果已经授权了
FineLoggerFactory.getLogger().info(getLogMessage("如果已经是激活状态"));
/*
if (entity.getAccount_type().equals("1") || entity.getAccount_type().equals("3") || entity.getAccount_type().equals("4")) { //如果账号类型是这些
String roleName = ROLE_MAP.containsKey(entity.getAccount_type()) ? ROLE_MAP.get(entity.getAccount_type()) : "其他";
addRole(entity.getId(),roleName);
}
*/
//登录
loginFromToken(req, res, entity.getId());
FineLoggerFactory.getLogger().info(getLogMessage("自动登录结束"));
String jump = getOrigin(req);
FineLoggerFactory.getLogger().info("get Origin path is {}", jump);
if (StringUtils.isNotBlank(jump)) {
FineLoggerFactory.getLogger().info(getLogMessage("跳转到orgin:"+jump));
res.sendRedirect(jump);
}
else{
filter(req, res, filterChain);
}
return true;
}
}
/*
if (entity.getAccount_type().equals("1") || entity.getAccount_type().equals("3") || entity.getAccount_type().equals("4")) {
setError(res, entity.getId()); //到冻结界面去
return true;
}
*/
FineLoggerFactory.getLogger().info("isFirst:"+isFirst);
//还没激活
if(isFirst == true){ //如果是首次
//如果没授权,
//其他类型跳转到write_report界面去,我应该是在这里做
FineLoggerFactory.getLogger().info(getLogMessage("下面是没激活,也没有授权,就跳转到write_report配置的授权界面"));
String url = PropertiesUtils.getProperties("conf").getProperty("write_report");
FineLoggerFactory.getLogger().info("write_report:"+url);
String jump = getOrigin(req);
if(StringUtils.isBlank(jump)){
jump = getOrginUrl(req);
}
String param = "username=" + entity.getOp_name() + "&id=" + entity.getId()+"&accountType="+entity.getAccount_type()+"&orgin="+jump+"";
if(url.indexOf("&clientType=1") != -1){
param += "&clientType=1";
url = url.replace("&clientType=1","");
}
if(url.indexOf("&clientType=2") != -1){
param += "&clientType=2";
url = url.replace("&clientType=2","");
}
FineLoggerFactory.getLogger().info("urlparam加密前:"+param);
param = Encrypt(param, SxKaController.cKey);//URLEncoder.encode(param);
url = url.indexOf("?") != -1 ? url + "&" + param : url + "?" + param;
FineLoggerFactory.getLogger().info("授权界面url:"+url);
res.sendRedirect(url);
}
else{ //如果是非首次,也没激活,就去冻结
if(entity.getAccount_type().equals("1") == true){
FineLoggerFactory.getLogger().info("企业管理员第二次来,直接跳过");
//登录
loginFromToken(req, res, entity.getId());
FineLoggerFactory.getLogger().info(getLogMessage("自动登录结束"));
filter(req, res, filterChain);
return true;
}
FineLoggerFactory.getLogger().info("到冻结界面去");
setError(res, entity.getId()); //到冻结界面去
return true;
}
return true;
}
// 加密
public static String Encrypt(String sSrc, String sKey) throws Exception {
if (sKey == null) {
System.out.print("Key为空null");
return null;
}
// 判断Key是否为16位
if (sKey.length() != 16) {
System.out.print("Key长度不是16位");
return null;
}
byte[] raw = sKey.getBytes("utf-8");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//"算法/模式/补码方式"
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));
String msg = Base64.getEncoder().encodeToString(encrypted);
return msg;//此处使用BASE64做转码功能,同时能起到2次加密的作用。
}
private static UserInfoEntity recordUserInfo(JSONObject user) {
//将json转为UserInfoEntity对象
ObjectMapper mapper = EmbedJson.MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
UserInfoEntity entity = mapper.convertValue(user, UserInfoEntity.class);
try {
RoleDBAccessProvider.getDbAccessor().runDMLAction(new DBAction<UserInfoEntity>() {
@Override
public UserInfoEntity run(DAOContext daoContext) throws Exception {
UserInfoDao dao = daoContext.getDAO(UserInfoDao.class);
//查询数据库是否存在该id对应的数据
UserInfoEntity byId = dao.getById(entity.getId());
if (byId != null) {//如果存在,更新下
entity.setStatus(byId.getStatus());
entity.setAccount_type(byId.getAccount_type());
entity.setRegistryDate(byId.getRegistryDate());
FineLoggerFactory.getLogger().info("外置表里有这个用户,这里更新");
} else {//如果不存在,将状态置为false
FineLoggerFactory.getLogger().info("外置表里没这个用户,这里不增加,留到后面来增加");
}
//更新或者添加
// dao.addOrUpdate(entity);
return entity;
}
});
} catch (Exception e) {
FineLoggerFactory.getLogger().info(e.getMessage(), e);
}
return entity;
}
private String getOrigin(HttpServletRequest req) throws Exception {
Cookie[] cookies = req.getCookies();
if (cookies == null) {
return null;
}
for (int i = 0; i < cookies.length; i++) {
if ("ORIGIN_URL".equals(cookies[i].getName())) {
String id = cookies[i].getValue();
OriginUrlResponseBean path = DecisionStatusService.originUrlStatusService().get(id);
FineLoggerFactory.getLogger().info("ORIGIN_URL,id="+id+",path="+path);
if (path != null) {
DecisionStatusService.originUrlStatusService().delete(id);
return path.getOriginUrl();
}
}
}
return StringUtils.EMPTY;
}
public static boolean existUser(String username) {
User user = null;
try {
user = UserService.getInstance().getUserByUserName(username);
} catch (Exception e) {
FineLoggerFactory.getLogger().error(e.getMessage(), e);
}
return user != null;
}
private boolean loginFromToken(HttpServletRequest req, HttpServletResponse res, String username) throws Exception {
try {
if (StringUtils.isNotEmpty(username)) {
FineLoggerFactory.getLogger().info("current username:" + username);
User user = UserService.getInstance().getUserByUserName(username);
FineLoggerFactory.getLogger().info("get user:" + user);
if (user == null) {
throw new UserNotExistException();
}
String token = LoginService.getInstance().login(req, res, username);
FineLoggerFactory.getLogger().info("get login token:" + token);
req.setAttribute(DecisionServiceConstants.FINE_AUTH_TOKEN_NAME, token);
FineLoggerFactory.getLogger().info("username:" + username + "login success");
return true;
} else {
FineLoggerFactory.getLogger().warn("username is null!");
return false;
}
} catch (Exception e) {
FineLoggerFactory.getLogger().error(e.getMessage(), e);
}
return false;
}
private JSONObject acquireUserInfo(String state, String accessToken) {
String url = PropertiesUtils.getProperties("conf").getProperty("user_url");
Map<String, String> params = new HashMap<>();
params.put("client_id", PropertiesUtils.getProperties("conf").getProperty("client_id"));
params.put("access_token", accessToken);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
try {
String res = HttpToolbox.executeAndParse(HttpRequest.custom().url(url)
.headers(headers.toSingleValueMap())
.post(params)
.build());
FineLoggerFactory.getLogger().info("get user name url is 【{}】,params is,{} res is {}", url, params, res);
JSONObject object = new JSONObject(res);
return object.getJSONObject("data");
} catch (IOException e) {
FineLoggerFactory.getLogger().error(e.getMessage(), e);
}
return JSONObject.EMPTY;
}
private JSONObject refreshToken(String refreshToken) {
String url = PropertiesUtils.getProperties("conf").getProperty("token_url");
Map<String, String> params = new HashMap<>();
params.put("grant_type", "refresh_token");
params.put("refresh_token", refreshToken);
params.put("client_id", PropertiesUtils.getProperties("conf").getProperty("client_id"));
params.put("client_sign", this.makeSign(refreshToken));
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
try {
String res = HttpToolbox.executeAndParse(HttpRequest.custom().url(url)
.headers(headers.toSingleValueMap())
.post(params)
.build());
FineLoggerFactory.getLogger().info("get refresh token url is 【{}】,params is,{} res is {}", url, params, res);
JSONObject object = new JSONObject(res);
return object.getJSONObject("data");
} catch (IOException e) {
FineLoggerFactory.getLogger().error(e.getMessage(), e);
}
return JSONObject.EMPTY;
}
private JSONObject acquireAccessToken(String code) {
FineLoggerFactory.getLogger().info(getLogMessage("去远程获取token"));
String url = PropertiesUtils.getProperties("conf").getProperty("token_url");
Map<String, String> params = new HashMap<>();
params.put("grant_type", "authorization_code");
params.put("code", code);
params.put("client_id", PropertiesUtils.getProperties("conf").getProperty("client_id"));
params.put("client_sign", this.makeSign(code));
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
try {
String res = HttpToolbox.executeAndParse(HttpRequest.custom().url(url)
.headers(headers.toSingleValueMap())
.post(params)
.build());
FineLoggerFactory.getLogger().info("get access token url is 【{}】,params is,{} res is {}", url, params, res);
JSONObject object = new JSONObject(res);
return object.getJSONObject("data");
} catch (IOException e) {
FineLoggerFactory.getLogger().error(e.getMessage(), e);
}
return JSONObject.EMPTY;
}
/**
* 生成签名值= md5Hex("<client_id>$<data>$<client_secret>", UTF8)
*
* @param data
* @return
*/
private String makeSign(String data) {
String value = String.join("$", new String[]{
PropertiesUtils.getProperties("conf").getProperty("client_id"),
data,
PropertiesUtils.getProperties("conf").getProperty("client_secret")
});
return DigestUtils.md5DigestAsHex(value.getBytes(StandardCharsets.UTF_8));
}
private String buildAuthorizeUrl(String state) {
String format = "%s?client_id=%s&response_type=code&scope=A1,C1,C2&state=%s&redirect_uri=%s";
return String.format(format, PropertiesUtils.getProperties("conf").getProperty("auth_url"), PropertiesUtils.getProperties("conf").getProperty("client_id"), state, PropertiesUtils.getProperties("conf").getProperty("redirect_uri"));
}
private void setUserStateCookie(HttpServletResponse response, String state) {
Cookie cookie = new Cookie("uid_state", state);
cookie.setMaxAge(300);
// 正式环境采用HTTPS协议,需要取消下方注释,确保仅在HTTPS下可用
// cookie.setSecure(true);
cookie.setPath("/");
response.addCookie(cookie);
}
private String getUserStateFromCookie(HttpServletRequest request, HttpServletResponse res) {
FineLoggerFactory.getLogger().info(getLogMessage("从cookie获取uid_state"));
if (request.getCookies() == null) {
return null;
}
String state = StringUtils.EMPTY;
for (Cookie cookie : request.getCookies()) {
if ("uid_state".equals(cookie.getName())) {
state = cookie.getValue();
}
}
if (StringUtils.isBlank(state)) {
state = UUID.randomUUID().toString();
this.setUserStateCookie(res, state);
}
return state;
}
private boolean isAccept(HttpServletRequest req) {
FineLoggerFactory.getLogger().info(getLogMessage("看url是否为放行的url"));
if (req.getRequestURI().endsWith("/view/form") || req.getRequestURI().endsWith("/view/report")) {
return true;
/*String viewlet = WebUtils.getHTTPRequestParameter(req, "viewlet");
if (StringUtils.isBlank(viewlet)) {
return true;
}
if (!whiteList.stream().filter(e -> viewlet.contains(e)).collect(Collectors.toList()).isEmpty()) {
return true;
}*/
}
String[] urlFilters = getUrlFilterArray();
for (int i = 0; i < urlFilters.length; i++) {
if (req.getRequestURI().contains(urlFilters[i])) {
return true;
}
}
if (req.getRequestURI().endsWith("/.css") || req.getRequestURI().endsWith("/.js")) {
return true;
}
return false;
}
private boolean isLogin(HttpServletRequest request) {
String oldToken = TokenResource.COOKIE.getToken(request);
boolean isOk = oldToken != null && checkTokenValid(request, (String) oldToken);
FineLoggerFactory.getLogger().info(getLogMessage("验证是否登录,如果有token,验证有效性:isOk:"+isOk));
return isOk;
}
private boolean checkTokenValid(HttpServletRequest req, String token) {
try {
Device device = NetworkHelper.getDevice(req);
FineLoggerFactory.getLogger().info(getLogMessage("调用LoginService.getInstance().loginStatusValid验证token有效性"));
LoginService.getInstance().loginStatusValid(token, TerminalHandler.getTerminal(req, device));
return true;
} catch (Exception ignore) {
}
return false;
}
public static void setError(HttpServletResponse res, String id) {
String error = PropertiesUtils.getProperties("conf").getProperty("unavailable");
try {
if (StringUtils.isNotBlank(error)) {
error = error.contains("?") ? (error + "&id=" + id) : (error + "?+id=" + id);
FineLoggerFactory.getLogger().info("到冻结界面去了:"+error);
res.sendRedirect(error);
return;
}
FineLoggerFactory.getLogger().info("到冻结界面去了");
PrintWriter printWriter = WebUtils.createPrintWriter(res);
Map<String, Object> map = new HashMap<>();
map.put("result", InterProviderFactory.getProvider().getLocText("Fine-Engine_Error_Page_Result"));
map.put("reason", "当前用户已冻结,请联系系统管理员激活");
map.put("solution", InterProviderFactory.getProvider().getLocText("Fine-Engine_Please_Contact_Platform_Admin"));
String page = WebServiceUtils.parseWebPageResourceSafe("com/fr/web/controller/decision/entrance/resources/unavailable.html", map);
printWriter.write(page);
printWriter.flush();
printWriter.close();
} catch (Exception e) {
FineLoggerFactory.getLogger().error(e.getMessage(), e);
}
}
private void filter(HttpServletRequest req, HttpServletResponse res, FilterChain filterChain) {
try {
filterChain.doFilter(req, res);
} catch (IOException e) {
FineLoggerFactory.getLogger().error(e.getMessage(), e);
} catch (ServletException e) {
FineLoggerFactory.getLogger().error(e.getMessage(), e);
}
}
private String[] getUrlFilterArray(){
String[] urls = UrlFilterConfigReader.getInstance().getUrlFilterArray();
if(urls == null){
return notFilter;
}
else{
return urls;
}
}
private String getLogMessage(String message){
return "[SsoFilter]"+message;
}
}

101
src/main/java/com/fr/plugin/sxka/sso/SxKaPerformanceMonitor.java

@ -0,0 +1,101 @@
package com.fr.plugin.sxka.sso;
import com.fr.decision.webservice.utils.DecisionStatusService;
import com.fr.json.JSONObject;
import com.fr.log.FineLoggerFactory;
import com.fr.plugin.context.PluginContext;
import com.fr.plugin.observer.inner.AbstractPluginLifecycleMonitor;
import com.fr.plugin.sxka.sso.conf.RoleXmlConfigReader;
import com.fr.plugin.sxka.sso.conf.UrlFilterConfigReader;
import com.fr.plugin.sxka.sso.controller.SxKaController;
import com.fr.plugin.sxka.sso.entity.UserInfoEntity;
import com.fr.plugin.transform.FunctionRecorder;
import com.fr.record.analyzer.EnableMetrics;
import com.fr.stable.xml.XMLTools;
import com.fr.workspace.WorkContext;
import java.io.File;
@EnableMetrics
@FunctionRecorder
public class SxKaPerformanceMonitor extends AbstractPluginLifecycleMonitor {
@Override
public void afterRun(PluginContext pluginContext) {
FineLoggerFactory.getLogger().info(pluginContext.getName()+"插件启动完成");
///webroot/decision/file?path=com/fr/plugin/sxka/sso/registe/index.html
//读取webroot下的角色配置文件
String envPath = WorkContext.getCurrent().getPath();
FineLoggerFactory.getLogger().info("envPath:"+envPath);
String webReport = (new File(envPath)).getParent();
FineLoggerFactory.getLogger().info("webReport:"+webReport);
File envFile = new File(webReport+File.separator+"sxka"+File.separator+"role.xml");
try {
RoleXmlConfigReader.getInstance().init();
XMLTools.readFileXML(RoleXmlConfigReader.getInstance(), envFile);
} catch (Exception e) {
e.printStackTrace();
}
File urlFilterFile = new File(webReport+File.separator+"sxka"+File.separator+"urlFilter.xml");
try {
UrlFilterConfigReader.getInstance().init();
XMLTools.readFileXML(UrlFilterConfigReader.getInstance(), urlFilterFile);
} catch (Exception e) {
e.printStackTrace();
}
/*
try {
String ass = SsoFilter.Encrypt("username=bbb&id=bbb&accountType=4&orgin=http://baidu.com&clientType=1", SxKaController.cKey);
FineLoggerFactory.getLogger().info("ass:"+ass);
ass = SsoFilter.Encrypt("username=bbb&id=bbb&accountType=4&orgin=http://baidu.com&clientType=2", SxKaController.cKey);
FineLoggerFactory.getLogger().info("ass:"+ass);
} catch (Exception e) {
e.printStackTrace();
}*/
/*
JSONObject userProfile = new JSONObject();
userProfile.put("id","aaa");
userProfile.put("op_name","ssss");
userProfile.put("organization","ssss1");
userProfile.put("account_type","1");
userProfile.put("login_type","1");
userProfile.put("gs_name","2333");
userProfile.put("gs_type","2333");
userProfile.put("gs_name_en","2333");
userProfile.put("gs_address","2333");
userProfile.put("gs_address_en","2333");
userProfile.put("gs_tax_code","2333");
userProfile.put("gs_expires","2333");
userProfile.put("gs_postcode","2333");
userProfile.put("gs_scope","2333");
userProfile.put("gs_status","2333");
userProfile.put("gs_regcap","2333");
userProfile.put("gs_regcap_cur","2333");
userProfile.put("gs_social_credit_code","2333");
userProfile.put("gs_code","2333");
userProfile.put("gs_regorg","2333");
userProfile.put("gs_reg_number","2333");
userProfile.put("gs_location","2333");
userProfile.put("cus_number","2333");
userProfile.put("cus_expires","2333");
userProfile.put("cus_master","2333");
userProfile.put("status","2333");
userProfile.put("registry_date","2333");
try {
DecisionStatusService.loginStatusService().put("aaa",userProfile);
} catch (Exception e) {
e.printStackTrace();
}
*/
}
@Override
public void beforeStop(PluginContext pluginContext) {
FineLoggerFactory.getLogger().info(pluginContext.getName()+"插件即将停止");
}
}

13
src/main/java/com/fr/plugin/sxka/sso/beans/DecryptParamBean.java

@ -0,0 +1,13 @@
package com.fr.plugin.sxka.sso.beans;
public class DecryptParamBean {
private String decryptParam;
public String getDecryptParam() {
return decryptParam;
}
public void setDecryptParam(String decryptParam) {
this.decryptParam = decryptParam;
}
}

23
src/main/java/com/fr/plugin/sxka/sso/beans/SxkaConfigBean.java

@ -0,0 +1,23 @@
package com.fr.plugin.sxka.sso.beans;
public class SxkaConfigBean {
private String unavailable;
private String unavailable1;
public String getUnavailable() {
return unavailable;
}
public String getUnavailable1() {
return unavailable1;
}
public void setUnavailable(String unavailable) {
this.unavailable = unavailable;
}
public void setUnavailable1(String unavailable1) {
this.unavailable1 = unavailable1;
}
}

50
src/main/java/com/fr/plugin/sxka/sso/beans/UserRoleTypeParamBean.java

@ -0,0 +1,50 @@
package com.fr.plugin.sxka.sso.beans;
public class UserRoleTypeParamBean {
private String userId;
private String userRoleTypes;
private int accountType;
private String orgin;
private String clientType;
public String getClientType() {
return clientType;
}
public void setClientType(String clientType) {
this.clientType = clientType;
}
public String getOrgin() {
return orgin;
}
public void setOrgin(String orgin) {
this.orgin = orgin;
}
public int getAccountType() {
return accountType;
}
public void setAccountType(int accountType) {
this.accountType = accountType;
}
public void setUserId(String userId) {
this.userId = userId;
}
public void setUserRoleTypes(String userRoleTypes) {
this.userRoleTypes = userRoleTypes;
}
public String getUserId() {
return userId;
}
public String getUserRoleTypes() {
return userRoleTypes;
}
}

96
src/main/java/com/fr/plugin/sxka/sso/conf/RoleConfigBean.java

@ -0,0 +1,96 @@
package com.fr.plugin.sxka.sso.conf;
public class RoleConfigBean {
private String roleType;
private String roleSetPageUrl;
private String roleName;
private String roleDescn;
private boolean selected;
private boolean disabled;
private String owner;
private boolean isTab;
private boolean audit;
private String roleCode;
public String getRoleCode() {
return roleCode;
}
public void setRoleCode(String roleCode) {
this.roleCode = roleCode;
}
public void setAudit(boolean audit) {
this.audit = audit;
}
public boolean isAudit() {
return audit;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
public void setDisabled(boolean disabled) {
this.disabled = disabled;
}
public void setOwner(String owner) {
this.owner = owner;
}
public void setTab(boolean tab) {
isTab = tab;
}
public boolean isSelected() {
return selected;
}
public boolean isDisabled() {
return disabled;
}
public String getOwner() {
return owner;
}
public boolean isTab() {
return isTab;
}
public void setRoleType(String roleType) {
this.roleType = roleType;
}
public void setRoleSetPageUrl(String roleSetPageUrl) {
this.roleSetPageUrl = roleSetPageUrl;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public void setRoleDescn(String roleDescn) {
this.roleDescn = roleDescn;
}
public String getRoleType() {
return roleType;
}
public String getRoleSetPageUrl() {
return roleSetPageUrl;
}
public String getRoleName() {
return roleName;
}
public String getRoleDescn() {
return roleDescn;
}
}

74
src/main/java/com/fr/plugin/sxka/sso/conf/RoleXmlConfigReader.java

@ -0,0 +1,74 @@
package com.fr.plugin.sxka.sso.conf;
import com.fr.stable.xml.XMLReadable;
import com.fr.stable.xml.XMLableReader;
import java.util.ArrayList;
import java.util.List;
public class RoleXmlConfigReader implements XMLReadable {
private static RoleXmlConfigReader instance;
public static RoleXmlConfigReader getInstance(){
if(instance == null){
instance = new RoleXmlConfigReader();
}
return instance;
}
public List<RoleConfigBean> roles;
public void init(){
roles = new ArrayList<>();
}
public String getRoleCodeByName(String roleName){
for(RoleConfigBean bean : roles){
if(bean.getRoleType().equals(roleName)){
return bean.getRoleCode();
}
}
return "";
}
/**
* 配置文件格式为:
* <root>
* <roleType type="政府端" selected="false" roleCode="aaaa" disabled="false" owner="0,1,2,3" isTab="true" name="政府端" descn="这是一个企业管理员" url="/aaa/uuu/ddd" />
*
* </root>
* @param reader
*/
@Override
public void readXML(XMLableReader reader) {
if (reader.isChildNode()) {
String nodeName = reader.getTagName();
if("roleType".equals(nodeName)){
RoleConfigBean bean = new RoleConfigBean();
String type = reader.getAttrAsString("type","");
String roleCode = reader.getAttrAsString("roleCode","");
String name = reader.getAttrAsString("name","");
String descn = reader.getAttrAsString("descn","");
String url = reader.getAttrAsString("url","");
boolean selected = reader.getAttrAsBoolean("selected",false);
boolean disabled = reader.getAttrAsBoolean("disabled",false);
String owner = reader.getAttrAsString("owner","");
boolean isTab = reader.getAttrAsBoolean("isTab",false);
boolean audit = reader.getAttrAsBoolean("audit",false);
bean.setRoleCode(roleCode);
bean.setSelected(selected);
bean.setDisabled(disabled);
bean.setOwner(owner);
bean.setTab(isTab);
bean.setRoleDescn(descn);
bean.setRoleName(name);
bean.setRoleType(type);
bean.setRoleSetPageUrl(url);
bean.setAudit(audit);
roles.add(bean);
}
}
}
}

49
src/main/java/com/fr/plugin/sxka/sso/conf/UrlFilterConfigReader.java

@ -0,0 +1,49 @@
package com.fr.plugin.sxka.sso.conf;
import com.fr.stable.StringUtils;
import com.fr.stable.xml.XMLReadable;
import com.fr.stable.xml.XMLableReader;
import java.util.ArrayList;
import java.util.List;
public class UrlFilterConfigReader implements XMLReadable {
private static UrlFilterConfigReader instance;
public static UrlFilterConfigReader getInstance(){
if(instance == null){
instance = new UrlFilterConfigReader();
}
return instance;
}
public List<String> urlFilters;
public void init(){
urlFilters = new ArrayList<>();
}
public String[] getUrlFilterArray(){
if(urlFilters == null || urlFilters.size() == 0){
return null;
}
String[] urls = new String[urlFilters.size()];
for(int i = 0 ; i < urlFilters.size();i++){
urls[i] = urlFilters.get(i);
}
return urls;
}
@Override
public void readXML(XMLableReader reader) {
if (reader.isChildNode()) {
String nodeName = reader.getTagName();
if ("url".equals(nodeName)) {
String urlValue = StringUtils.trim(reader.getElementValue());
if(StringUtils.isNotEmpty(urlValue)){
urlFilters.add(urlValue);
}
}
}
}
}

9
src/main/java/com/fr/plugin/sxka/sso/conf/aaa.xml

@ -0,0 +1,9 @@
<root>
<roleType type="企业管理" selected="true" disabled="true" owner="1" isTab="false" name="企业管理" descn="这是一个企业管理员" url="" />
<roleType type="企业操作员" selected="true" disabled="true" owner="3" isTab="false" name="企业操作员" descn="这是一个企业操作员" url="" />
<roleType type="企业管理" selected="false" disabled="true" owner="2" isTab="false" name="企业管理" descn="这是一个企业管理员,个人用户不能选择" url="" />
<roleType type="政府端" selected="false" disabled="false" owner="0,1,2,3" isTab="true" name="政府端" descn="这是一个政府端" url="view/report?viewlet=fanruan%252Fsso%252F%25E6%2594%25BF%25E5%25BA%259C%25E7%25AB%25AF%25E6%25B3%25A8%25E5%2586%258C%25E4%25BF%25A1%25E6%2581%25AF%25E7%2599%25BB%25E8%25AE%25B0%25E8%25A1%25A8.cpt&amp;op=write" />
<roleType type="大屏端" selected="false" disabled="false" owner="0,2" isTab="true" name="大屏端" descn="这是一个大屏端" url="/view/report?viewlet=fanruan%252Fsso%252F%25E5%25A4%25A7%25E5%25B1%258F%25E7%25AB%25AF%25E6%25B3%25A8%25E5%2586%258C%25E4%25BF%25A1%25E6%2581%25AF.cpt&amp;op=write" />
</root>

389
src/main/java/com/fr/plugin/sxka/sso/controller/SxKaController.java

@ -0,0 +1,389 @@
package com.fr.plugin.sxka.sso.controller;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import com.fr.base.PropertiesUtils;
import com.fr.decision.webservice.Response;
import com.fr.decision.webservice.annotation.LoginStatusChecker;
import com.fr.decision.webservice.bean.user.UserBean;
import com.fr.decision.webservice.utils.DecisionStatusService;
import com.fr.decision.webservice.utils.WebServiceUtils;
import com.fr.decision.webservice.v10.user.UserService;
import com.fr.json.JSONObject;
import com.fr.json.revise.EmbedJson;
import com.fr.locale.InterProviderFactory;
import com.fr.log.FineLoggerFactory;
import com.fr.plugin.sxka.sso.RoleDBAccessProvider;
import com.fr.plugin.sxka.sso.SsoFilter;
import com.fr.plugin.sxka.sso.beans.DecryptParamBean;
import com.fr.plugin.sxka.sso.beans.UserRoleTypeParamBean;
import com.fr.plugin.sxka.sso.beans.SxkaConfigBean;
import com.fr.plugin.sxka.sso.conf.RoleConfigBean;
import com.fr.plugin.sxka.sso.conf.RoleXmlConfigReader;
import com.fr.plugin.sxka.sso.dao.UserInfoDao;
import com.fr.plugin.sxka.sso.entity.FineLogRegisterEntity;
import com.fr.plugin.sxka.sso.entity.UserInfoEntity;
import com.fr.plugin.sxka.sso.entity.UserRoleTypeDBAUtil;
import com.fr.plugin.sxka.sso.entity.UserRoleTypeEntity;
import com.fr.plugin.sxka.sso.service.UserRoleTypeService;
import com.fr.security.encryption.transmission.TransmissionEncryptors;
import com.fr.stable.StringUtils;
import com.fr.stable.db.action.DBAction;
import com.fr.stable.db.dao.DAOContext;
import com.fr.stable.query.QueryFactory;
import com.fr.stable.query.condition.QueryCondition;
import com.fr.stable.query.restriction.RestrictionFactory;
import com.fr.third.fasterxml.jackson.databind.DeserializationFeature;
import com.fr.third.fasterxml.jackson.databind.ObjectMapper;
import com.fr.third.springframework.stereotype.Controller;
import com.fr.third.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;
@Controller
@LoginStatusChecker(
required = false //不需要验证是否登录
)
public class SxKaController {
@RequestMapping(
value = {"/sxka/getConfig"},
method = {RequestMethod.GET}
)
@ResponseBody
public Response getConfig(HttpServletRequest req, HttpServletResponse res) throws Exception {
SxkaConfigBean bean = new SxkaConfigBean();
String unavailableUrlPath = PropertiesUtils.getProperties("conf").getProperty("unavailable");
String unavailableUrlPath1 = PropertiesUtils.getProperties("conf").getProperty("unavailable1");
bean.setUnavailable(unavailableUrlPath);
bean.setUnavailable1(unavailableUrlPath1);
return Response.ok(bean);
}
/**
* 获取所有的角色类型
*
* @param req
* @param res
* @return
* @throws Exception
*/
@RequestMapping(
value = {"/sxka/getAllRoleTypeList"},
method = {RequestMethod.GET}
)
@ResponseBody
public Response getAllRoleTypeList(HttpServletRequest req, HttpServletResponse res) throws Exception {
List<RoleConfigBean> allRoleTypes = RoleXmlConfigReader.getInstance().roles;
return Response.ok(allRoleTypes);
}
/**
* 获取用户选择的权限列表
*
* @param req
* @param res
* @param userId
* @return
* @throws Exception
*/
@RequestMapping(
value = {"/sxka/getUserRoleTypeList"},
method = {RequestMethod.GET}
)
@ResponseBody
public Response getUserRoleTypeList(HttpServletRequest req, HttpServletResponse res, @RequestParam("userId") String userId) throws Exception {
FineLoggerFactory.getLogger().info("获取用户的权限类型列表:userId=" + userId);
List<UserRoleTypeEntity> userRoleTypeList = UserRoleTypeService.getInstance().getUserRoleTypeByUserId(userId);
return Response.ok(userRoleTypeList);
}
public static final String cKey = "eaassww34422**aa";
@RequestMapping(
value = {"/sxka/decryptParam"},
method = {RequestMethod.POST}
)
@ResponseBody
public Response decryptParam(HttpServletRequest req, HttpServletResponse res, @RequestBody DecryptParamBean decryptParamBean) throws Exception {
FineLoggerFactory.getLogger().info("解密 param=" + decryptParamBean.getDecryptParam());
String result = Decrypt(decryptParamBean.getDecryptParam(),cKey);
FineLoggerFactory.getLogger().info("解密结果=" + result);
return Response.ok(result);
}
public static String Decrypt(String sSrc, String sKey) throws Exception {
try {
// 判断Key是否正确
if (sKey == null) {
FineLoggerFactory.getLogger().info("Key为空null");
return null;
}
// 判断Key是否为16位
if (sKey.length() != 16) {
FineLoggerFactory.getLogger().info("Key长度不是16位");
return null;
}
byte[] raw = sKey.getBytes("utf-8");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] encrypted1 = Base64.getDecoder().decode(sSrc);//先用base64解密
try {
byte[] original = cipher.doFinal(encrypted1);
String originalString = new String(original,"utf-8");
return originalString;
} catch (Exception e) {
System.out.println(e.toString());
return null;
}
} catch (Exception ex) {
System.out.println(ex.toString());
return null;
}
}
/**
* 批量增加用户角色
*
* @param req
* @param res
* @param userRoleTypeParam
* @return
* @throws Exception
*/
@RequestMapping(
value = {"/sxka/addUserRoleTypes"},
method = {RequestMethod.POST}
)
@ResponseBody
public Response addUserRoleTypes(HttpServletRequest req, HttpServletResponse res, @RequestBody UserRoleTypeParamBean userRoleTypeParam) throws Exception {
FineLoggerFactory.getLogger().info("用户增加权限类型:userId=" + userRoleTypeParam.getUserId() + ",userRoleTypes=" + userRoleTypeParam.getUserRoleTypes()+",clientType="+userRoleTypeParam.getClientType()+",orgin="+userRoleTypeParam.getOrgin()+",accountType="+userRoleTypeParam.getAccountType());
addLoginUserAndUserInfo(userRoleTypeParam.getUserId());
//多个roleType用逗号隔开
UserRoleTypeService.getInstance().addUserRoleTypes(userRoleTypeParam.getUserId(), userRoleTypeParam.getUserRoleTypes());
//如果是企业管理员,直接可用
if (userRoleTypeParam.getAccountType() == 1) {
FineLoggerFactory.getLogger().info("企业管理员直接可用,不跳冻结界面");
if (StringUtils.isNotBlank(userRoleTypeParam.getOrgin())) {
return Response.ok(userRoleTypeParam.getOrgin());
}
else{
String unavailableUrlPath = PropertiesUtils.getProperties("conf").getProperty("unavailable1");
FineLoggerFactory.getLogger().info("unavailableUrlPath:" + unavailableUrlPath);
// res.sendRedirect(unavailableUrlPath);
return Response.ok(unavailableUrlPath);
}
}
//查看是否有需要审批的权限
List<RoleConfigBean> roles = RoleXmlConfigReader.getInstance().roles;
boolean isAudit = false;
for (RoleConfigBean config : roles) {
boolean isoK1 = config.getOwner().indexOf("" + userRoleTypeParam.getAccountType()) != -1;
boolean isoK2 = config.isAudit() == true;
boolean isoK3 = userRoleTypeParam.getUserRoleTypes().indexOf(config.getRoleType()) != -1;
if (isoK1 && isoK2 && isoK3) {
isAudit = true;
}
}
FineLoggerFactory.getLogger().info("isAudit:" + isAudit);
if (isAudit == true) {
FineLoggerFactory.getLogger().info("clientType:" + userRoleTypeParam.getClientType());
if ("1".equals(userRoleTypeParam.getClientType())) {
String unavailableUrlPath = PropertiesUtils.getProperties("conf").getProperty("unavailable");
;
//res.sendRedirect(unavailableUrlPath);
return Response.ok(unavailableUrlPath);
} else {
String unavailableUrlPath = PropertiesUtils.getProperties("conf").getProperty("unavailable1");
FineLoggerFactory.getLogger().info("unavailableUrlPath:" + unavailableUrlPath);
// res.sendRedirect(unavailableUrlPath);
return Response.ok(unavailableUrlPath);
}
// SsoFilter.setError(res, userRoleTypeParam.getUserId());//需要审核
} else {
if (StringUtils.isNotBlank(userRoleTypeParam.getOrgin())) {
return Response.ok(userRoleTypeParam.getOrgin());
}
}
return Response.ok("ok");
}
@RequestMapping(
value = {"/sxka/deleteAllRoleType"},
method = {RequestMethod.GET}
)
@ResponseBody
public Response deleteAllRoleType(HttpServletRequest req, HttpServletResponse res) throws Exception {
UserRoleTypeDBAUtil.getInstance().deleteAllEntity();
return Response.ok("ok");
}
@RequestMapping(
value = {"/sxka/getAllUsers"},
method = {RequestMethod.GET}
)
@ResponseBody
public Response getAllUserInfo(HttpServletRequest req, HttpServletResponse res) throws Exception {
List<UserInfoEntity> allUsers = RoleDBAccessProvider.getDbAccessor().runDMLAction(new DBAction<List<UserInfoEntity>>() {
@Override
public List<UserInfoEntity> run(DAOContext daoContext) throws Exception {
UserInfoDao dao = daoContext.getDAO(UserInfoDao.class);
QueryCondition condition = QueryFactory.create();
return dao.find(condition);
}
});
return Response.ok(allUsers);
}
@RequestMapping(
value = {"/sxka/deleteAllUsers"},
method = {RequestMethod.GET}
)
@ResponseBody
public Response deleteAllUsers(HttpServletRequest req, HttpServletResponse res) throws Exception {
List<UserInfoEntity> allUsers = RoleDBAccessProvider.getDbAccessor().runDMLAction(new DBAction<List<UserInfoEntity>>() {
@Override
public List<UserInfoEntity> run(DAOContext daoContext) throws Exception {
UserInfoDao dao = daoContext.getDAO(UserInfoDao.class);
QueryCondition condition = QueryFactory.create();
List<UserInfoEntity> allEntitys = dao.find(condition);
for(UserInfoEntity entity:allEntitys){
QueryCondition deleteCondition = QueryFactory.create();
deleteCondition.addRestriction(RestrictionFactory.eq("id",entity.getId()));
dao.remove(deleteCondition);
}
return null;
}
});
return Response.ok(allUsers);
}
@RequestMapping(
value = {"/sxka/initUserInfo"},
method = {RequestMethod.GET}
)
@ResponseBody
public Response initUserInfo(HttpServletRequest req, HttpServletResponse res, @RequestParam("userId") String userId) throws Exception {
FineLoggerFactory.getLogger().info("/sxka/initUserInfo user info:userId=" + userId);
addLoginUserAndUserInfo(userId);
return Response.ok("ok");
}
public static final String DATE_FORMAT_YMDHMS = "yyyy-MM-dd HH:mm:ss";
private static final SimpleDateFormat YMDHMSFormater = new SimpleDateFormat(DATE_FORMAT_YMDHMS);
private void addLoginUserAndUserInfo(String userId) throws Exception {
FineLoggerFactory.getLogger().info("从缓存里取:key:"+userId);
JSONObject userProfile = DecisionStatusService.loginStatusService().get(userId);
if(userProfile != null){
FineLoggerFactory.getLogger().info("从缓存里取到了:"+userProfile);
if (!SsoFilter.existUser(userProfile.getString("id"))){
FineLoggerFactory.getLogger().info("如果决策系统不存在id属性值的用户,那么默认在决策系统中加上这个人");
UserBean userBean = new UserBean();
userBean.setUsername(userProfile.getString("id"));
userBean.setRealName(userProfile.getString("op_name"));
userBean.setEnable(true);
userBean.setPassword(TransmissionEncryptors.getInstance().encrypt(UUID.randomUUID().toString()));
UserService.getInstance().addUser(userBean);
FineLoggerFactory.getLogger().info("增加新用户:"+userProfile.getString("id"));
}
ObjectMapper mapper = EmbedJson.MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
UserInfoEntity entity = mapper.convertValue(userProfile, UserInfoEntity.class);
final boolean[] isAdd= {false,false};
try {
RoleDBAccessProvider.getDbAccessor().runDMLAction(new DBAction<UserInfoEntity>() {
@Override
public UserInfoEntity run(DAOContext daoContext) throws Exception {
UserInfoDao dao = daoContext.getDAO(UserInfoDao.class);
//查询数据库是否存在该id对应的数据
UserInfoEntity byId = dao.getById(entity.getId());
if (byId != null) {//如果存在,更新下
entity.setStatus(byId.getStatus());
entity.setAccount_type(byId.getAccount_type());
entity.setRegistryDate(byId.getRegistryDate());
FineLoggerFactory.getLogger().info("外置表里有这个用户,这里更新");
} else {//如果不存在,将状态置为false
FineLoggerFactory.getLogger().info("外置表里没这个用户,这里增加");
entity.setStatus("false");
entity.setRegistryDate(new Date());
if(entity.getAccount_type().equals("1")){
isAdd[0] = true;
entity.setStatus("true");
}
if(entity.getAccount_type().equals("3")){
isAdd[1] = true;
}
}
//更新或者添加
dao.addOrUpdate(entity);
return entity;
}
});
if( isAdd[0] == true){
UserRoleTypeService.getInstance().addUserRoleTypes(entity.getId(), "企业管理员");
SsoFilter.addRole(entity.getId(),"企业管理员");
//增加企业管理员日志
addRegisteLog(entity,"1");
}
if(isAdd[1] == true){
UserRoleTypeService.getInstance().addUserRoleTypes(entity.getId(), "企业操作员");
SsoFilter.addRole(entity.getId(),"企业操作员");
//增加企业操作员日志
addRegisteLog(entity,"3");
}
} catch (Exception e) {
FineLoggerFactory.getLogger().error(e.getMessage(), e);
}
DecisionStatusService.loginStatusService().delete(userId);
FineLoggerFactory.getLogger().info("从缓存里delete:key:"+userId);
}
}
public static void addRegisteLog(UserInfoEntity entity,String type){
FineLogRegisterEntity logEntity = new FineLogRegisterEntity();
logEntity.setGs_name(entity.getGs_name());
logEntity.setGs_social_credit_code(entity.getGs_social_credit_code());
logEntity.setType(type);
logEntity.setUser_id(entity.getId());
logEntity.setOp_name(entity.getOp_name());
Date date = new Date();
String datef = YMDHMSFormater.format(date);
logEntity.setLog_time(datef);
if(type.equals("3")){
logEntity.setAction("企业操作员注册");
}if(type.equals("1")){
logEntity.setAction("企业管理员注册");
}
logEntity.setExecutor_gs_name(logEntity.getGs_name());
logEntity.setExecutor_gs_social_credit_code(logEntity.getGs_social_credit_code());
logEntity.setExecutor(logEntity.getUser_id());
logEntity.setExecutor_name(logEntity.getOp_name());
UserRoleTypeDBAUtil.getInstance().addFineLogRegiste(logEntity);
}
}

12
src/main/java/com/fr/plugin/sxka/sso/controller/SxKaControllerProvider.java

@ -0,0 +1,12 @@
package com.fr.plugin.sxka.sso.controller;
import com.fr.decision.fun.impl.AbstractControllerRegisterProvider;
public class SxKaControllerProvider extends AbstractControllerRegisterProvider {
@Override
public Class<?>[] getControllers() {
return new Class[]{
SxKaController.class
};
}
}

41
src/main/java/com/fr/plugin/sxka/sso/dao/FineLogRegisterDao.java

@ -0,0 +1,41 @@
package com.fr.plugin.sxka.sso.dao;
import com.fr.plugin.sxka.sso.entity.FineLogRegisterEntity;
import com.fr.plugin.sxka.sso.entity.UserRoleTypeEntity;
import com.fr.stable.db.dao.BaseDAO;
import com.fr.stable.db.dao.DAOProvider;
import com.fr.stable.db.session.DAOSession;
import java.util.UUID;
public class FineLogRegisterDao extends BaseDAO<FineLogRegisterEntity>{
public FineLogRegisterDao(DAOSession daoSession) {
super(daoSession);
}
public void addEntity(FineLogRegisterEntity entity) throws Exception {
if(entity.getId()==null){
entity.setId(UUID.randomUUID().toString());
}
getSession().persist(entity);
}
@Override
protected Class<FineLogRegisterEntity> getEntityClass() {
return FineLogRegisterEntity.class;
}
public final static DAOProvider DAO = new DAOProvider() {
@Override
public Class getEntityClass() {
return FineLogRegisterEntity.class;
}
@Override
public Class<? extends BaseDAO> getDAOClass() {
return FineLogRegisterDao.class;
}
};
}

21
src/main/java/com/fr/plugin/sxka/sso/dao/UserInfoDao.java

@ -0,0 +1,21 @@
package com.fr.plugin.sxka.sso.dao;
import com.fr.plugin.sxka.sso.entity.UserInfoEntity;
import com.fr.stable.db.dao.BaseDAO;
import com.fr.stable.db.session.DAOSession;
/**
* @Author hujian
* @Date 2021/5/17
* @Description
**/
public class UserInfoDao extends BaseDAO<UserInfoEntity> {
public UserInfoDao(DAOSession daoSession) {
super(daoSession);
}
@Override
protected Class<UserInfoEntity> getEntityClass() {
return UserInfoEntity.class;
}
}

78
src/main/java/com/fr/plugin/sxka/sso/dao/UserRoleTypeDao.java

@ -0,0 +1,78 @@
package com.fr.plugin.sxka.sso.dao;
import com.fr.log.FineLoggerFactory;
import com.fr.plugin.sxka.sso.entity.UserRoleTypeEntity;
import com.fr.stable.db.dao.BaseDAO;
import com.fr.stable.db.dao.DAOProvider;
import com.fr.stable.db.session.DAOSession;
import com.fr.stable.query.QueryFactory;
import com.fr.stable.query.condition.QueryCondition;
import com.fr.stable.query.restriction.RestrictionFactory;
import java.util.List;
import java.util.UUID;
public class UserRoleTypeDao extends BaseDAO<UserRoleTypeEntity> {
public UserRoleTypeDao(DAOSession daoSession) {
super(daoSession);
}
public void addEntity(UserRoleTypeEntity entity) throws Exception {
List<UserRoleTypeEntity> list = getEntitiesByUserIdAndRoleCode(entity.getUserId(),entity.getRoleCode());
if(list.size() == 0){
if(entity.getId()==null){
entity.setId(UUID.randomUUID().toString());
}
getSession().persist(entity);
FineLoggerFactory.getLogger().info("userId:"+entity.getUserId()+",roleCode:"+entity.getRoleCode()+"插入");
}
else{
FineLoggerFactory.getLogger().info("userId:"+entity.getUserId()+",roleCode:"+entity.getRoleCode()+"已经存在");
}
}
public List<UserRoleTypeEntity> getEntitiesByUserIdAndRoleCode(String userId,String roleCode) throws Exception {
QueryCondition condition = QueryFactory.create();
condition.addRestriction(RestrictionFactory.eq("userId",userId));
condition.addRestriction(RestrictionFactory.eq("roleCode",roleCode));
return getSession().find(condition,getEntityClass());
}
public List<UserRoleTypeEntity> getEntitiesByUserId(String userId) throws Exception {
QueryCondition condition = QueryFactory.create();
condition.addRestriction(RestrictionFactory.eq("userId",userId));
return getSession().find(condition,getEntityClass());
}
public void deleteUserRoleTypeByUserId(String userId) throws Exception {
List<UserRoleTypeEntity> userRoleTypeList = getEntitiesByUserId(userId);
for(UserRoleTypeEntity entity:userRoleTypeList){
getSession().remove(QueryFactory.create().addRestriction(RestrictionFactory.eq("id",entity.getId())),getEntityClass());
}
}
public void deleteAllEntity() throws Exception {
QueryCondition condition = QueryFactory.create();
List<UserRoleTypeEntity> entitys = getSession().find(condition,getEntityClass());
for(UserRoleTypeEntity entity:entitys){
getSession().remove(QueryFactory.create().addRestriction(RestrictionFactory.eq("id",entity.getId())),getEntityClass());
}
}
@Override
protected Class<UserRoleTypeEntity> getEntityClass() {
return UserRoleTypeEntity.class;
}
public final static DAOProvider DAO = new DAOProvider() {
@Override
public Class getEntityClass() {
return UserRoleTypeEntity.class;
}
@Override
public Class<? extends BaseDAO> getDAOClass() {
return UserRoleTypeDao.class;
}
};
}

132
src/main/java/com/fr/plugin/sxka/sso/entity/FineLogRegisterEntity.java

@ -0,0 +1,132 @@
package com.fr.plugin.sxka.sso.entity;
import com.fr.stable.db.entity.BaseEntity;
import com.fr.third.javax.persistence.Column;
import com.fr.third.javax.persistence.Entity;
import com.fr.third.javax.persistence.Table;
@Entity
@Table(name = "fine_log_register_company")
public class FineLogRegisterEntity extends BaseEntity {
@Column(name = "gs_name")
private String gs_name;
@Column(name = "gs_social_credit_code")
private String gs_social_credit_code;
@Column(name = "type")
private String type;
@Column(name = "user_id")
private String user_id;
@Column(name = "op_name")
private String op_name;
@Column(name = "action")
private String action;
@Column(name = "log_time")
private String log_time;
@Column(name = "executor_gs_name")
private String executor_gs_name;
@Column(name = "executor_gs_social_credit_code")
private String executor_gs_social_credit_code;
@Column(name = "executor")
private String executor;
@Column(name = "executor_name")
private String executor_name;
public String getGs_name() {
return gs_name;
}
public void setGs_name(String gs_name) {
this.gs_name = gs_name;
}
public String getGs_social_credit_code() {
return gs_social_credit_code;
}
public void setGs_social_credit_code(String gs_social_credit_code) {
this.gs_social_credit_code = gs_social_credit_code;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getUser_id() {
return user_id;
}
public void setUser_id(String user_id) {
this.user_id = user_id;
}
public String getOp_name() {
return op_name;
}
public void setOp_name(String op_name) {
this.op_name = op_name;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
public String getLog_time() {
return log_time;
}
public void setLog_time(String log_time) {
this.log_time = log_time;
}
public String getExecutor_gs_name() {
return executor_gs_name;
}
public void setExecutor_gs_name(String executor_gs_name) {
this.executor_gs_name = executor_gs_name;
}
public String getExecutor_gs_social_credit_code() {
return executor_gs_social_credit_code;
}
public void setExecutor_gs_social_credit_code(String executor_gs_social_credit_code) {
this.executor_gs_social_credit_code = executor_gs_social_credit_code;
}
public String getExecutor() {
return executor;
}
public void setExecutor(String executor) {
this.executor = executor;
}
public String getExecutor_name() {
return executor_name;
}
public void setExecutor_name(String executor_name) {
this.executor_name = executor_name;
}
}

310
src/main/java/com/fr/plugin/sxka/sso/entity/UserInfoEntity.java

@ -0,0 +1,310 @@
package com.fr.plugin.sxka.sso.entity;
import com.fr.stable.db.entity.BaseEntity;
import com.fr.third.javax.persistence.Column;
import com.fr.third.javax.persistence.Entity;
import com.fr.third.javax.persistence.Table;
import java.util.Date;
/**
* @Author fr.open
* @Date 2021/5/13
* @Description
**/
@Entity
@Table(name = "plugin_sxka_user_info")
public class UserInfoEntity extends BaseEntity {
private static final long serialVersionUID = 5278704449983309952L;
@Column(name = "op_name")
private String op_name;
@Column(name = "organization")
private String organization;
@Column(name = "account_type")
private String account_type;
@Column(name = "login_type")
private String login_type;
@Column(name = "gs_name")
private String gs_name;
@Column(name = "gs_name_en")
private String gs_name_en;
@Column(name = "gs_type")
private String gs_type;
@Column(name = "gs_address")
private String gs_address;
@Column(name = "gs_address_en")
private String gs_address_en;
@Column(name = "gs_tax_code")
private String gs_tax_code;
@Column(name = "gs_expires")
private String gs_expires;
@Column(name = "gs_postcode")
private String gs_postcode;
@Column(name = "gs_scope")
private String gs_scope;
@Column(name = "gs_status")
private String gs_status;
@Column(name = "gs_regcap")
private String gs_regcap;
@Column(name = "gs_regcap_cur")
private String gs_regcap_cur;
@Column(name = "gs_social_credit_code")
private String gs_social_credit_code;
@Column(name = "gs_code")
private String gs_code;
@Column(name = "gs_regorg")
private String gs_regorg;
@Column(name = "gs_reg_number")
private String gs_reg_number;
@Column(name = "gs_location")
private String gs_location;
@Column(name = "cus_number")
private String cus_number;
@Column(name = "cus_expires")
private String cus_expires;
@Column(name = "cus_master")
private String cus_master;
@Column(name = "status")
private String status;
@Column(name = "registry_date")
private Date registryDate;
public Date getRegistryDate() {
return registryDate;
}
public void setRegistryDate(Date registryDate) {
this.registryDate = registryDate;
}
public static long getSerialVersionUID() {
return serialVersionUID;
}
public String getOp_name() {
return op_name;
}
public void setOp_name(String op_name) {
this.op_name = op_name;
}
public String getOrganization() {
return organization;
}
public void setOrganization(String organization) {
this.organization = organization;
}
public String getAccount_type() {
return account_type;
}
public void setAccount_type(String account_type) {
this.account_type = account_type;
}
public String getLogin_type() {
return login_type;
}
public void setLogin_type(String login_type) {
this.login_type = login_type;
}
public String getGs_name() {
return gs_name;
}
public void setGs_name(String gs_name) {
this.gs_name = gs_name;
}
public String getGs_name_en() {
return gs_name_en;
}
public void setGs_name_en(String gs_name_en) {
this.gs_name_en = gs_name_en;
}
public String getGs_type() {
return gs_type;
}
public void setGs_type(String gs_type) {
this.gs_type = gs_type;
}
public String getGs_address() {
return gs_address;
}
public void setGs_address(String gs_address) {
this.gs_address = gs_address;
}
public String getGs_address_en() {
return gs_address_en;
}
public void setGs_address_en(String gs_address_en) {
this.gs_address_en = gs_address_en;
}
public String getGs_tax_code() {
return gs_tax_code;
}
public void setGs_tax_code(String gs_tax_code) {
this.gs_tax_code = gs_tax_code;
}
public String getGs_expires() {
return gs_expires;
}
public void setGs_expires(String gs_expires) {
this.gs_expires = gs_expires;
}
public String getGs_postcode() {
return gs_postcode;
}
public void setGs_postcode(String gs_postcode) {
this.gs_postcode = gs_postcode;
}
public String getGs_scope() {
return gs_scope;
}
public void setGs_scope(String gs_scope) {
this.gs_scope = gs_scope;
}
public String getGs_status() {
return gs_status;
}
public void setGs_status(String gs_status) {
this.gs_status = gs_status;
}
public String getGs_regcap() {
return gs_regcap;
}
public void setGs_regcap(String gs_regcap) {
this.gs_regcap = gs_regcap;
}
public String getGs_regcap_cur() {
return gs_regcap_cur;
}
public void setGs_regcap_cur(String gs_regcap_cur) {
this.gs_regcap_cur = gs_regcap_cur;
}
public String getGs_social_credit_code() {
return gs_social_credit_code;
}
public void setGs_social_credit_code(String gs_social_credit_code) {
this.gs_social_credit_code = gs_social_credit_code;
}
public String getGs_code() {
return gs_code;
}
public void setGs_code(String gs_code) {
this.gs_code = gs_code;
}
public String getGs_regorg() {
return gs_regorg;
}
public void setGs_regorg(String gs_regorg) {
this.gs_regorg = gs_regorg;
}
public String getGs_reg_number() {
return gs_reg_number;
}
public void setGs_reg_number(String gs_reg_number) {
this.gs_reg_number = gs_reg_number;
}
public String getGs_location() {
return gs_location;
}
public void setGs_location(String gs_location) {
this.gs_location = gs_location;
}
public String getCus_number() {
return cus_number;
}
public void setCus_number(String cus_number) {
this.cus_number = cus_number;
}
public String getCus_expires() {
return cus_expires;
}
public void setCus_expires(String cus_expires) {
this.cus_expires = cus_expires;
}
public String getCus_master() {
return cus_master;
}
public void setCus_master(String cus_master) {
this.cus_master = cus_master;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}

108
src/main/java/com/fr/plugin/sxka/sso/entity/UserRoleTypeDBAUtil.java

@ -0,0 +1,108 @@
package com.fr.plugin.sxka.sso.entity;
import com.fr.log.FineLoggerFactory;
import com.fr.plugin.sxka.sso.RoleDBAccessProvider;
import com.fr.plugin.sxka.sso.dao.FineLogRegisterDao;
import com.fr.plugin.sxka.sso.dao.UserRoleTypeDao;
import com.fr.stable.db.action.DBAction;
import com.fr.stable.db.dao.DAOContext;
import java.util.ArrayList;
import java.util.List;
public class UserRoleTypeDBAUtil {
private static UserRoleTypeDBAUtil instance;
public static UserRoleTypeDBAUtil getInstance(){
if(instance == null){
instance = new UserRoleTypeDBAUtil();
}
return instance;
}
public void addFineLogRegiste(FineLogRegisterEntity entity){
try{
RoleDBAccessProvider.getDbAccessor().runDMLAction(new DBAction<UserRoleTypeEntity>() {
@Override
public UserRoleTypeEntity run(DAOContext daoContext) throws Exception {
daoContext.getDAO(FineLogRegisterDao.class).addEntity(entity);
FineLoggerFactory.getLogger().info("增加日志成功.....");
return null;
}
});
}
catch(Exception ex){
FineLoggerFactory.getLogger().info("增加日志失败.....");
ex.printStackTrace();
}
}
public void addUserRoleType(UserRoleTypeEntity entity){
try{
RoleDBAccessProvider.getDbAccessor().runDMLAction(new DBAction<UserRoleTypeEntity>() {
@Override
public UserRoleTypeEntity run(DAOContext daoContext) throws Exception {
daoContext.getDAO(UserRoleTypeDao.class).addEntity(entity);
return null;
}
});
}
catch(Exception ex){
ex.printStackTrace();
}
}
public List<UserRoleTypeEntity> getUserRoleTypeByUserId(String userId){
try{
List<UserRoleTypeEntity> entities = RoleDBAccessProvider.getDbAccessor().runQueryAction(new DBAction<List<UserRoleTypeEntity>>() {
@Override
public List<UserRoleTypeEntity> run(DAOContext daoContext) throws Exception {
return daoContext.getDAO(UserRoleTypeDao.class).getEntitiesByUserId(userId);
}
});
return entities;
}
catch(Exception ex){
ex.printStackTrace();
return new ArrayList<>();
}
}
public void deleteUserRoleTypeByUserId(String userId) throws Exception {
try{
RoleDBAccessProvider.getDbAccessor().runDMLAction(new DBAction<UserRoleTypeEntity>() {
@Override
public UserRoleTypeEntity run(DAOContext daoContext) throws Exception {
daoContext.getDAO(UserRoleTypeDao.class).deleteUserRoleTypeByUserId(userId);
return null;
}
});
}
catch(Exception ex){
ex.printStackTrace();
}
}
public void deleteAllEntity() throws Exception {
try{
RoleDBAccessProvider.getDbAccessor().runDMLAction(new DBAction<UserRoleTypeEntity>() {
@Override
public UserRoleTypeEntity run(DAOContext daoContext) throws Exception {
daoContext.getDAO(UserRoleTypeDao.class).deleteAllEntity();
return null;
}
});
}
catch(Exception ex){
ex.printStackTrace();
}
}
}

45
src/main/java/com/fr/plugin/sxka/sso/entity/UserRoleTypeEntity.java

@ -0,0 +1,45 @@
package com.fr.plugin.sxka.sso.entity;
import com.fr.stable.db.entity.BaseEntity;
import com.fr.third.javax.persistence.Column;
import com.fr.third.javax.persistence.Entity;
import com.fr.third.javax.persistence.Table;
@Entity
@Table(name = "plugin_sxka_user_role_type")
public class UserRoleTypeEntity extends BaseEntity {
@Column(name = "userId")
private String userId;
@Column(name = "roleType")
private String roleType;
@Column(name = "roleCode")
private String roleCode;
public String getRoleCode() {
return roleCode;
}
public void setRoleCode(String roleCode) {
this.roleCode = roleCode;
}
public void setUserId(String userId) {
this.userId = userId;
}
public void setRoleType(String roleType) {
this.roleType = roleType;
}
public String getUserId() {
return userId;
}
public String getRoleType() {
return roleType;
}
}

54
src/main/java/com/fr/plugin/sxka/sso/js/FileDef.java

@ -0,0 +1,54 @@
package com.fr.plugin.sxka.sso.js;
import com.fr.plugin.transform.ExecuteFunctionRecord;
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;
/**
* @author fr.open
* @date 2021/8/12
*/
public class FileDef extends Component {
public static final FileDef KEY = new FileDef();
private FileDef(){}
/**
* 返回需要引入的JS脚本路径
* @param client 请求客户端描述
* @return JS脚本路径
*/
@Override
public ScriptPath script(RequestClient client ) {
//如果不需要就直接返回 ScriptPath.EMPTY
return ScriptPath.build("com/fr/plugin/sxka/sso/theme.js");
}
/**
* 返回需要引入的CSS样式路径
* @param client 请求客户端描述
* @return CSS样式路径
*/
@Override
public StylePath style(RequestClient client ) {
//如果不需要就直接返回 StylePath.EMPTY;
return StylePath.EMPTY;
}
/**
* 通过给定的资源过滤器控制是否加载这个资源
* @return 资源过滤器
*/
@ExecuteFunctionRecord
@Override
public Filter filter() {
return new Filter(){
@Override
public boolean accept() {
//任何情况下我们都在平台组件加载时加载我们的组件
return true;
}
};
}
}

25
src/main/java/com/fr/plugin/sxka/sso/js/JSCSSBridge.java

@ -0,0 +1,25 @@
package com.fr.plugin.sxka.sso.js;
import com.fr.decision.fun.impl.AbstractWebResourceProvider;
import com.fr.decision.web.MainComponent;
import com.fr.plugin.transform.FunctionRecorder;
import com.fr.web.struct.Atom;
/**
* @author fr.open
* @date 2021/8/12
*/
@FunctionRecorder
public class JSCSSBridge extends AbstractWebResourceProvider {
@Override
public Atom attach() {
//在平台主组件加载时添加我们自己的组件
return MainComponent.KEY;
}
@Override
public Atom client() {
//我们自己要引入的组件
return FileDef.KEY;
}
}

57
src/main/java/com/fr/plugin/sxka/sso/service/UserRoleTypeService.java

@ -0,0 +1,57 @@
package com.fr.plugin.sxka.sso.service;
import com.fr.log.FineLoggerFactory;
import com.fr.plugin.sxka.sso.conf.RoleXmlConfigReader;
import com.fr.plugin.sxka.sso.entity.UserRoleTypeDBAUtil;
import com.fr.plugin.sxka.sso.entity.UserRoleTypeEntity;
import java.util.List;
import java.util.UUID;
public class UserRoleTypeService {
private static UserRoleTypeService instance;
public static UserRoleTypeService getInstance(){
if(instance == null){
instance = new UserRoleTypeService();
}
return instance;
}
public synchronized void addUserRoleTypes(String userId,String userRoleTypes) throws Exception {
//先删除所有
deleteUserRoleTypeByUserId(userId);
FineLoggerFactory.getLogger().info("先删除用户的权限:"+Thread.currentThread().getName());
//多个roleType用逗号隔开
String[] roleTypeArr = userRoleTypes.split(",");
// String[] roleCodeArr = roleCodes.split(",");
int index = 0;
for(String roleType:roleTypeArr){
UserRoleTypeEntity entity = new UserRoleTypeEntity();
entity.setId(UUID.randomUUID().toString());
entity.setRoleType(roleType);
entity.setUserId(userId);
String addRoleCode = RoleXmlConfigReader.getInstance().getRoleCodeByName(roleType);
entity.setRoleCode(addRoleCode);
FineLoggerFactory.getLogger().info("增加角色,roleType:"+roleType+",roleCode:"+addRoleCode+",userId:"+userId+",threadName:"+Thread.currentThread().getName());
addUserRoleType(entity);
index++;
}
}
public void addUserRoleType(UserRoleTypeEntity entity){
if(entity.getId() == null || "".equals(entity.getId())){
entity.setId(UUID.randomUUID().toString());
}
UserRoleTypeDBAUtil.getInstance().addUserRoleType(entity);
}
public List<UserRoleTypeEntity> getUserRoleTypeByUserId(String userId){
return UserRoleTypeDBAUtil.getInstance().getUserRoleTypeByUserId(userId);
}
public void deleteUserRoleTypeByUserId(String userId) throws Exception {
UserRoleTypeDBAUtil.getInstance().deleteUserRoleTypeByUserId(userId);
}
}

1
src/main/resources/com/fr/plugin/sxka/sso/registe/css/app.24a019f4.css

File diff suppressed because one or more lines are too long

1
src/main/resources/com/fr/plugin/sxka/sso/registe/css/chunk-vendors.a16c4353.css

File diff suppressed because one or more lines are too long

BIN
src/main/resources/com/fr/plugin/sxka/sso/registe/favicon.ico

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

BIN
src/main/resources/com/fr/plugin/sxka/sso/registe/fonts/element-icons.535877f5.woff

Binary file not shown.

BIN
src/main/resources/com/fr/plugin/sxka/sso/registe/fonts/element-icons.732389de.ttf

Binary file not shown.

25
src/main/resources/com/fr/plugin/sxka/sso/registe/index.html

@ -0,0 +1,25 @@
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="icon" href="/favicon.ico">
<title>用户注册</title>
<link href="/webroot/decision/file?path=com/fr/plugin/sxka/sso/registe/css/app.24a019f4.css" rel="preload" as="style">
<link href="/webroot/decision/file?path=com/fr/plugin/sxka/sso/registe/css/chunk-vendors.a16c4353.css" rel="preload" as="style">
<link href="/webroot/decision/file?path=com/fr/plugin/sxka/sso/registe/js/app.6d7e7596.js" rel="preload" as="script">
<link href="/webroot/decision/file?path=com/fr/plugin/sxka/sso/registe/js/chunk-vendors.98ebceb7.js" rel="preload" as="script">
<link href="/webroot/decision/file?path=com/fr/plugin/sxka/sso/registe/css/chunk-vendors.a16c4353.css" rel="stylesheet">
<link href="/webroot/decision/file?path=com/fr/plugin/sxka/sso/registe/css/app.24a019f4.css" rel="stylesheet">
</head>
<body style="background-color: #bdd7ee;"><noscript><strong>We're sorry but role_manage doesn't work properly without
JavaScript enabled. Please enable it to continue.</strong></noscript>
<div id="app"></div>
<script src="/webroot/decision/file?path=com/fr/plugin/sxka/sso/registe/js/chunk-vendors.98ebceb7.js"></script>
<script src="/webroot/decision/file?path=com/fr/plugin/sxka/sso/registe/js/app.6d7e7596.js"></script>
</body>
</html>

2
src/main/resources/com/fr/plugin/sxka/sso/registe/js/app.6d7e7596.js

File diff suppressed because one or more lines are too long

1
src/main/resources/com/fr/plugin/sxka/sso/registe/js/app.6d7e7596.js.map

File diff suppressed because one or more lines are too long

47
src/main/resources/com/fr/plugin/sxka/sso/registe/js/chunk-vendors.98ebceb7.js

File diff suppressed because one or more lines are too long

1
src/main/resources/com/fr/plugin/sxka/sso/registe/js/chunk-vendors.98ebceb7.js.map

File diff suppressed because one or more lines are too long

5
src/main/resources/com/fr/plugin/sxka/sso/theme.js

@ -0,0 +1,5 @@
!(function () {
BI.Plugin.registerObject("dec.user.account.setting.real_name", function (widget) {
widget.element.prev().hide()
})
}());

23
src/main/resources/conf.properties

@ -0,0 +1,23 @@
#\u5355\u70B9\u767B\u5F55\u7EDF\u4E00\u5730\u5740
auth_url=https://www.singlewindow.shaanxi.cn/oauth/authorize
#\u83B7\u53D6tokan\u5730\u5740
token_url=https://www.singlewindow.shaanxi.cn/oauth/token
#\u83B7\u53D6\u7528\u6237\u4FE1\u606F\u63A5\u53E3
user_url=https://www.singlewindow.shaanxi.cn/resource/user
#client_id
client_id=125d5ff7-a40a-11eb-8e31-005056826ea5
#client_secret
client_secret=93badcc315cf94843040c2d9f254094f6eb71e0f
#\u767B\u51FA\u540E\u8DF3\u8F6C\u5730\u5740
logout=https://www.singlewindow.shaanxi.cn/oauth/logout
##\u56DE\u8C03\u5730\u5740
redirect_uri=http://locahost:8075/webroot/decision
logout_redirect_uri=http://locahost:8075/webroot/decision
##\u586B\u62A5\u5730\u5740
write_report=
##\u65E0\u6743\u9650\u5730\u5740
unavailable=http://localhost:8075/webroot/decision/view/report?viewlet=GettingStarted.cpt
unavailable1=http://localhost:8075/webroot/decision/view/report?viewlet=GettingStarted.cpt
##\u653E\u884C\u76EE\u5F55
whiteList=fr/test

BIN
插件交接文档.docx

Binary file not shown.
Loading…
Cancel
Save