Commit 36ae69dc authored by 胡文斌's avatar 胡文斌

使用公共包方法

parent ea7930fa
......@@ -126,6 +126,11 @@
<artifactId>jfinal</artifactId>
<version>${jfinal.version}</version>
</dependency>
<dependency>
<groupId>com.archser</groupId>
<artifactId>archser-commons</artifactId>
<version>1.2.2</version>
</dependency>
<!-- 东方通依赖 -->
<!-- <dependency>
<groupId>io.swagger</groupId>
......
package com.archser.aserver.common.config;
import com.alibaba.druid.filter.logging.Log4jFilter;
import com.alibaba.druid.filter.logging.LogFilter;
import com.alibaba.druid.filter.stat.StatFilter;
import com.archser.aserver.common.config.plugins.DBUpgrade;
import com.archser.aserver.common.config.plugins.RedisConfig;
import com.archser.aserver.controller.*;
import com.archser.aserver.interceptor.JwtInterceptor;
import com.archser.aserver.itask.GoodSync;
import com.archser.aserver.model._MappingKit;
import com.archser.aserver.util.SharedDisk;
import com.archser.aserver.websocket.MessageWebSocket;
import com.archser.commons.AppStartConfig;
import com.archser.plugin.redis.RedisConfig;
import com.jfinal.config.*;
import com.jfinal.ext.handler.RequestHandler;
import com.jfinal.ext.handler.UrlSkipHandler;
import com.jfinal.ext.proxy.CglibProxyFactory;
import com.jfinal.json.MixedJsonFactory;
import com.jfinal.kit.Kv;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.CaseInsensitiveContainerFactory;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.dialect.*;
import com.jfinal.plugin.activerecord.dialect.DialectFactory;
import com.jfinal.plugin.cron4j.Cron4jPlugin;
import com.jfinal.plugin.druid.DruidPlugin;
import com.jfinal.plugin.druid.RecordSqlFilter;
......@@ -32,6 +27,7 @@ import com.jfinal.render.ViewType;
import com.jfinal.server.undertow.UndertowServer;
import com.jfinal.server.undertow.WebBuilder;
import com.jfinal.template.Engine;
import java.io.File;
public class MainConfig extends JFinalConfig {
......@@ -181,12 +177,13 @@ public class MainConfig extends JFinalConfig {
/******** 在此添加数据库 表-Model 映射 *********/
// 如果使用了JFinal Model 生成器 生成了BaseModel 把下面注释解开即可
_MappingKit.mapping(arp);
AppStartConfig.configActiveRecordPlugin(arp);
// 添加到插件列表中
me.add(dbPlugin);
me.add(arp);
// 配置Redis信息,自动判断单实例和集群并加入JFinal插件列表
new RedisConfig(me, p);
new RedisConfig(me);
// 添加定时任务
me.add(new Cron4jPlugin(PropKit.append("task.properties")));
......@@ -222,6 +219,7 @@ public class MainConfig extends JFinalConfig {
*/
@Override
public void onStart() {
AppStartConfig.onStart("aserver");
// new GoodSync().run();
}
......
package com.archser.aserver.controller;
import com.archser.aserver.util.FinalStringUtil;
import java.io.File;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletRequest;
import com.archser.aserver.interceptor.JwtInterceptor;
import com.archser.aserver.model.Helper;
import com.archser.aserver.model.Menu;
import com.archser.aserver.service.HelperService;
import com.archser.aserver.service.LogService;
import com.archser.aserver.util.DownLoadFileUtil;
import com.jfinal.aop.Inject;
import com.jfinal.core.Controller;
import com.jfinal.kit.Kv;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;
import dm.jdbc.a.d;
/**
* 帮助中心
*/
public class HelperController extends Controller {
@Inject
private HelperService helperService;
@Inject
private LogService logService;
public void getList(){
String username = getAttr("username");
try {
Integer pageNumber = getParaToInt("pageNumber",1);
Integer pageSize = getParaToInt("pageSize",20);
String searchText = getPara("searchText","");
Page<Helper> list = helperService.getList(pageNumber, pageSize,searchText);
renderJson(Ret.ok("list",list));
logService.saveAsLog("access", "应用管理-帮助中心-帮助中心", FinalStringUtil.QUERY);
} catch (Exception e) {
e.printStackTrace();
logService.saveAsLogByFile("error","应用管理-帮助中心-获取帮助中心数据错误",null,e.getMessage(),FinalStringUtil.QUERY);
renderJson(Ret.fail("message","服务器出现异常,请联系管理员!"));
}
}
public void add(){
String username = getAttr("username");
try {
UploadFile file = getFile("file");
String name = getPara("name");
String description = getPara("description");
Integer type = getParaToInt("type");
if (helperService.add(file, name, description, type)){
logService.saveAsLog("operate", "应用管理-帮助中心-添加帮助中心数据成功",FinalStringUtil.ADD);
renderJson(Ret.ok("data", "添加成功!"));
return;
}
logService.saveAsLog("operate", "应用管理-帮助中心-添加帮助中心数据失败",FinalStringUtil.ADD);
renderJson(Ret.ok("data", "添加失败!"));
} catch (Exception e) {
e.printStackTrace();
logService.saveAsLogByFile("error","应用管理-帮助中心-添加帮助中心数据错误",null,e.getMessage(),FinalStringUtil.ADD);
renderJson(Ret.fail("msg","服务器出现异常,请联系管理员!"));
}
}
public void edit(){
String username = getAttr("username");
try {
Integer id = getParaToInt("id");
String name = getPara("name");
String description = getPara("description");
Integer type = getParaToInt("type");
if (helperService.edit(id, name, description, type)){
logService.saveAsLog("operate", "应用管理-帮助中心-修改帮助中心数据成功",FinalStringUtil.UPDATE);
renderJson(Ret.ok("msg", "修改成功"));
} else {
logService.saveAsLog("operate", "应用管理-帮助中心-修改帮助中心数据失败",FinalStringUtil.UPDATE);
renderJson(Ret.fail("msg","修改失败!"));
}
} catch (Exception e) {
e.printStackTrace();
logService.saveAsLogByFile("error","应用管理-帮助中心-修改帮助中心数据错误",null,e.getMessage(),FinalStringUtil.UPDATE);
renderJson(Ret.fail("msg","服务器出现异常,请联系管理员!"));
}
}
public void remove(){
String username = getAttr("username");
try {
String ids = getPara("ids");
if ( helperService.remove(ids)){
logService.saveAsLog("operate", "应用管理-帮助中心-删除帮助中心数据成功",FinalStringUtil.DELETE);
renderJson(Ret.ok("msg", "删除成功!"));
} else {
logService.saveAsLog("operate", "应用管理-帮助中心-删除帮助中心数据失败",FinalStringUtil.DELETE);
renderJson(Ret.fail("msg","删除失败!"));
}
} catch (Exception e) {
e.printStackTrace();
logService.saveAsLogByFile("error","应用管理-帮助中心-删除帮助中心数据错误",null,e.getMessage(),FinalStringUtil.DELETE);
renderJson(Ret.fail("msg","服务器出现异常,请联系管理员!"));
}
}
/**
* LiuKexin 20201120 下载操作手册
*/
public void downloadOperation() {
try {
Integer id = getParaToInt("id");
//文件是否存在
Ret downloadOperation = helperService.downloadOperation(id,getResponse());
if (downloadOperation.isOk()) {
Kv pathKv = (Kv) downloadOperation.get("msg");
/**LiuKexin 20210122 处理文件名 start */
String userAgent = getRequest().getHeader("user-agent").toLowerCase();
String fileName = pathKv.getStr("name");
if (userAgent.contains("msie") || userAgent.contains("like gecko") ) {
// win10 ie edge 浏览器 和其他系统的ie
fileName = URLEncoder.encode(fileName, "UTF-8");
} else {
// 非ie
fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
}
/**LiuKexin 20210122 处理文件名 end */
//下载文件
DownLoadFileUtil.downLoadFile(getResponse(), fileName, pathKv.getStr("path"), true);
renderJson(Ret.ok("msg", "下载成功"));
} else {
renderJson(downloadOperation);
}
} catch (Exception e) {
e.printStackTrace();
renderJson(Ret.fail("msg","服务器出现异常,请联系管理员!"));
}
}
/**
* LiuKexin 20210310 判断此页是否设置为首页
*/
public void HomeIsAlready() {
String username = this.getAttr("username");
String homeUrl = this.getPara("homeUrl");
// LiuKexin 20210319 添加参数
Boolean isHome = this.getParaToBoolean("isHome");
String mark = this.getPara("mark");
if (null == homeUrl) {
renderJson(Ret.fail("msg", "获取数据错误"));
}
renderJson(helperService.HomeIsAlready(username,homeUrl,isHome,mark));
}
/**
* LiuKexin 20210310 设置首页
*/
public void settingHome() {
String username = this.getAttr("username");
String homeUrl = this.getPara("homeUrl");
String origin = this.getPara("origin");
if (null == homeUrl || null == origin) {
renderJson(Ret.fail("msg", "获取数据错误"));
}
renderJson(helperService.settingHome(username,homeUrl,origin));
}
}
package com.archser.aserver.controller;
import com.archser.aserver.model.Helper;
import com.archser.aserver.service.HelperService;
import com.archser.aserver.util.DownLoadFileUtil;
import com.archser.aserver.util.FinalStringUtil;
import com.archser.commons.services.LogService;
import com.jfinal.aop.Inject;
import com.jfinal.core.Controller;
import com.jfinal.kit.Kv;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.upload.UploadFile;
import java.net.URLEncoder;
/**
* 帮助中心
*/
public class HelperController extends Controller {
@Inject
private HelperService helperService;
@Inject
private LogService logService;
public void getList(){
String username = getAttr("username");
try {
Integer pageNumber = getParaToInt("pageNumber",1);
Integer pageSize = getParaToInt("pageSize",20);
String searchText = getPara("searchText","");
Page<Helper> list = helperService.getList(pageNumber, pageSize,searchText);
renderJson(Ret.ok("list",list));
logService.saveAsLog("access", "应用管理-帮助中心-帮助中心", FinalStringUtil.QUERY);
} catch (Exception e) {
e.printStackTrace();
logService.saveAsLogByFile("error","应用管理-帮助中心-获取帮助中心数据错误",null,e.getMessage(),FinalStringUtil.QUERY);
renderJson(Ret.fail("message","服务器出现异常,请联系管理员!"));
}
}
public void add(){
String username = getAttr("username");
try {
UploadFile file = getFile("file");
String name = getPara("name");
String description = getPara("description");
Integer type = getParaToInt("type");
if (helperService.add(file, name, description, type)){
logService.saveAsLog("operate", "应用管理-帮助中心-添加帮助中心数据成功",FinalStringUtil.ADD);
renderJson(Ret.ok("data", "添加成功!"));
return;
}
logService.saveAsLog("operate", "应用管理-帮助中心-添加帮助中心数据失败",FinalStringUtil.ADD);
renderJson(Ret.ok("data", "添加失败!"));
} catch (Exception e) {
e.printStackTrace();
logService.saveAsLogByFile("error","应用管理-帮助中心-添加帮助中心数据错误",null,e.getMessage(),FinalStringUtil.ADD);
renderJson(Ret.fail("msg","服务器出现异常,请联系管理员!"));
}
}
public void edit(){
String username = getAttr("username");
try {
Integer id = getParaToInt("id");
String name = getPara("name");
String description = getPara("description");
Integer type = getParaToInt("type");
if (helperService.edit(id, name, description, type)){
logService.saveAsLog("operate", "应用管理-帮助中心-修改帮助中心数据成功",FinalStringUtil.UPDATE);
renderJson(Ret.ok("msg", "修改成功"));
} else {
logService.saveAsLog("operate", "应用管理-帮助中心-修改帮助中心数据失败",FinalStringUtil.UPDATE);
renderJson(Ret.fail("msg","修改失败!"));
}
} catch (Exception e) {
e.printStackTrace();
logService.saveAsLogByFile("error","应用管理-帮助中心-修改帮助中心数据错误",null,e.getMessage(),FinalStringUtil.UPDATE);
renderJson(Ret.fail("msg","服务器出现异常,请联系管理员!"));
}
}
public void remove(){
String username = getAttr("username");
try {
String ids = getPara("ids");
if ( helperService.remove(ids)){
logService.saveAsLog("operate", "应用管理-帮助中心-删除帮助中心数据成功",FinalStringUtil.DELETE);
renderJson(Ret.ok("msg", "删除成功!"));
} else {
logService.saveAsLog("operate", "应用管理-帮助中心-删除帮助中心数据失败",FinalStringUtil.DELETE);
renderJson(Ret.fail("msg","删除失败!"));
}
} catch (Exception e) {
e.printStackTrace();
logService.saveAsLogByFile("error","应用管理-帮助中心-删除帮助中心数据错误",null,e.getMessage(),FinalStringUtil.DELETE);
renderJson(Ret.fail("msg","服务器出现异常,请联系管理员!"));
}
}
/**
* LiuKexin 20201120 下载操作手册
*/
public void downloadOperation() {
try {
Integer id = getParaToInt("id");
//文件是否存在
Ret downloadOperation = helperService.downloadOperation(id,getResponse());
if (downloadOperation.isOk()) {
Kv pathKv = (Kv) downloadOperation.get("msg");
/**LiuKexin 20210122 处理文件名 start */
String userAgent = getRequest().getHeader("user-agent").toLowerCase();
String fileName = pathKv.getStr("name");
if (userAgent.contains("msie") || userAgent.contains("like gecko") ) {
// win10 ie edge 浏览器 和其他系统的ie
fileName = URLEncoder.encode(fileName, "UTF-8");
} else {
// 非ie
fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
}
/**LiuKexin 20210122 处理文件名 end */
//下载文件
DownLoadFileUtil.downLoadFile(getResponse(), fileName, pathKv.getStr("path"), true);
renderJson(Ret.ok("msg", "下载成功"));
} else {
renderJson(downloadOperation);
}
} catch (Exception e) {
e.printStackTrace();
renderJson(Ret.fail("msg","服务器出现异常,请联系管理员!"));
}
}
/**
* LiuKexin 20210310 判断此页是否设置为首页
*/
public void HomeIsAlready() {
String username = this.getAttr("username");
String homeUrl = this.getPara("homeUrl");
// LiuKexin 20210319 添加参数
Boolean isHome = this.getParaToBoolean("isHome");
String mark = this.getPara("mark");
if (null == homeUrl) {
renderJson(Ret.fail("msg", "获取数据错误"));
}
renderJson(helperService.HomeIsAlready(username,homeUrl,isHome,mark));
}
/**
* LiuKexin 20210310 设置首页
*/
public void settingHome() {
String username = this.getAttr("username");
String homeUrl = this.getPara("homeUrl");
String origin = this.getPara("origin");
if (null == homeUrl || null == origin) {
renderJson(Ret.fail("msg", "获取数据错误"));
}
renderJson(helperService.settingHome(username,homeUrl,origin));
}
}
package com.archser.aserver.controller;
import com.archser.aserver.util.AesEncryptUtil;
import com.archser.aserver.util.FinalStringUtil;
import com.archser.aserver.util.redis.InfoSystem;
import com.archser.aserver.util.redis.InfoUser;
import java.math.BigInteger;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
import org.bouncycastle.pqc.math.linearalgebra.ByteUtils;
import com.alibaba.fastjson.JSON;
import com.archser.aserver.interceptor.JwtInterceptor;
import com.archser.aserver.model.System;
import com.archser.aserver.model.User;
import com.archser.aserver.service.LogService;
import com.archser.aserver.service.UserService;
import com.archser.aserver.util.HttpRequestUtil;
import com.archser.aserver.util.KeysUtil;
import com.archser.aserver.util.gm.BCECUtil;
import com.archser.aserver.util.gm.SM2Util;
import com.jfinal.aop.Clear;
import com.jfinal.aop.Inject;
import com.jfinal.core.Controller;
import com.jfinal.kit.HashKit;
import com.jfinal.kit.Kv;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.redis.Redis;
import com.spbportal.sso.SsoToken;
import io.jsonwebtoken.JwsHeader;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
/**
* IndexController 指向系统访问首页
*
* @author jbolt.cn
* @email 909854136@qq.com
* @date 2018年11月4日 下午9:02:52
*/
public class IndexController extends Controller {
/**
* 登陆用户名,密码解密
*/
public static final String PRIVATE_KEY_D = "38627fffe8003e6d2faa76d4eae2f74fd9cd7be257ab36c356c4f01bbc17e41d";
public static final ECPrivateKeyParameters USER_PRIVATE_KEY = BCECUtil.createECPrivateKeyParameters(
new BigInteger(ByteUtils.fromHexString(PRIVATE_KEY_D)), SM2Util.DOMAIN_PARAMS);
private static Log log = Log.getLog(IndexController.class);
/**
* 超期时间:24小时,即:24 * 60 * 60 * 1000
*/
public static final int EXPIRATION = 24 * 60 * 60 * 1000;
private static int permitLoginTimes = 5;// 允许登陆次数
private static int hour = 2; // 两小时内不可登录
@Inject
private LogService logService;
@Inject
private UserService userService;
@Inject
private AesEncryptUtil encryptUtil;
/**
* 首页Action
*/
@Clear
public void index() {
render("index.html");
}
/**
* 修改密码
*/
@Clear
public void updatePassword() {
String username = this.getPara("username");
String password = this.getPara("newPwd");
password = HashKit.sha256(password);
int a = userService.updatePwd(password, username);
if (a == 0) {
this.renderJson(Ret.fail("msg", "修改失败"));
logService.saveAsLog("operate",
username + "修改密码操作:修改密码失败", FinalStringUtil.UPDATE);
return;
}
this.renderJson(Ret.ok("msg", "修改成功"));
logService.saveAsLog("operate", username + "修改密码操作:修改密码成功", FinalStringUtil.UPDATE);
}
private String decrypt(String sm2Cipher) throws InvalidCipherTextException {
return new String(SM2Util.decrypt(USER_PRIVATE_KEY, ByteUtils.fromHexString("04" + sm2Cipher)));
}
/**
* 登录验证
*/
@Clear(JwtInterceptor.class)
// @Before(LoginValidator.class)
public void login() {
String app = this.getPara("app");
String username = this.getPara("username");
String password = this.getPara("password");
String callback = this.getPara("callback");
// 解密用户名和密码
try {
username = AesEncryptUtil.desEncrypt(username);
password = AesEncryptUtil.desEncrypt(password);
} catch (Exception e1) {
e1.printStackTrace();
username = this.getPara("username");
password = this.getPara("password");
}
//校验密码是否符合强度设置
String verify = password;
password = HashKit.sha256(password);
User user = InfoUser.getUser(username);
if (user == null) {
this.renderJson(Ret.fail("msg", "用户名或密码不存在: " + username));
logService.saveAsLog("login", "该用户非本系统用户正在非法登录", FinalStringUtil.QUERY);
return;
}
/**chenyong 20201116 add 增加演示时提醒 start**/
String showSetting = Db.queryStr(Db.getSql("getConfigByName"), "showSetting");
if (showSetting != null) {
String[] showSettingArr=showSetting.split("\\|");
boolean isShow="是".equals(showSettingArr[0]);
if(isShow) {
boolean isShowUser=false;
String[] userNameArr=showSettingArr[1].split(",");
for(String userName:userNameArr) {
if(username.equals(userName)) {
isShowUser=true;
break;
}
}
if(!isShowUser) {
this.renderJson(Ret.fail("msg", "系统正在演示中,请稍候......"));
return;
}
}
}
/**chenyong 20201116 add end**/
// 一旦开启三员 admin用户不能使用
if ("admin".equals(user.getUsername())) {
Integer userCount = Db.queryInt(Db.getSql("hasThreeMemberUsersCount"));
boolean isExistThreeMemberUsers = userCount != null && (userCount > 0);
if (isExistThreeMemberUsers) {
this.renderJson(Ret.fail("msg", "已开启三员管理,admin失效了。"));
logService.saveAsLog("login", "登录失败,原因:已开启三员管理", FinalStringUtil.QUERY);
return;
}
}
if (user.getLocked() != null && Integer.parseInt(user.getLocked()) == 1) {
this.renderJson(Ret.fail("msg", "当前账户已被锁定"));
logService.saveAsLog("login","登录失败,原因:该用户已被锁定", FinalStringUtil.QUERY);
return;
}
if (!password.equals(user.getPassword())) {
if (this.checkErrorCount(user)) {
this.renderJson(Ret.fail("msg", "您的错误次数已达5次以上,请稍后再试!"));
} else {
int errorCount = permitLoginTimes - (user.getErrorcount() == null ? 0 : user.getErrorcount()) - 1;
if (user.getErrorcount() !=null && user.getErrorcount() == 4) {
this.renderJson(Ret.fail("msg", "用户名或密码验证失败,您的账户于两小时后才可登录!"));
} else {
this.renderJson(Ret.fail("msg", "用户名或密码验证失败,您还有" + errorCount + "次机会!"));
logService.saveAsLog("login", "登录失败,原因:密码验证错误", FinalStringUtil.QUERY);
}
}
return ;
}
Integer errorcount = user.getErrorcount();
if (errorcount != null && errorcount != 0) {
if (!this.checkWhenPwdOk(user)) {
Date date = new Date();
long hour1 = 2 * 60 * 60;
long begin = date.getTime();
long end = user.getLastLoginTime().getTime();
long between = (begin - end) / 1000;
long hour2 = (hour1 - between) % (24 * 3600) / 3600;
long minute = (hour1 - between) % 3600 / 60;
long second = (hour1 - between) % 60;
if (between < hour1) {
this.renderJson(Ret.fail("msg", "您的账户还剩" + hour2 + "小时" + minute + "分" + second + "秒才可登录!"));
return;
}
}
}
if (!"admin".equals(user.getUsername())) {
Integer noLockedRolesCount = Db.queryInt(Db.getSql("hasNoLockedRolesCount"), user.getUsername());
boolean noLockedRolesFlag = noLockedRolesCount != null && (noLockedRolesCount > 0);
if (!noLockedRolesFlag) {
this.renderJson(Ret.fail("msg", "拥有的角色全部被锁定,不能登录系统了。"));
logService.saveAsLog("login", "登录失败,原因:该用户拥有的角色全部被锁定", FinalStringUtil.QUERY);
return;
}
}
System system = InfoSystem.getSystem(app);
if (system == null) {
this.renderJson(Ret.fail("msg", "没有找到应用:" + app));
logService.saveAsLog("login", "登录失败,原因:没有找到应用" + app, FinalStringUtil.QUERY);
return;
}
if (StrKit.isBlank(system.getPrivatekey()) || StrKit.isBlank(system.getKeyid())) {
this.renderJson(Ret.fail("msg", "没有找到应用的密钥:" + app));
logService.saveAsLog("login", "登录失败,原因:没有找到应用的密钥" + app, FinalStringUtil.QUERY);
return;
}
//查询用户是否有该系统的权限
// boolean homeAuth = userService.checkUserSystemPermission(user.getId(), app);
// if (!homeAuth) {
// this.renderJson(Ret.fail("msg", "您没有权限登录" + system.getTitle() + "系统"));
// logService.saveAsLog("login", username, JwtInterceptor.getIpAddr(getRequest()), "登录失败,原因:您没有权限登录此系统" + app,
// app);
// return;
// }
List<System> systemList = userService.findSystemWithUserPermission(user.getId());
/** 修改如果登陆用户为admin用户则直接登陆 huwenbin 2020/5/20 start */
if (!"admin".equals(user.getUsername())) {
if ((systemList == null || systemList.isEmpty())) {
this.renderJson(Ret.fail("msg", "您没有权限登录" + system.getTitle() + "系统"));
logService.saveAsLog("login",
"登录失败,原因:您没有权限登录此系统" + app, FinalStringUtil.QUERY);
return;
}
Optional<System> systemOptional = userService.getSystemByName(app, systemList);
if (!systemOptional.isPresent()) {// 没有当前系统的权限
system = systemList.get(0);
app = system.getName();
callback = system.getUrl();
}
}
/** 修改如果登陆用户为admin用户则直接登陆 huwenbin 2020/5/20 end */
try {
String jws = Jwts.builder()
// 设置密匙ID
.setHeaderParam(JwsHeader.KEY_ID, system.getKeyid())
// 赋予应用
.setSubject(app)
// 签发时间
.setIssuedAt(new Date())
// 超期时间
.setExpiration(new Date(java.lang.System.currentTimeMillis() + EXPIRATION))
// 用户名
.claim("name", username).claim("ip", JwtInterceptor.getIpAddr(getRequest()))
// 签名
.signWith(KeysUtil.privatekey(system.getPrivatekey()), SignatureAlgorithm.RS256).compact();
if (errorcount != null && errorcount != 0) {
this.setErrZero(user);
}
Boolean aBoolean = userService.verifyPassword(verify);
this.renderJson(Ret.ok("token", jws).set("callback", callback).set("verify",aBoolean));
logService.saveAsLog("login", username + "登录" + app + "成功", FinalStringUtil.QUERY);
/**
* 20200706 lidecai 将用户信息保存到Redis end
*/
} catch (Exception e) {
log.error("生成登录票据失败", e);
this.renderJson(Ret.fail("msg", "生成登录票据失败"));
logService.saveAsLog("login", "生成登录票据失败", FinalStringUtil.QUERY);
}
}
/**
* LiuKexin 20210310 登录前先获取设置首页的信息
*/
@Clear
public void getUserHome() {
String username = this.getPara("username");
Record findUser = Db.findById("AS_USER", "username", username);
if (null == findUser) {
renderJson(Ret.fail());
return;
}
Record findUserHome = Db.findById("AS_USER_HOME", "user_id", findUser.getInt("ID"));
if (null == findUserHome) {
renderJson(Ret.fail());
return;
}
renderJson(Ret.ok("app", findUserHome.getStr("system")).set("callback", findUserHome.getStr("home_url")));
}
/**
* @Description: 验证密码强度
* @authorAndDate: ChengYaqing create on 2020/10/30 10:38
* @return void
*/
@Clear
public void verifyPassword() {
String password = getPara("password");
if(password==null||"".equals(password)||"null".equals(password)) {
renderJson(Ret.fail("msg","密码不能为空"));
return;
}
try {
password = decrypt(password);
} catch (Exception e1) {
e1.printStackTrace();
password = this.getPara("password");
}
try {
String verify = userService.verifyPasswordInfo(password);
if("".equals(verify)) {
renderJson(Ret.ok());
} else {
renderJson(Ret.fail("msg",verify));
}
} catch (Exception e) {
renderJson(Ret.fail("error",e.getMessage()));
}
}
// 密码正确时错误次数清零
private void setErrZero(User user) {
Db.update(Db.getSqlPara("updateForOk", Kv.by("id", user.getId())));
}
//密码错误时判断错误次数是否为5次
private boolean checkErrorCount(User user) {
Kv cond = Kv.by("id", user.getId()).set("hour", hour).set("permitLoginTimes", permitLoginTimes);
List<Record> currentList = Db.find(Db.getSqlPara("getErrorCount", cond));
int currentNum = 0;
for (Record record : currentList) {
currentNum = Integer.parseInt(record.get("flag").toString());
}
if (currentNum >= permitLoginTimes) {
return true;
} else {
//执行+1或=1的操作
Db.update(Db.getSqlPara("updateForErr", cond));
//同步到redis ChengYaqing 20210224
User byId = User.dao.findById(user.getId());
InfoUser.saveUser(byId);
return false;
}
}
//密码正确时判断次数和锁定时间是否在指定范围内
private boolean checkWhenPwdOk(User user) {
List<Record> currentList = Db.find(Db.getSqlPara("checkWhenPwdOk",
Kv.by("id", user.getId()).set("hour", hour).set("permitLoginTimes", permitLoginTimes)));
int currentNum = 0;
if (currentList == null || currentList.size() == 0) {
return true;
}
for (Record record : currentList) {
currentNum = Integer.parseInt(record.get("flag").toString());
}
if (currentNum >= permitLoginTimes) {
return false;
} else {
return true;
}
}
/**
* 通过门户系统单点登录
*
* @author Guo XJ
* @date 2019-12-13 15:08:00
*/
public void ssoByPortalSystem() {
try {
//获取app
String app = getPara("app", null);
if (app == null) {
renderJson(Ret.fail("msg", "获取服务信息失败"));
return;
}
//获取到门户系统的Token
String ssotoken = getPara("ssotoken");
//获取到personCode(用户唯一标识)
SsoToken st = new SsoToken();
st.initialise(ssotoken);
String personCode = st.getTokenId();
//获取用户
Record user = userService.getUserInfoByPersonCode(personCode);
System system = System.dao.template("getSystemPrivatekey", app).findFirst();
if (system == null) {
renderJson(Ret.fail("msg", "获取服务信息失败"));
return;
}
//判断用户是否存在
if (user != null && user.getStr("username") != null) {
String jws = Jwts.builder()
// 设置密匙ID
.setHeaderParam(JwsHeader.KEY_ID, system.getKeyid())
// 赋予应用
.setSubject(app)
// 签发时间
.setIssuedAt(new Date())
// 超期时间
.setExpiration(new Date(java.lang.System.currentTimeMillis() + EXPIRATION))
// 用户名
.claim("name", user.getStr("username")).claim("ip", JwtInterceptor.getIpAddr(getRequest()))
// 签名
.signWith(KeysUtil.privatekey(system.getPrivatekey()), SignatureAlgorithm.RS256).compact();
this.renderJson(Ret.ok("token", jws));
return;
} else {
this.renderJson(Ret.fail("msg", "没有找到当前用户"));
return;
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
this.renderJson(Ret.fail("msg", "登录出错!"));
}
}
/**
* 根据邮政门户传回的code 获取用户信息
*
* @Title: getUserInfoForH5
* @author LDC
* @date 2019-11-19 03:22:34
*/
@Clear
public void getUserInfoForH5() {
String code = getPara("code", null);
if (code == null) {
renderJson(Ret.fail("msg", "获取用户信息失败"));
return;
}
String app = getPara("app", null);
if (app == null) {
renderJson(Ret.fail("msg", "获取服务信息失败"));
return;
}
Map<String, String> paramMap = new LinkedHashMap<String, String>();
paramMap.put("client_id", "MmEepJkH7Hiz7EtS");
paramMap.put("code", code);
paramMap.put("state", "1");
paramMap.put("grant_type", "authorization_code");
paramMap.put("scope", "scope");
paramMap.put("redirect_uri", PropKit.get("redirect_uri"));
Iterator<Entry<String, String>> entrySet = paramMap.entrySet().iterator();
StringBuilder builder = new StringBuilder();
while (entrySet.hasNext()) {
Entry<String, String> next = entrySet.next();
builder.append(next.getKey()).append("=").append(next.getValue()).append("&");
}
String param = builder.deleteCharAt(builder.length() - 1).toString();
Kv header = Kv.by("Content-type", "application/x-www-form-urlencoded");
String result = HttpRequestUtil.sendPost(PropKit.get("authUrl"), param,header);
Kv parseObject = JSON.parseObject(result, Kv.class);
Object access_token = parseObject.get("access_token");
if (access_token == null) {
renderJson(Ret.fail("msg", "获取授权失败,请重新登录"));
return;
}
String sendPost = HttpRequestUtil.sendPost(PropKit.get("userInfoUrl"),
"access_token=" + access_token.toString(),header);
Kv userObj = JSON.parseObject(sendPost, Kv.class);
Object uuid = userObj.get("uuid");
if (uuid == null) {
renderJson(Ret.fail("msg", "获取用户信息失败"));
return;
}
System system = System.dao.template("getSystemPrivatekey", app).findFirst();
if (system == null) {
renderJson(Ret.fail("msg", "获取服务信息失败"));
return;
}
Record userInfo = Db.findById("AS_USER", "UUID", uuid.toString());
if (userInfo == null) {
renderJson(Ret.fail("msg", "没有找到当前用户"));
return;
}
String userName = userInfo.getStr("USERNAME");
if (userName == null) {
renderJson(Ret.fail("msg", "获取用户名失败"));
return;
}
try {
String jws = Jwts.builder()
// 设置密匙ID
.setHeaderParam(JwsHeader.KEY_ID, system.getKeyid())
// 赋予应用
.setSubject(app)
// 签发时间
.setIssuedAt(new Date())
// 超期时间
.setExpiration(new Date(java.lang.System.currentTimeMillis() + EXPIRATION))
// 用户名
.claim("name", userName).claim("ip", JwtInterceptor.getIpAddr(getRequest()))
// 签名
.signWith(KeysUtil.privatekey(system.getPrivatekey()), SignatureAlgorithm.RS256).compact();
this.renderJson(Ret.ok("token", jws));
logService.saveAsLog("login", userName + "登录" + app + "成功", FinalStringUtil.QUERY);
} catch (Exception e) {
log.error("生成登录票据失败", e);
this.renderJson(Ret.fail("msg", "生成登录票据失败"));
logService.saveAsLog("login", "生成登录票据失败", FinalStringUtil.QUERY);
}
}
/**
* 退出系统,清空Redis 中的用户信息
* @Time:2020年7月6日 - 下午5:19:58
* @author:李德才
* @param:
* @return: void
* @throws
*/
public void loginOut() {
String userName = getAttrForStr("username");
Redis.use().del(userName + "_INFO");
renderJson(Ret.ok());
}
}
package com.archser.aserver.controller;
import com.archser.aserver.model.User;
import com.archser.commons.db.InfoSystem;
import com.archser.commons.db.InfoUser;
import com.archser.commons.model.AsSystem;
import com.archser.commons.model.AsUser;
import com.archser.commons.services.LogService;
import com.archser.aserver.util.AesEncryptUtil;
import com.archser.aserver.util.FinalStringUtil;
import java.math.BigInteger;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
import org.bouncycastle.pqc.math.linearalgebra.ByteUtils;
import com.alibaba.fastjson.JSON;
import com.archser.aserver.interceptor.JwtInterceptor;
import com.archser.aserver.model.System;
import com.archser.aserver.service.UserService;
import com.archser.aserver.util.HttpRequestUtil;
import com.archser.aserver.util.KeysUtil;
import com.archser.aserver.util.gm.BCECUtil;
import com.archser.aserver.util.gm.SM2Util;
import com.jfinal.aop.Clear;
import com.jfinal.aop.Inject;
import com.jfinal.core.Controller;
import com.jfinal.kit.HashKit;
import com.jfinal.kit.Kv;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.redis.Redis;
import com.spbportal.sso.SsoToken;
import io.jsonwebtoken.JwsHeader;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
/**
* IndexController 指向系统访问首页
*
* @author jbolt.cn
* @email 909854136@qq.com
* @date 2018年11月4日 下午9:02:52
*/
public class IndexController extends Controller {
/**
* 登陆用户名,密码解密
*/
public static final String PRIVATE_KEY_D = "38627fffe8003e6d2faa76d4eae2f74fd9cd7be257ab36c356c4f01bbc17e41d";
public static final ECPrivateKeyParameters USER_PRIVATE_KEY = BCECUtil.createECPrivateKeyParameters(
new BigInteger(ByteUtils.fromHexString(PRIVATE_KEY_D)), SM2Util.DOMAIN_PARAMS);
private static Log log = Log.getLog(IndexController.class);
/**
* 超期时间:24小时,即:24 * 60 * 60 * 1000
*/
public static final int EXPIRATION = 24 * 60 * 60 * 1000;
private static int permitLoginTimes = 5;// 允许登陆次数
private static int hour = 2; // 两小时内不可登录
@Inject
private LogService logService;
@Inject
private UserService userService;
@Inject
private AesEncryptUtil encryptUtil;
/**
* 首页Action
*/
@Clear
public void index() {
render("index.html");
}
/**
* 修改密码
*/
@Clear
public void updatePassword() {
String username = this.getPara("username");
String password = this.getPara("newPwd");
password = HashKit.sha256(password);
int a = userService.updatePwd(password, username);
if (a == 0) {
this.renderJson(Ret.fail("msg", "修改失败"));
logService.saveAsLog("operate",
username + "修改密码操作:修改密码失败", FinalStringUtil.UPDATE);
return;
}
this.renderJson(Ret.ok("msg", "修改成功"));
logService.saveAsLog("operate", username + "修改密码操作:修改密码成功", FinalStringUtil.UPDATE);
}
private String decrypt(String sm2Cipher) throws InvalidCipherTextException {
return new String(SM2Util.decrypt(USER_PRIVATE_KEY, ByteUtils.fromHexString("04" + sm2Cipher)));
}
/**
* 登录验证
*/
@Clear(JwtInterceptor.class)
// @Before(LoginValidator.class)
public void login() {
String app = this.getPara("app");
String username = this.getPara("username");
String password = this.getPara("password");
String callback = this.getPara("callback");
// 解密用户名和密码
try {
username = decrypt(username);
password = decrypt(password);
} catch (Exception e1) {
e1.printStackTrace();
username = this.getPara("username");
password = this.getPara("password");
}
//校验密码是否符合强度设置
String verify = password;
password = HashKit.sha256(password);
AsUser user = InfoUser.getUser(username);
if (user == null) {
this.renderJson(Ret.fail("msg", "用户名或密码不存在: " + username));
logService.saveAsLog("login", "该用户非本系统用户正在非法登录", FinalStringUtil.QUERY);
return;
}
/**chenyong 20201116 add 增加演示时提醒 start**/
String showSetting = Db.queryStr(Db.getSql("getConfigByName"), "showSetting");
if (showSetting != null) {
String[] showSettingArr=showSetting.split("\\|");
boolean isShow="是".equals(showSettingArr[0]);
if(isShow) {
boolean isShowUser=false;
String[] userNameArr=showSettingArr[1].split(",");
for(String userName:userNameArr) {
if(username.equals(userName)) {
isShowUser=true;
break;
}
}
if(!isShowUser) {
this.renderJson(Ret.fail("msg", "系统正在演示中,请稍候......"));
return;
}
}
}
/**chenyong 20201116 add end**/
// 一旦开启三员 admin用户不能使用
if ("admin".equals(user.getUsername())) {
Integer userCount = Db.queryInt(Db.getSql("hasThreeMemberUsersCount"));
boolean isExistThreeMemberUsers = userCount != null && (userCount > 0);
if (isExistThreeMemberUsers) {
this.renderJson(Ret.fail("msg", "已开启三员管理,admin失效了。"));
logService.saveAsLog("login", "登录失败,原因:已开启三员管理", FinalStringUtil.QUERY);
return;
}
}
if (user.getLocked() != null && Integer.parseInt(user.getLocked()) == 1) {
this.renderJson(Ret.fail("msg", "当前账户已被锁定"));
logService.saveAsLog("login","登录失败,原因:该用户已被锁定", FinalStringUtil.QUERY);
return;
}
if (!password.equals(user.getPassword())) {
if (this.checkErrorCount(user)) {
this.renderJson(Ret.fail("msg", "您的错误次数已达5次以上,请稍后再试!"));
} else {
int errorCount = permitLoginTimes - (user.getErrorcount() == null ? 0 : user.getErrorcount()) - 1;
if (user.getErrorcount() !=null && user.getErrorcount() == 4) {
this.renderJson(Ret.fail("msg", "用户名或密码验证失败,您的账户于两小时后才可登录!"));
} else {
this.renderJson(Ret.fail("msg", "用户名或密码验证失败,您还有" + errorCount + "次机会!"));
logService.saveAsLog("login", "登录失败,原因:密码验证错误", FinalStringUtil.QUERY);
}
}
return ;
}
Integer errorcount = user.getErrorcount();
if (errorcount != null && errorcount != 0) {
if (!this.checkWhenPwdOk(user)) {
Date date = new Date();
long hour1 = 2 * 60 * 60;
long begin = date.getTime();
long end = user.getLastLoginTime().getTime();
long between = (begin - end) / 1000;
long hour2 = (hour1 - between) % (24 * 3600) / 3600;
long minute = (hour1 - between) % 3600 / 60;
long second = (hour1 - between) % 60;
if (between < hour1) {
this.renderJson(Ret.fail("msg", "您的账户还剩" + hour2 + "小时" + minute + "分" + second + "秒才可登录!"));
return;
}
}
}
if (!"admin".equals(user.getUsername())) {
Integer noLockedRolesCount = Db.queryInt(Db.getSql("hasNoLockedRolesCount"), user.getUsername());
boolean noLockedRolesFlag = noLockedRolesCount != null && (noLockedRolesCount > 0);
if (!noLockedRolesFlag) {
this.renderJson(Ret.fail("msg", "拥有的角色全部被锁定,不能登录系统了。"));
logService.saveAsLog("login", "登录失败,原因:该用户拥有的角色全部被锁定", FinalStringUtil.QUERY);
return;
}
}
AsSystem system = InfoSystem.getSystem(app);
if (system == null) {
this.renderJson(Ret.fail("msg", "没有找到应用:" + app));
logService.saveAsLog("login", "登录失败,原因:没有找到应用" + app, FinalStringUtil.QUERY);
return;
}
if (StrKit.isBlank(system.getPrivatekey()) || StrKit.isBlank(system.getKeyid())) {
this.renderJson(Ret.fail("msg", "没有找到应用的密钥:" + app));
logService.saveAsLog("login", "登录失败,原因:没有找到应用的密钥" + app, FinalStringUtil.QUERY);
return;
}
//查询用户是否有该系统的权限
// boolean homeAuth = userService.checkUserSystemPermission(user.getId(), app);
// if (!homeAuth) {
// this.renderJson(Ret.fail("msg", "您没有权限登录" + system.getTitle() + "系统"));
// logService.saveAsLog("login", username, JwtInterceptor.getIpAddr(getRequest()), "登录失败,原因:您没有权限登录此系统" + app,
// app);
// return;
// }
List<AsSystem> systemList = userService.findSystemWithUserPermission(user.getId());
/** 修改如果登陆用户为admin用户则直接登陆 huwenbin 2020/5/20 start */
if (!"admin".equals(user.getUsername())) {
if ((systemList == null || systemList.isEmpty())) {
this.renderJson(Ret.fail("msg", "您没有权限登录" + system.getTitle() + "系统"));
logService.saveAsLog("login",
"登录失败,原因:您没有权限登录此系统" + app, FinalStringUtil.QUERY);
return;
}
Optional<AsSystem> systemOptional = userService.getSystemByName(app, systemList);
if (!systemOptional.isPresent()) {// 没有当前系统的权限
system = systemList.get(0);
app = system.getName();
callback = system.getUrl();
}
}
/** 修改如果登陆用户为admin用户则直接登陆 huwenbin 2020/5/20 end */
try {
String jws = Jwts.builder()
// 设置密匙ID
.setHeaderParam(JwsHeader.KEY_ID, system.getKeyid())
// 赋予应用
.setSubject(app)
// 签发时间
.setIssuedAt(new Date())
// 超期时间
.setExpiration(new Date(java.lang.System.currentTimeMillis() + EXPIRATION))
// 用户名
.claim("name", username).claim("ip", JwtInterceptor.getIpAddr(getRequest()))
// 签名
.signWith(KeysUtil.privatekey(system.getPrivatekey()), SignatureAlgorithm.RS256).compact();
if (errorcount != null && errorcount != 0) {
this.setErrZero(user);
}
Boolean aBoolean = userService.verifyPassword(verify);
this.renderJson(Ret.ok("token", jws).set("callback", callback).set("verify",aBoolean));
logService.saveAsLog("login", username + "登录" + app + "成功", FinalStringUtil.QUERY);
/**
* 20200706 lidecai 将用户信息保存到Redis end
*/
} catch (Exception e) {
log.error("生成登录票据失败", e);
this.renderJson(Ret.fail("msg", "生成登录票据失败"));
logService.saveAsLog("login", "生成登录票据失败", FinalStringUtil.QUERY);
}
}
/**
* LiuKexin 20210310 登录前先获取设置首页的信息
*/
@Clear
public void getUserHome() {
String username = this.getPara("username");
Record findUser = Db.findById("AS_USER", "username", username);
if (null == findUser) {
renderJson(Ret.fail());
return;
}
Record findUserHome = Db.findById("AS_USER_HOME", "user_id", findUser.getInt("ID"));
if (null == findUserHome) {
renderJson(Ret.fail());
return;
}
renderJson(Ret.ok("app", findUserHome.getStr("system")).set("callback", findUserHome.getStr("home_url")));
}
/**
* @Description: 验证密码强度
* @authorAndDate: ChengYaqing create on 2020/10/30 10:38
* @return void
*/
@Clear
public void verifyPassword() {
String password = getPara("password");
if(password==null||"".equals(password)||"null".equals(password)) {
renderJson(Ret.fail("msg","密码不能为空"));
return;
}
try {
password = decrypt(password);
} catch (Exception e1) {
e1.printStackTrace();
password = this.getPara("password");
}
try {
String verify = userService.verifyPasswordInfo(password);
if("".equals(verify)) {
renderJson(Ret.ok());
} else {
renderJson(Ret.fail("msg",verify));
}
} catch (Exception e) {
renderJson(Ret.fail("error",e.getMessage()));
}
}
// 密码正确时错误次数清零
private void setErrZero(AsUser user) {
Db.update(Db.getSqlPara("updateForOk", Kv.by("id", user.getId())));
}
//密码错误时判断错误次数是否为5次
private boolean checkErrorCount(AsUser user) {
Kv cond = Kv.by("id", user.getId()).set("hour", hour).set("permitLoginTimes", permitLoginTimes);
List<Record> currentList = Db.find(Db.getSqlPara("getErrorCount", cond));
int currentNum = 0;
for (Record record : currentList) {
currentNum = Integer.parseInt(record.get("flag").toString());
}
if (currentNum >= permitLoginTimes) {
return true;
} else {
//执行+1或=1的操作
Db.update(Db.getSqlPara("updateForErr", cond));
//同步到redis ChengYaqing 20210224
AsUser byId = AsUser.dao.findById(user.getId());
InfoUser.saveUser(byId);
return false;
}
}
//密码正确时判断次数和锁定时间是否在指定范围内
private boolean checkWhenPwdOk(AsUser user) {
List<Record> currentList = Db.find(Db.getSqlPara("checkWhenPwdOk",
Kv.by("id", user.getId()).set("hour", hour).set("permitLoginTimes", permitLoginTimes)));
int currentNum = 0;
if (currentList == null || currentList.size() == 0) {
return true;
}
for (Record record : currentList) {
currentNum = Integer.parseInt(record.get("flag").toString());
}
if (currentNum >= permitLoginTimes) {
return false;
} else {
return true;
}
}
/**
* 通过门户系统单点登录
*
* @author Guo XJ
* @date 2019-12-13 15:08:00
*/
public void ssoByPortalSystem() {
try {
//获取app
String app = getPara("app", null);
if (app == null) {
renderJson(Ret.fail("msg", "获取服务信息失败"));
return;
}
//获取到门户系统的Token
String ssotoken = getPara("ssotoken");
//获取到personCode(用户唯一标识)
SsoToken st = new SsoToken();
st.initialise(ssotoken);
String personCode = st.getTokenId();
//获取用户
Record user = userService.getUserInfoByPersonCode(personCode);
System system = System.dao.template("getSystemPrivatekey", app).findFirst();
if (system == null) {
renderJson(Ret.fail("msg", "获取服务信息失败"));
return;
}
//判断用户是否存在
if (user != null && user.getStr("username") != null) {
String jws = Jwts.builder()
// 设置密匙ID
.setHeaderParam(JwsHeader.KEY_ID, system.getKeyid())
// 赋予应用
.setSubject(app)
// 签发时间
.setIssuedAt(new Date())
// 超期时间
.setExpiration(new Date(java.lang.System.currentTimeMillis() + EXPIRATION))
// 用户名
.claim("name", user.getStr("username")).claim("ip", JwtInterceptor.getIpAddr(getRequest()))
// 签名
.signWith(KeysUtil.privatekey(system.getPrivatekey()), SignatureAlgorithm.RS256).compact();
this.renderJson(Ret.ok("token", jws));
return;
} else {
this.renderJson(Ret.fail("msg", "没有找到当前用户"));
return;
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
this.renderJson(Ret.fail("msg", "登录出错!"));
}
}
/**
* 根据邮政门户传回的code 获取用户信息
*
* @Title: getUserInfoForH5
* @author LDC
* @date 2019-11-19 03:22:34
*/
@Clear
public void getUserInfoForH5() {
String code = getPara("code", null);
if (code == null) {
renderJson(Ret.fail("msg", "获取用户信息失败"));
return;
}
String app = getPara("app", null);
if (app == null) {
renderJson(Ret.fail("msg", "获取服务信息失败"));
return;
}
Map<String, String> paramMap = new LinkedHashMap<String, String>();
paramMap.put("client_id", "MmEepJkH7Hiz7EtS");
paramMap.put("code", code);
paramMap.put("state", "1");
paramMap.put("grant_type", "authorization_code");
paramMap.put("scope", "scope");
paramMap.put("redirect_uri", PropKit.get("redirect_uri"));
Iterator<Entry<String, String>> entrySet = paramMap.entrySet().iterator();
StringBuilder builder = new StringBuilder();
while (entrySet.hasNext()) {
Entry<String, String> next = entrySet.next();
builder.append(next.getKey()).append("=").append(next.getValue()).append("&");
}
String param = builder.deleteCharAt(builder.length() - 1).toString();
Kv header = Kv.by("Content-type", "application/x-www-form-urlencoded");
String result = HttpRequestUtil.sendPost(PropKit.get("authUrl"), param,header);
Kv parseObject = JSON.parseObject(result, Kv.class);
Object access_token = parseObject.get("access_token");
if (access_token == null) {
renderJson(Ret.fail("msg", "获取授权失败,请重新登录"));
return;
}
String sendPost = HttpRequestUtil.sendPost(PropKit.get("userInfoUrl"),
"access_token=" + access_token.toString(),header);
Kv userObj = JSON.parseObject(sendPost, Kv.class);
Object uuid = userObj.get("uuid");
if (uuid == null) {
renderJson(Ret.fail("msg", "获取用户信息失败"));
return;
}
System system = System.dao.template("getSystemPrivatekey", app).findFirst();
if (system == null) {
renderJson(Ret.fail("msg", "获取服务信息失败"));
return;
}
Record userInfo = Db.findById("AS_USER", "UUID", uuid.toString());
if (userInfo == null) {
renderJson(Ret.fail("msg", "没有找到当前用户"));
return;
}
String userName = userInfo.getStr("USERNAME");
if (userName == null) {
renderJson(Ret.fail("msg", "获取用户名失败"));
return;
}
try {
String jws = Jwts.builder()
// 设置密匙ID
.setHeaderParam(JwsHeader.KEY_ID, system.getKeyid())
// 赋予应用
.setSubject(app)
// 签发时间
.setIssuedAt(new Date())
// 超期时间
.setExpiration(new Date(java.lang.System.currentTimeMillis() + EXPIRATION))
// 用户名
.claim("name", userName).claim("ip", JwtInterceptor.getIpAddr(getRequest()))
// 签名
.signWith(KeysUtil.privatekey(system.getPrivatekey()), SignatureAlgorithm.RS256).compact();
this.renderJson(Ret.ok("token", jws));
logService.saveAsLog("login", userName + "登录" + app + "成功", FinalStringUtil.QUERY);
} catch (Exception e) {
log.error("生成登录票据失败", e);
this.renderJson(Ret.fail("msg", "生成登录票据失败"));
logService.saveAsLog("login", "生成登录票据失败", FinalStringUtil.QUERY);
}
}
/**
* 退出系统,清空Redis 中的用户信息
* @Time:2020年7月6日 - 下午5:19:58
* @author:李德才
* @param:
* @return: void
* @throws
*/
public void loginOut() {
String userName = getAttrForStr("username");
Redis.use().del(userName + "_INFO");
renderJson(Ret.ok());
}
}
package com.archser.aserver.controller;
import com.archser.aserver.util.FinalStringUtil;
import com.archser.aserver.util.redis.InfoSystem;
import com.archser.aserver.util.redis.InfoUser;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
......@@ -10,11 +8,13 @@ import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import com.archser.commons.db.InfoSystem;
import com.archser.commons.db.InfoUser;
import com.archser.commons.services.LogService;
import com.archser.aserver.interceptor.JwtInterceptor;
import com.archser.aserver.model.Menu;
import com.archser.aserver.model.MenuStar;
import com.archser.aserver.model.System;
import com.archser.aserver.service.LogService;
import com.archser.aserver.service.MenuService;
import com.archser.aserver.util.CollectionUtil;
import com.jfinal.aop.Inject;
......
package com.archser.aserver.controller;
import com.archser.aserver.util.FinalStringUtil;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import com.alibaba.fastjson.JSON;
import com.archser.aserver.interceptor.JwtInterceptor;
import com.archser.aserver.model.Message;
import com.archser.aserver.service.LogService;
import com.archser.aserver.service.MessageService;
import com.archser.aserver.websocket.MessageRefreshTrigger;
import com.jfinal.aop.Clear;
import com.jfinal.aop.Inject;
import com.jfinal.core.Controller;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
/**
* 消息相关
*
* @author dgq
*
*/
public class MessageController extends Controller {
@Inject
LogService logService;
@Inject
MessageService messageService;
private static final Logger logger = Logger.getLogger(MessageController.class);
/**
* 获取未读消息数量
*/
public void count() {
String username = this.getAttr("username");
Long count = messageService.getCountByRead(null, username);
this.renderJson(Ret.ok("count", count));
}
/**
* menu unread:未读,readed:已读,其他;查询所有
*/
public void getMessagePageData() {
int pageNumber = this.getParaToInt("pageNumber");
int pageSize = this.getParaToInt("pageSize");
String username = this.getAttr("username");
String menu = this.getPara("menu");
/** 2020年7月1日 添加模糊查询 yangchengwu YZJ-3915*/
String likeVal = this.getPara("likeVal");
Page<Message> page = messageService.getMessagePageData(pageNumber, pageSize, username, menu,likeVal);
if (page != null) {
renderJson(Ret.ok("page", page));
} else {
renderJson(Ret.fail("msg", "获取消息列表失败"));
}
}
/**
* 标记为已读
*/
public void markRead() {
int id = this.getParaToInt("id");
boolean markRead = this.messageService.markRead(id);
renderJson(markRead ? Ret.ok(): Ret.fail());
}
/**
* 删除消息
*/
public void deleteMessage() {
String ids = this.getPara("ids");
if (ids.length() == 0) {
renderJson(Ret.fail());
}
boolean deleted = this.messageService.deleteMessage(ids.split(","));
if (deleted) {
renderJson(Ret.ok());
logService.saveAsLog("operate", "个人首页-消息中心-删除消息-" + "-已删除了"+ids.split(",").length+"个消息", FinalStringUtil.DELETE);
}else {
renderJson(Ret.fail());
logService.saveAsLog("operate", "个人首页-消息中心-删除消息-删除消息失败",FinalStringUtil.DELETE);
}
}
/**
* 根据指定用户更新websocket的消息
*/
@Clear(JwtInterceptor.class)
public void refreshMessage() {
try {
String userId = this.getPara("userId");
if (StrKit.isBlank(userId)) {
userId = IOUtils.toString(this.getRequest().getInputStream());
userId = JSON.parseObject(userId).getString("userId");
}
logger.error("接受到消息刷新" + userId);
if (StrKit.notBlank(userId)) {
boolean refrashed = MessageRefreshTrigger.refresh(userId);
renderJson(Ret.ok("refrashed", refrashed));
} else {
renderJson(Ret.fail("msg", "userId为null或userId不是一个数字"));
}
} catch (Exception e) {
logger.error("刷新消息出错", e);
renderJson(Ret.fail("msg", "刷新消息出错"));
}
}
/**
* LiuKexin 20210402 批量标记为已读,且将通知性消息标为已读,下载或跳转的消息不批量已读
*/
public void allMsgReaded() {
String username = this.getAttr("username");
Ret allMsgReaded = messageService.allMsgReaded(username);
renderJson(allMsgReaded);
}
}
package com.archser.aserver.controller;
import com.archser.aserver.service.MessageService;
import com.archser.aserver.util.FinalStringUtil;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import com.alibaba.fastjson.JSON;
import com.archser.aserver.interceptor.JwtInterceptor;
import com.archser.aserver.model.Message;
import com.archser.aserver.service.LogService;
import com.archser.aserver.websocket.MessageRefreshTrigger;
import com.jfinal.aop.Clear;
import com.jfinal.aop.Inject;
import com.jfinal.core.Controller;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
/**
* 消息相关
*
* @author dgq
*
*/
public class MessageController extends Controller {
@Inject
LogService logService;
@Inject
MessageService messageService;
private static final Logger logger = Logger.getLogger(MessageController.class);
/**
* 获取未读消息数量
*/
public void count() {
String username = this.getAttr("username");
Long count = messageService.getCountByRead(null, username);
this.renderJson(Ret.ok("count", count));
}
/**
* menu unread:未读,readed:已读,其他;查询所有
*/
public void getMessagePageData() {
int pageNumber = this.getParaToInt("pageNumber");
int pageSize = this.getParaToInt("pageSize");
String username = this.getAttr("username");
String menu = this.getPara("menu");
/** 2020年7月1日 添加模糊查询 yangchengwu YZJ-3915*/
String likeVal = this.getPara("likeVal");
Page<Message> page = messageService.getMessagePageData(pageNumber, pageSize, username, menu,likeVal);
if (page != null) {
renderJson(Ret.ok("page", page));
} else {
renderJson(Ret.fail("msg", "获取消息列表失败"));
}
}
/**
* 标记为已读
*/
public void markRead() {
int id = this.getParaToInt("id");
boolean markRead = this.messageService.markRead(id);
renderJson(markRead ? Ret.ok(): Ret.fail());
}
/**
* 删除消息
*/
public void deleteMessage() {
String ids = this.getPara("ids");
if (ids.length() == 0) {
renderJson(Ret.fail());
}
boolean deleted = this.messageService.deleteMessage(ids.split(","));
if (deleted) {
renderJson(Ret.ok());
logService.saveAsLog("operate", "个人首页-消息中心-删除消息-" + "-已删除了"+ids.split(",").length+"个消息", FinalStringUtil.DELETE);
}else {
renderJson(Ret.fail());
logService.saveAsLog("operate", "个人首页-消息中心-删除消息-删除消息失败",FinalStringUtil.DELETE);
}
}
/**
* 根据指定用户更新websocket的消息
*/
@Clear(JwtInterceptor.class)
public void refreshMessage() {
try {
String userId = this.getPara("userId");
if (StrKit.isBlank(userId)) {
userId = IOUtils.toString(this.getRequest().getInputStream());
userId = JSON.parseObject(userId).getString("userId");
}
logger.error("接受到消息刷新" + userId);
if (StrKit.notBlank(userId)) {
boolean refrashed = MessageRefreshTrigger.refresh(userId);
renderJson(Ret.ok("refrashed", refrashed));
} else {
renderJson(Ret.fail("msg", "userId为null或userId不是一个数字"));
}
} catch (Exception e) {
logger.error("刷新消息出错", e);
renderJson(Ret.fail("msg", "刷新消息出错"));
}
}
/**
* LiuKexin 20210402 批量标记为已读,且将通知性消息标为已读,下载或跳转的消息不批量已读
*/
public void allMsgReaded() {
String username = this.getAttr("username");
Ret allMsgReaded = messageService.allMsgReaded(username);
renderJson(allMsgReaded);
}
}
package com.archser.aserver.itask;
import com.archser.aserver.model.Organ;
import com.archser.aserver.model.System;
import com.archser.aserver.model.User;
import com.archser.aserver.util.redis.InfoOrgan;
import com.archser.aserver.util.redis.InfoSystem;
import com.archser.aserver.util.redis.InfoUser;
import com.archser.commons.db.InfoOrgan;
import com.archser.commons.db.InfoSystem;
import com.archser.commons.db.InfoUser;
import com.archser.commons.model.AsOrgan;
import com.archser.commons.model.AsSystem;
import com.archser.commons.model.AsUser;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.cron4j.ITask;
......@@ -25,13 +25,13 @@ public class GoodSync implements ITask {
if (PropKit.getBoolean("updateRedis")) {
// 同步用户数据
java.lang.System.err.println("同步用户信息");
User.dao.findAll().forEach(InfoUser::saveUser);
AsUser.dao.findAll().forEach(InfoUser::saveUser);
// 同步系统数据
java.lang.System.err.println("同步系统数据");
System.dao.findAll().forEach(InfoSystem::saveSystem);
AsSystem.dao.findAll().forEach(InfoSystem::saveSystem);
// 同步机构数据
java.lang.System.err.println("同步机构数据");
Organ.dao.findAll().forEach(InfoOrgan::saveOrgan);
AsOrgan.dao.findAll().forEach(InfoOrgan::saveOrgan);
}
}
......
package com.archser.aserver.util.redis;
import com.alibaba.fastjson.JSONObject;
import com.archser.aserver.model.Organ;
/**
* 20201127 lidecai
* 操作redis中的机构信息
*/
public class InfoOrgan {
private static final String ORGAN = "ORGAN_";
/**
* 保存机构信息
*
* @param organ
* @return
*/
public static boolean saveOrgan(Organ organ) {
return RedisConvert.saveObject(ORGAN + organ.getId(), organ);
}
/**
* 获取机构信息
* @param organId
* @return
*/
public static Organ getOrgan(Integer organId){
Object organObj = RedisConvert.getObject(ORGAN + organId);
Organ organ = JSONObject.parseObject(JSONObject.toJSONString(organObj), Organ.class);
if(organ == null ){
organ = Organ.dao.findById(organId);
saveOrgan(organ);
}
return JSONObject.parseObject(JSONObject.toJSONString(organObj), Organ.class);
}
}
package com.archser.aserver.util.redis;
import com.alibaba.fastjson.JSONObject;
import com.archser.aserver.model.System;
import com.jfinal.plugin.redis.Redis;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* 获取系统信息 20201126 lidecai
*/
public class InfoSystem {
private static final String _INFO = "_INFO";
private static final String SYSTEM = "SYSTEM_";
/**
* 根据名称获取系统信息
*
* @param systemName
* @return
*/
public static System getSystem(String systemName) {
Object object = RedisConvert.getObject(SYSTEM + systemName + _INFO);
System system = JSONObject.parseObject(JSONObject.toJSONString(object), System.class);
if (system == null || system.getKeyid() == null) {
return getSystemByDatabase(systemName);
}
return system;
}
/**
* 备用方案,从数据库获取
*
* @param systemName
* @return
*/
public static System getSystemByDatabase(String systemName) {
System system = System.dao.template("getSystemPrivatekey", systemName).findFirst();
RedisConvert.saveObject(SYSTEM + systemName + _INFO, system);
return system;
}
/**
* 获取所有系统
* @return
*/
public static List<System> getAllSystem() {
Set<String> keys = Redis.use().keys(SYSTEM + "*");
List<System> systemList = new ArrayList<System>();
keys.forEach(system -> {
systemList.add(JSONObject
.parseObject(JSONObject.toJSONString(Redis.use().hgetAll(system)), System.class));
});
return systemList;
}
/**
* 保存系统信息
*
* @param system
* @return
*/
public static boolean saveSystem(System system) {
return RedisConvert.saveObject(SYSTEM + system.getName() + _INFO, system);
}
/**
* 删除系统信息
*
* @param systemName
* @return
*/
public static boolean deleteSystem(String systemName) {
return RedisConvert.deleteKey(SYSTEM + systemName + _INFO) > 0;
}
}
package com.archser.aserver.util.redis;
import com.archser.aserver.model.User;
import com.jfinal.kit.JsonKit;
/**
* 20201127 lidecai 操作redis中的用户信息
*/
public class InfoUser {
private static final String _INFO = "_INFO";
private static final String USER = "USER_";
/**
* 获取用户信息
*
* @param userName
* @return
*/
public static User getUser(String userName) {
Object object = RedisConvert.getObject(USER + userName + _INFO);
User user = JsonKit.parse(JsonKit.toJson(object), User.class);
if (user.getId() == null) {
User userByDataBase = getUserByDataBase(userName);
saveUser(userByDataBase);
return userByDataBase;
}
return user;
}
public static boolean saveUser(User user) {
return RedisConvert.saveObject(USER + user.getUsername() + _INFO, user);
}
/**
* 备用方案,从数据库获取用户信息
*
* @param userName
* @return
*/
public static User getUserByDataBase(String userName) {
return User.dao.template("getUser", userName).findFirst();
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment