Commit b54b928f by 宋振民

feat:审计日志新增登录时长

parent 26426cd4
ALTER TABLE `audit_log`
MODIFY COLUMN `USER_ID` int(11) NOT NULL COMMENT '用户ID' AFTER `STATE`,
MODIFY COLUMN `IP` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '用户IP' AFTER `USER_ID`,
MODIFY COLUMN `MODULE_CODE` int(11) NULL DEFAULT NULL COMMENT '模块编码' AFTER `IP`,
MODIFY COLUMN `OPERATE_TYPE` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '操作类型' AFTER `MODULE_CODE`,
MODIFY COLUMN `DESCRIBE` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '描述' AFTER `OPERATE_TYPE`,
ADD COLUMN `TOKEN` varchar(255) NULL COMMENT 'TOKEN' AFTER `DESCRIBE`;
ALTER TABLE `audit_log`
ADD COLUMN `URL` varchar(255) NULL COMMENT '访问url' AFTER `TOKEN`,
ADD COLUMN `PARAMS` text NULL COMMENT '参数' AFTER `URL`;
\ No newline at end of file
......@@ -82,6 +82,12 @@
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.5</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.8.1</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
......
package com.hs.admin.common.utils;
import org.apache.commons.lang3.time.DateFormatUtils;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DateUtils {
/**
* 仅显示年月日,例如 2015-08-11.
*/
public static final String DATE_FORMAT = "yyyy-MM-dd";
/**
* 显示年月日时分秒,例如 2015-08-11 09:51:53.
*/
public static final String DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
/**
* 仅显示时分秒,例如 09:51:53.
*/
public static final String TIME_FORMAT = "HH:mm:ss";
/**
* 每天的毫秒数 8640000.
*/
public static final long MILLISECONDS_PER_DAY = 86400000L;
/**
* 每周的天数.
*/
public static final long DAYS_PER_WEEK = 7L;
/**
* 每小时毫秒数.
*/
public static final long MILLISECONDS_PER_HOUR = 3600000L;
/**
* 每分钟秒数.
*/
public static final long SECONDS_PER_MINUTE = 60L;
/**
* 每小时秒数.
*/
public static final long SECONDS_PER_HOUR = 3600L;
/**
* 每天秒数.
*/
public static final long SECONDS_PER_DAY = 86400L;
/**
* 每个月秒数,默认每月30天.
*/
public static final long SECONDS_PER_MONTH = 2592000L;
/**
* 每年秒数,默认每年365天.
*/
public static final long SECONDS_PER_YEAR = 31536000L;
/**
* 常用的时间格式.
*/
private static String[] parsePatterns = { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy/MM/dd",
"yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm" };
/**
* 得到当前日期字符串.
* @return String 日期字符串,例如2015-08-11
* @since 1.0
*/
public static String getDate() {
return getDate(DateUtils.DATE_FORMAT);
}
/**
* 得到当前时间字符串.
* @return String 时间字符串,例如 09:51:53
* @since 1.0
*/
public static String getTime() {
return formatDate(new Date(), DateUtils.TIME_FORMAT);
}
/**
* 得到当前日期和时间字符串.
* @return String 日期和时间字符串,例如 2015-08-11 09:51:53
* @since 1.0
*/
public static String getDateTime() {
return formatDate(new Date(), DateUtils.DATETIME_FORMAT);
}
/**
* 获取当前时间指定格式下的字符串.
* @param pattern
* 转化后时间展示的格式,例如"yyyy-MM-dd","yyyy-MM-dd HH:mm:ss"等
* @return String 格式转换之后的时间字符串.
* @since 1.0
*/
public static String getDate(String pattern) {
return DateFormatUtils.format(new Date(), pattern);
}
/**
* 获取指定日期的字符串格式.
* @param date 需要格式化的时间,不能为空
* @param pattern 时间格式,例如"yyyy-MM-dd","yyyy-MM-dd HH:mm:ss"等
* @return String 格式转换之后的时间字符串.
* @since 1.0
*/
public static String getDate(Date date, String pattern) {
return DateFormatUtils.format(date, pattern);
}
/**
* 获取日期时间字符串,默认格式为(yyyy-MM-dd).
* @param date 需要转化的日期时间
* @param pattern 时间格式,例如"yyyy-MM-dd" "HH:mm:ss" "E"等
* @return String 格式转换后的时间字符串
* @since 1.0
*/
public static String formatDate(Date date, Object... pattern) {
String formatDate = null;
if (pattern != null && pattern.length > 0) {
formatDate = DateFormatUtils.format(date, pattern[0].toString());
} else {
formatDate = DateFormatUtils.format(date, DateUtils.DATE_FORMAT);
}
return formatDate;
}
/**
* 获取当前年份字符串.
* @return String 当前年份字符串,例如 2015
* @since 1.0
*/
public static String getYear() {
return formatDate(new Date(), "yyyy");
}
/**
* 获取当前月份字符串.
* @return String 当前月份字符串,例如 08
* @since 1.0
*/
public static String getMonth() {
return formatDate(new Date(), "MM");
}
/**
* 获取当前天数字符串.
* @return String 当前天数字符串,例如 11
* @since 1.0
*/
public static String getDay() {
return formatDate(new Date(), "dd");
}
/**
* 获取当前星期字符串.
* @return String 当前星期字符串,例如星期二
* @since 1.0
*/
public static String getWeek() {
return formatDate(new Date(), "E");
}
/**
* 将日期型字符串转换为日期格式.
* 支持的日期字符串格式包括"yyyy-MM-dd","yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm",
* "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm"
* @param str
* @return Date
* @since 1.0
*/
public static Date parseDate(Object str) {
if (str == null) {
return null;
}
try {
return org.apache.commons.lang3.time.DateUtils.parseDate(str.toString(), parsePatterns);
} catch (ParseException e) {
return null;
}
}
/**
* 获取当前日期与指定日期相隔的天数.
* @param date 给定的日期
* @return long 日期间隔天数,正数表示给定日期在当前日期之前,负数表示在当前日期之后
* @since 1.0
*/
public static long pastDays(Date date) {
// 将指定日期转换为yyyy-MM-dd格式
date = DateUtils.parseDate(DateUtils.formatDate(date, DateUtils.DATE_FORMAT));
// 当前日期转换为yyyy-MM-dd格式
Date currentDate = DateUtils.parseDate(DateUtils.formatDate(new Date(), DateUtils.DATE_FORMAT));
long t=0;
if(date!=null&&currentDate!=null){
t = (currentDate.getTime() - date.getTime()) / DateUtils.MILLISECONDS_PER_DAY;
}
return t;
}
/**
* 获取当前日期指定天数之后的日期.
* @param num 相隔天数
* @return Date 日期
* @since 1.0
*/
public static Date nextDay(int num) {
Calendar curr = Calendar.getInstance();
curr.set(Calendar.DAY_OF_MONTH, curr.get(Calendar.DAY_OF_MONTH) + num);
return curr.getTime();
}
/**
* 获取当前日期指定月数之后的日期.
* @param num 间隔月数
* @return Date 日期
* @since 1.0
*/
public static Date nextMonth(int num) {
Calendar curr = Calendar.getInstance();
curr.set(Calendar.MONTH, curr.get(Calendar.MONTH) + num);
return curr.getTime();
}
/**
* 获取当前日期指定年数之后的日期.
* @param num 间隔年数
* @return Date 日期
* @since 1.0
*/
public static Date nextYear(int num) {
Calendar curr = Calendar.getInstance();
curr.set(Calendar.YEAR, curr.get(Calendar.YEAR) + num);
return curr.getTime();
}
/**
* 将 Date 日期转化为 Calendar 类型日期.
* @param date 给定的时间,若为null,则默认为当前时间
* @return Calendar Calendar对象
* @since 1.0
*/
public static Calendar getCalendar(Date date) {
Calendar calendar = Calendar.getInstance();
// calendar.setFirstDayOfWeek(Calendar.SUNDAY);//每周从周日开始
// calendar.setMinimalDaysInFirstWeek(1); // 设置每周最少为1天
if (date != null) {
calendar.setTime(date);
}
return calendar;
}
/**
* 计算两个日期之间相差天数.
* @param start 计算开始日期
* @param end 计算结束日期
* @return long 相隔天数
* @since 1.0
*/
public static long getDaysBetween(Date start, Date end) {
// 将指定日期转换为yyyy-MM-dd格式
start = DateUtils.parseDate(DateUtils.formatDate(start, DateUtils.DATE_FORMAT));
// 当前日期转换为yyyy-MM-dd格式
end = DateUtils.parseDate(DateUtils.formatDate(end, DateUtils.DATE_FORMAT));
long diff=0;
if(start!=null&&end!=null) {
diff = (end.getTime() - start.getTime()) / DateUtils.MILLISECONDS_PER_DAY;
}
return diff;
}
/**
* 计算两个日期之前相隔多少周.
* @param start 计算开始时间
* @param end 计算结束时间
* @return long 相隔周数,向下取整
* @since 1.0
*/
public static long getWeeksBetween(Date start, Date end) {
return getDaysBetween(start, end) / DateUtils.DAYS_PER_WEEK;
}
/**
* 获取与指定日期间隔给定天数的日期.
* @param specifiedDay 给定的字符串格式日期,支持的日期字符串格式包括"yyyy-MM-dd","yyyy-MM-dd HH:mm:ss",
* "yyyy-MM-dd HH:mm", "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss",
* "yyyy/MM/dd HH:mm"
* @param num 间隔天数
* @return String 间隔指定天数之后的日期
* @since 1.0
*/
public static String getSpecifiedDayAfter(String specifiedDay, int num) {
Date specifiedDate = parseDate(specifiedDay);
Calendar c = Calendar.getInstance();
c.setTime(specifiedDate);
int day = c.get(Calendar.DATE);
c.set(Calendar.DATE, day + num);
String dayAfter = formatDate(c.getTime(), DateUtils.DATE_FORMAT);
return dayAfter;
}
/**
* 计算两个日期之前间隔的小时数.
*
* @param date1
* 结束时间
* @param date2
* 开始时间
* @return String 相差的小时数,保留一位小数
* @since 1.0
*/
public static String dateMinus(Date date1, Date date2) {
if (date1 == null || date2 == null) {
return "0";
}
Long r = date1.getTime() - date2.getTime();
DecimalFormat df = new DecimalFormat("#.0");
double result = r * 1.0 / DateUtils.MILLISECONDS_PER_HOUR;
return df.format(result);
}
/**
* 获取当前季度 .
*
* @return Integer 当前季度数
* @since 1.0
*/
public static Integer getCurrentSeason() {
Calendar calendar = Calendar.getInstance();
Integer month = calendar.get(Calendar.MONTH) + 1;
int season = 0;
if (month >= 1 && month <= 3) {
season = 1;
} else if (month >= 4 && month <= 6) {
season = 2;
} else if (month >= 7 && month <= 9) {
season = 3;
} else if (month >= 10 && month <= 12) {
season = 4;
}
return season;
}
/**
* 将以秒为单位的时间转换为其他单位.
*
* @param seconds
* 秒数
* @return String 例如 16分钟前、2小时前、3天前、4月前、5年前等
* @since 1.0
*/
public static String getIntervalBySeconds(long seconds) {
StringBuffer buffer = new StringBuffer();
if (seconds < SECONDS_PER_MINUTE) {
buffer.append(seconds).append("秒前");
} else if (seconds < SECONDS_PER_HOUR) {
buffer.append(seconds / SECONDS_PER_MINUTE).append("分钟前");
} else if (seconds < SECONDS_PER_DAY) {
buffer.append(seconds / SECONDS_PER_HOUR).append("小时前");
} else if (seconds < SECONDS_PER_MONTH) {
buffer.append(seconds / SECONDS_PER_DAY).append("天前");
} else if (seconds < SECONDS_PER_YEAR) {
buffer.append(seconds / SECONDS_PER_MONTH).append("月前");
} else {
buffer.append(seconds / DateUtils.SECONDS_PER_YEAR).append("年前");
}
return buffer.toString();
}
/**
*
* getNowTimeBefore(记录时间相当于目前多久之前)
*
* @param seconds
* 秒
* @return
* @exception @since
* 1.0
* @author rlliu
*/
public static String getNowTimeBefore(long seconds) {
StringBuffer buffer = new StringBuffer();
buffer.append("上传于");
if (seconds < 3600) {
buffer.append((long) Math.floor(seconds / 60.0)).append("分钟前");
} else if (seconds < 86400) {
buffer.append((long) Math.floor(seconds / 3600.0)).append("小时前");
} else if (seconds < 604800) {
buffer.append((long) Math.floor(seconds / 86400.0)).append("天前");
} else if (seconds < 2592000) {
buffer.append((long) Math.floor(seconds / 604800.0)).append("周前");
} else if (seconds < 31104000) {
buffer.append((long) Math.floor(seconds / 2592000.0)).append("月前");
} else {
buffer.append((long) Math.floor(seconds / 31104000.0)).append("年前");
}
return buffer.toString();
}
/**
*
* getMonthsBetween(查询两个日期相隔的月份)
*
* @param startDate 开始日期1 (格式yyyy-MM-dd)
* @param endDate 截止日期2 (格式yyyy-MM-dd)
* @return
*/
public static int getMonthsBetween(String startDate, String endDate) {
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
c1.setTime(DateUtils.parseDate(startDate));
c2.setTime(DateUtils.parseDate(endDate));
int year = c2.get(Calendar.YEAR) - c1.get(Calendar.YEAR);
int month = c2.get(Calendar.MONTH) - c1.get(Calendar.MONTH);
return Math.abs(year * 12 + month);
}
/**
*
* getDayOfWeek(获取当前日期是星期几)
*
* @param dateStr 日期
* @return 星期几
*/
public static String getDayOfWeek(String dateStr) {
String[] weekOfDays = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
Date date = parseDate(dateStr);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int num = calendar.get(Calendar.DAY_OF_WEEK) - 1;
return weekOfDays[num];
}
/**
* sns 格式 如几秒前,几分钟前,几小时前,几天前,几个月前,几年后, ... 精细,类如某个明星几秒钟之前发表了一篇微博
*
* @param createTime
* @return
*/
public static String snsFormat(long createTime) {
long now = System.currentTimeMillis() / 1000;
long differ = now - createTime / 1000;
String dateStr = "";
if (differ <= 60) {
dateStr = "刚刚";
} else if (differ <= 3600) {
dateStr = (differ / 60) + "分钟前";
} else if (differ <= 3600 * 24) {
dateStr = (differ / 3600) + "小时前";
} else if (differ <= 3600 * 24 * 30) {
dateStr = (differ / (3600 * 24)) + "天前";
} else {
Date date = new Date(createTime);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
dateStr = sdf.format(date);
}
return dateStr;
}
/**
* 得到UTC时间,类型为字符串,格式为"yyyy-MM-dd HH:mm"
* 如果获取失败,返回null
* @return
*/
public static String getUTCTimeStr() {
StringBuffer UTCTimeBuffer = new StringBuffer();
// 1、取得本地时间:
Calendar cal = Calendar.getInstance() ;
// 2、取得时间偏移量:
int zoneOffset = cal.get(Calendar.ZONE_OFFSET);
// 3、取得夏令时差:
int dstOffset = cal.get(Calendar.DST_OFFSET);
// 4、从本地时间里扣除这些差量,即可以取得UTC时间:
cal.add(Calendar.MILLISECOND, -(zoneOffset + dstOffset));
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH)+1;
int day = cal.get(Calendar.DAY_OF_MONTH);
int hour = cal.get(Calendar.HOUR_OF_DAY);
int minute = cal.get(Calendar.MINUTE);
UTCTimeBuffer.append(year).append("-").append(month).append("-").append(day) ;
UTCTimeBuffer.append(" ").append(hour).append(":").append(minute) ;
try{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
sdf.parse(UTCTimeBuffer.toString()) ;
return UTCTimeBuffer.toString() ;
}catch(ParseException e)
{
e.printStackTrace() ;
}
return null ;
}
public static String dateDiff(Date startTime, Date endTime) {
long nh = 1000 * 60 * 60;// 一小时的毫秒数
long nm = 1000 * 60;// 一分钟的毫秒数
long diff;
long day = 0;
long hour = 0;
long min = 0;
// 获得两个时间的毫秒时间差异
diff = endTime.getTime() - startTime.getTime();
hour = diff / nh;// 计算差多少小时
min = diff % nh / nm;// 计算差多少分钟
return hour + "小时"
+ (min - day * 24 * 60) + "分钟";
}
}
\ No newline at end of file
......@@ -35,4 +35,17 @@ public class AuditLog {
@Setter
private String describe;
@Setter
private String token;
@Setter
private String url;
@Setter
private String params;
@Setter
private String onlineTime;
}
......@@ -4,18 +4,22 @@ import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hs.admin.common.base.PageRequest;
import com.hs.admin.common.base.PageResult;
import com.hs.admin.common.utils.AESUtil;
import com.hs.admin.common.utils.DateUtils;
import com.hs.admin.common.utils.PageUtil;
import com.hs.admin.mapper.AuditLogMapper;
import com.hs.admin.model.AuditLog;
import com.hs.admin.model.reqmodel.AuditLogReq;
import com.hs.admin.model.respmodel.SysUserList;
import com.hs.admin.service.AuditLogService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import static java.util.stream.Collectors.groupingBy;
@Service
public class AuditLogServiceImpl implements AuditLogService {
......@@ -35,7 +39,52 @@ public class AuditLogServiceImpl implements AuditLogService {
PageHelper.startPage(page.getPageNum(), page.getPageSize());
List<AuditLog> allAuditLogs = auditLogMapper.getAllAuditLogs();
PageResult pageResult = PageUtil.getPageResult(page, new PageInfo<AuditLog>(allAuditLogs));
getOnlineTime(pageResult.getContent());
return pageResult;
}
private void getOnlineTime(List<AuditLog> auditLogs) {
Map<String,String> onlineTimeMap = new HashMap<>();
Map<String, List<AuditLog>> map = auditLogs.stream()
.collect(groupingBy(AuditLog::getToken));
for (String token : map.keySet()) {
List<AuditLog> auditLogList = map.get(token);
Date loginTime = null;
Date logoutTime = null;
Date lastRefreshTIme = null;
System.out.println("token=" + token);
for(AuditLog auditLog: auditLogList) {
Date createDate = auditLog.getCreateDate();
if(auditLog.getOperateType().equals("login")) {
loginTime= createDate;
}else if(auditLog.getOperateType().equals("logout")) {
logoutTime=createDate;
}else if(auditLog.getOperateType().equals("refresh")) {
if(lastRefreshTIme==null || createDate.getTime()>lastRefreshTIme.getTime()) {
lastRefreshTIme=createDate;
}
}
}
//有登录、退出时间的
if(loginTime!=null && logoutTime!=null) {
String dateMinus = DateUtils.dateDiff(loginTime, logoutTime);
System.out.println("时间差为:" + dateMinus);
onlineTimeMap.put(token, dateMinus);
}else if(loginTime!=null && logoutTime==null && lastRefreshTIme!=null) {
String dateMinus = DateUtils.dateDiff(loginTime, lastRefreshTIme);
System.out.println("时间差为:" + dateMinus);
onlineTimeMap.put(token, dateMinus);
}else{
onlineTimeMap.put(token,"0分钟");
}
}
System.out.println(onlineTimeMap);
for(AuditLog auditLog: auditLogs) {
auditLog.setOnlineTime(onlineTimeMap.get(auditLog.getToken()));
}
}
}
#### \u6D4B\u8BD5\u73AF\u5883 ###################################################
spring.datasource.url=jdbc:mysql://192.168.18.176:3306/scml_sy2.0?useUnicode=true&characterEncoding=utf8&useSSL=false&autoReconnect=true&rewriteBatchedStatements=TRUE&serverTimezone=UTC
spring.datasource.url=jdbc:mysql://192.168.18.176:3306/scml_sy2.1_org?useUnicode=true&characterEncoding=utf8&useSSL=false&autoReconnect=true&rewriteBatchedStatements=TRUE&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=Suvalue2016
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.druid.initial-size=1
# Redis\u6570\u636E\u5E93\u7D22\u5F15\uFF08\u9ED8\u8BA40\uFF09
spring.redis.database=0
spring.redis.database=1
spring.redis.host=192.168.18.166
spring.redis.port=6379
spring.redis.password=ll123456
......
......@@ -11,6 +11,9 @@
<result column="MODULE_CODE" jdbcType="INTEGER" property="moduleCode"/>
<result column="OPERATE_TYPE" jdbcType="VARCHAR" property="operateType"/>
<result column="DESCRIBE" jdbcType="VARCHAR" property="describe"/>
<result column="TOKEN" jdbcType="VARCHAR" property="token"/>
<result column="URL" jdbcType="VARCHAR" property="url"/>
<result column="PARAMS" jdbcType="VARCHAR" property="params"/>
</resultMap>
<insert id="insert" parameterType="com.hs.admin.model.AuditLog">
<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Long">
......
package com.hs.admin;
import com.hs.admin.model.AuditLog;
import com.hs.admin.model.reqmodel.UpdateUserReq;
import com.hs.admin.model.respmodel.SysUserList;
import com.hs.admin.service.AuditLogService;
import com.hs.admin.service.LoginService;
import com.hs.admin.service.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.ArrayList;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = HsAdminApplicationTests.class)
public class AuditLogServiceTest {
......
......@@ -9,6 +9,7 @@ import com.hs.api.model.respmodel.LoginInfo;
import com.hs.api.service.AuditLogService;
import com.hs.api.service.UserService;
import com.hs.common.utils.HttpUtil;
import com.hs.common.utils.RedisUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
......@@ -20,7 +21,9 @@ import org.springframework.web.context.request.ServletRequestAttributes;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
@Aspect
@Component
......@@ -60,12 +63,6 @@ public class AuditAspect {
@AfterReturning(pointcut = "audit()", returning = "rc")
public void afterReturning(JoinPoint joinPoint, Result rc) {
if(rc.getCode() == Result.ErrorCode.SUCCESS.getCode()) {
LoginInfo loginInfo = (LoginInfo) rc.getData();
SysUser user = loginInfo.getUser();
if (user==null) return;
HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
String ip = HttpUtil.getIP(request);
MethodSignature ms = (MethodSignature) joinPoint.getSignature();
Method method = ms.getMethod();
Audit audit = method.getAnnotation(Audit.class);
......@@ -73,6 +70,23 @@ public class AuditAspect {
int moduleCode = auditType.getModuleCode();
String operateType = auditType.getOperateType();
String describe = auditType.getDescribe();
SysUser user = new SysUser();
String token = new String();
HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
String ip = HttpUtil.getIP(request);
String uri = request.getRequestURI();
Object[] params = joinPoint.getArgs();
List<Object> paramsList = Arrays.asList(params);
if(operateType.equals(AuditLogType.REFRESH.getOperateType())) {
token = request.getHeader("Authorization");
user = (SysUser) RedisUtil.get(token);
}else {
LoginInfo loginInfo = (LoginInfo) rc.getData();
user = loginInfo.getUser();
token = loginInfo.getToken();
}
auditLog.setCreateDate(new Date());
auditLog.setState(true);
......@@ -81,6 +95,9 @@ public class AuditAspect {
auditLog.setModuleCode(moduleCode);
auditLog.setOperateType(operateType);
auditLog.setDescribe(describe);
auditLog.setToken(token);
auditLog.setUrl(uri);
auditLog.setParams(paramsList.toString());
auditLogService.add(auditLog);
}
}
......
......@@ -2,7 +2,8 @@ package com.hs.api.common.enums;
public enum AuditLogType {
LOGIN(1, "login","用户登录"),
LOGOUT(2, "logout","用户注销");
LOGOUT(2, "logout","用户注销"),
REFRESH(1, "refresh","页面刷新");
private int moduleCode;
private String operateType;
......
package com.hs.api.controller;
import com.hs.api.common.Result;
import com.hs.api.common.annotations.Audit;
import com.hs.api.common.annotations.CurrentUser;
import com.hs.api.common.annotations.Token;
import com.hs.api.common.enums.AuditLogType;
import com.hs.api.model.reqmodel.BlockValues;
import com.hs.api.model.reqmodel.BlockValuesNew;
import com.hs.api.model.respmodel.BlockValue;
......@@ -36,6 +38,7 @@ public class BlockValuesController {
@ApiIgnore
// @PostMapping("blockValues")
@Token
@Audit(type = AuditLogType.REFRESH)
@ApiOperation("根据Page查询板块数值")
public Object getBlockValuesByPageID(@RequestBody BlockValues blockValues) throws InterruptedException {
......@@ -52,6 +55,7 @@ public class BlockValuesController {
*/
@PostMapping("blockValuesNew")
@Token
@Audit(type = AuditLogType.REFRESH)
@ApiOperation("根据Page查询板块数值")
public Object getBlockValuesByPageIDNew(@ApiIgnore @CurrentUser Long userId,@RequestBody BlockValuesNew blockValues) throws InterruptedException {
......@@ -67,6 +71,7 @@ public class BlockValuesController {
*/
@PostMapping("customBlockValues")
@Token
@Audit(type = AuditLogType.REFRESH)
@ApiOperation("根据Page获取报表标题信息")
public Object getCustomBlockValuesByPageCode(@ApiIgnore @CurrentUser Long userId,@RequestBody BlockValuesNew blockValues) throws InterruptedException {
Map<String, List> titleMap = blockValuesService.getCustomBlockValuesByPageCode(userId, blockValues.getPageCode(), blockValues.getDim());
......
package com.hs.api.controller;
import com.hs.api.common.Result;
import com.hs.api.common.annotations.Audit;
import com.hs.api.common.annotations.CurrentUser;
import com.hs.api.common.annotations.Token;
import com.hs.api.common.enums.AuditLogType;
import com.hs.api.model.SerDepartment;
import com.hs.api.model.reqmodel.Disease;
import com.hs.api.service.SysUserOrgRsService;
......@@ -29,6 +31,7 @@ public class DeptController {
*/
@PostMapping("/dept/list")
@Token
@Audit(type = AuditLogType.REFRESH)
@ApiOperation("查询科室列表")
public Object getList(@ApiIgnore @CurrentUser Long userId, @RequestBody Disease.DiseaseIDorLevel disease) {
List<SerDepartment> sysMenuList = sysUserOrgRsService.getUserOrg(userId, disease.getDisease(), disease.getDate());
......
package com.hs.api.controller;
import com.hs.api.common.Result;
import com.hs.api.common.annotations.Audit;
import com.hs.api.common.annotations.Token;
import com.hs.api.common.enums.AuditLogType;
import com.hs.api.model.reqmodel.ReqDimValue;
import com.hs.api.model.respmodel.DimValue;
import com.hs.api.service.DicDimService;
......@@ -29,6 +31,7 @@ public class DimController {
*/
@PostMapping("dimValue")
@Token
@Audit(type = AuditLogType.REFRESH)
@ApiOperation("根据pageCode查询维度数值")
public Object getdimValueByPageCode(@RequestBody @Valid ReqDimValue reqDimValue) {
List<DimValue> dimValueList = dicDimService.getByPageCode(reqDimValue.getPageCode(),reqDimValue.getOrgId(),reqDimValue.getDate());
......
package com.hs.api.controller;
import com.hs.api.common.Result;
import com.hs.api.common.annotations.Audit;
import com.hs.api.common.annotations.Token;
import com.hs.api.common.enums.AuditLogType;
import com.hs.api.model.SerDoctor;
import com.hs.api.model.reqmodel.Doctor;
import com.hs.api.service.SerDoctorService;
......@@ -27,6 +29,7 @@ public class DoctorController {
*/
@PostMapping("/doctor/list")
@Token
@Audit(type = AuditLogType.REFRESH)
@ApiOperation("根据科室查询医生列表")
public Object getList(@RequestBody Doctor doctor) throws InterruptedException {
List<SerDoctor> list = serDoctorService.getDoctor(doctor.getDept());
......
package com.hs.api.controller;
import com.hs.api.common.Result;
import com.hs.api.common.annotations.Audit;
import com.hs.api.common.annotations.Token;
import com.hs.api.common.enums.AuditLogType;
import com.hs.api.common.handlers.GlobalExceptionHandler;
import com.hs.api.model.reqmodel.ExportReq;
import com.hs.api.service.ExcelService;
......@@ -27,6 +29,7 @@ public class ExcelController {
@PostMapping("export")
@Token
@Audit(type = AuditLogType.REFRESH)
@ApiOperation("将Table转换为Xls")
public Object tableToXls(HttpServletRequest request,@RequestBody ExportReq info) {
String tableStr = StringEscapeUtils.unescapeHtml4(info.getTableStr());
......
package com.hs.api.controller;
import com.hs.api.common.Result;
import com.hs.api.common.annotations.Audit;
import com.hs.api.common.enums.AuditLogType;
import com.hs.api.model.DicIndInfo;
import com.hs.api.service.DicIndService;
import io.swagger.annotations.Api;
......@@ -39,6 +41,7 @@ public class IndController {
// }
@GetMapping("ind/find")
@Audit(type = AuditLogType.REFRESH)
public Object find(Integer pageCode, String filter) {
List<DicIndInfo> list = dicIndService.selectAll(pageCode, filter);
return Result.success(list);
......
package com.hs.api.controller;
import com.hs.api.common.Result;
import com.hs.api.common.annotations.Audit;
import com.hs.api.common.annotations.CurrentUser;
import com.hs.api.common.annotations.Token;
import com.hs.api.common.enums.AuditLogType;
import com.hs.api.model.reqmodel.Disease;
import com.hs.api.model.respmodel.DiseaseLevel;
import com.hs.api.model.respmodel.DiseaseName;
......@@ -33,6 +35,7 @@ public class SerDiseaseController {
*/
@PostMapping("disease/list")
@Token
@Audit(type = AuditLogType.REFRESH)
@ApiOperation("根据疾病编码或者疾病等级查询疾病列表")
public Object getDiseaseByLevel(@ApiIgnore @CurrentUser Long userId, @RequestBody Disease.DiseaseIDorLevel disease) throws InterruptedException {
List<DiseaseLevel> diseaseLevel = serDiseaseService.selectListByIdorLevel(disease.getDate(), disease.getDisease(),
......@@ -42,6 +45,7 @@ public class SerDiseaseController {
@PostMapping("disease/name")
@Token
@Audit(type = AuditLogType.REFRESH)
@ApiOperation("根据疾病名称查询疾病信息")
public Object getDiseaseByMdcName(@ApiIgnore @CurrentUser Long userId, @RequestBody Disease.DiseaseName disease) throws InterruptedException {
List<DiseaseName> list = serDiseaseService.selectByMdcName(userId, disease.getDate(), disease.getMdcName(), disease.getDoctor(), disease.getDept(), disease.getMedicalRecord());
......
package com.hs.api.controller;
import com.hs.api.common.Result;
import com.hs.api.common.annotations.Audit;
import com.hs.api.common.annotations.Token;
import com.hs.api.common.enums.AuditLogType;
import com.hs.api.model.SerDiseaseDocRs;
import com.hs.api.model.reqmodel.DiseaseDoc;
import com.hs.api.service.SerDiseaseDocService;
......@@ -23,6 +25,7 @@ public class SerDiseaseDocController {
@PostMapping("diseaseDoc")
@Token
@Audit(type = AuditLogType.REFRESH)
@ApiOperation("根据Code查询疾病关系信息")
public Object getDiseaseDoc(@RequestBody DiseaseDoc disease) throws InterruptedException {
List<SerDiseaseDocRs> list = serDiseaseDocService.getDiseaseDoc(disease.getDocCode(),disease.getMdcCode(),
......
package com.hs.api.controller;
import com.hs.api.common.Result;
import com.hs.api.common.annotations.Audit;
import com.hs.api.common.annotations.CurrentUser;
import com.hs.api.common.annotations.Token;
import com.hs.api.common.enums.AuditLogType;
import com.hs.api.model.reqmodel.AddBudgetValue;
import com.hs.api.model.reqmodel.QueryBudgetValue;
import com.hs.api.model.reqmodel.QuerySummary;
......@@ -25,6 +27,7 @@ public class SerProjValueController {
@PostMapping("budget/value")
@Token
@Audit(type = AuditLogType.REFRESH)
@ApiOperation("查询预算编制数据")
public Object getProjValue(@ApiIgnore @CurrentUser Long userId,@RequestBody QueryBudgetValue request) throws Throwable {
Object result = projValueService.getValue(request.getProjectType(),request.getDate(),request.getDeptCode(),userId);
......@@ -34,6 +37,7 @@ public class SerProjValueController {
@PostMapping("budget/save")
@Token
@Audit(type = AuditLogType.REFRESH)
@ApiOperation("保存数据")
public Object save(@ApiIgnore @CurrentUser Long userId,@RequestBody AddBudgetValue request) throws Throwable {
boolean result = projValueService.save(userId,request);
......@@ -45,6 +49,7 @@ public class SerProjValueController {
@PostMapping("budget/summary")
@Token
@Audit(type = AuditLogType.REFRESH)
@ApiOperation("查询预算编制汇总数据")
public Object getSummary(@ApiIgnore @CurrentUser Long userId,@RequestBody QuerySummary request) throws Throwable {
Object result = projValueService.getSummary(request.getDate(),request.getBudgetType(),userId);
......@@ -53,6 +58,7 @@ public class SerProjValueController {
@PostMapping("budget/summarynew")
@Token
@Audit(type = AuditLogType.REFRESH)
@ApiOperation("查询预算编制汇总数据")
public Object getSummaryNew(@RequestBody QuerySummary req) throws Throwable {
Object result = projValueService.getData(req.getDate(),req.getPage());
......
package com.hs.api.controller;
import com.hs.api.common.Result;
import com.hs.api.common.annotations.Audit;
import com.hs.api.common.annotations.Token;
import com.hs.api.common.enums.AuditLogType;
import com.hs.api.model.reqmodel.SysConfigReq;
import com.hs.api.service.SysConfigService;
import io.swagger.annotations.Api;
......@@ -24,6 +26,7 @@ public class SysConfigController {
*/
@PostMapping("getSysConfigByKey")
@Token
@Audit(type = AuditLogType.REFRESH)
@ApiOperation("根据key查询系统配置")
public Result<Boolean> sysConfigReq(@RequestBody SysConfigReq sysConfigReq) {
boolean state = sysConfigService.getStateByKey(sysConfigReq.getKey());
......
......@@ -76,6 +76,7 @@ public class UserController {
*/
@PostMapping("roles")
@Token
@Audit(type = AuditLogType.REFRESH)
@ApiOperation("查询用户角色")
public Object getRoleListByUser(@ApiIgnore @CurrentUser Long userId) throws Exception {
List<SysRole> sysRoleList = sysUserRoleRsService.getRoleListByUser(userId);
......@@ -90,6 +91,7 @@ public class UserController {
*/
@PostMapping("menus")
@Token
@Audit(type = AuditLogType.REFRESH)
@ApiOperation("查询用户菜单")
public Object getMenuByUser(@ApiIgnore @CurrentUser Long userId) throws Exception {
List<SysMenuList> sysMenuList = sysMenuService.getMenu(userId);
......@@ -98,6 +100,7 @@ public class UserController {
@PostMapping("menu/list")
@Token
@Audit(type = AuditLogType.REFRESH)
@ApiOperation("查询综合菜单")
public Object getMenuByType(HttpServletRequest request,@RequestBody MenuReq req) throws Exception {
String token = request.getHeader(Constants.TOKEN_KEY);
......@@ -108,6 +111,7 @@ public class UserController {
@PostMapping("module/state")
@Token
@Audit(type = AuditLogType.REFRESH)
@ApiOperation("查询module状态")
public Object getModuleStateByCode(HttpServletRequest request,@RequestBody ModuleReq req) throws Exception {
String token = request.getHeader(Constants.TOKEN_KEY);
......@@ -124,6 +128,7 @@ public class UserController {
*/
@PostMapping("dept")
@Token
@Audit(type = AuditLogType.REFRESH)
@ApiOperation("查询用户科室")
public Object getOrgByUser(@ApiIgnore @CurrentUser Long userId, @RequestBody Disease.DiseaseIDorLevel disease) throws Exception {
List<SerDepartment> sysMenuList = sysUserOrgRsService.getUserOrg(userId, disease.getDisease(), disease.getDate());
......
......@@ -32,4 +32,13 @@ public class AuditLog {
@Setter
private String describe;
@Setter
private String token;
@Setter
private String url;
@Setter
private String params;
}
......@@ -148,6 +148,7 @@ public class LoginServiceImpl implements LoginService {
String token = request.getHeader(Constants.TOKEN_KEY);
SysUser user = (SysUser) RedisUtil.get(token);
loginInfo.setUser(user);
loginInfo.setToken(token);
if(!token.equals("") && token!=null) {
RedisUtil.del(token);
};
......
......@@ -9,10 +9,10 @@ spring.datasource.druid.initial-size=1
project.path=localhost
# Redis\u6570\u636E\u5E93\u7D22\u5F15\uFF08\u9ED8\u8BA40\uFF09
spring.redis.database=1
spring.redis.host=127.0.0.1
spring.redis.port=7379
spring.redis.password=123456
spring.redis.database=2
spring.redis.host=192.168.18.166
spring.redis.port=6379
spring.redis.password=ll123456
spring.redis.jedis.pool.max-active=8
# \u8FDE\u63A5\u6C60\u6700\u5927\u963B\u585E\u7B49\u5F85\u65F6\u95F4\uFF08\u4F7F\u7528\u8D1F\u503C\u8868\u793A\u6CA1\u6709\u9650\u5236\uFF09
spring.redis.jedis.pool.max-wait=-1
......
......@@ -16,10 +16,11 @@
SELECT LAST_INSERT_ID()
</selectKey>
insert into audit_log (CREATE_DATE, `STATE`,
USER_ID, IP, MODULE_CODE, OPERATE_TYPE, `DESCRIBE`
USER_ID, IP, MODULE_CODE, OPERATE_TYPE, `DESCRIBE`,TOKEN,URL,PARAMS
)
values (#{createDate,jdbcType=TIMESTAMP}, #{state,jdbcType=DECIMAL}, #{userId,jdbcType=DECIMAL},
#{ip,jdbcType=VARCHAR}, #{moduleCode,jdbcType=VARCHAR}, #{operateType,jdbcType=DECIMAL}, #{describe,jdbcType=VARCHAR}
#{ip,jdbcType=VARCHAR}, #{moduleCode,jdbcType=VARCHAR}, #{operateType,jdbcType=DECIMAL}, #{describe,jdbcType=VARCHAR},
#{token,jdbcType=VARCHAR},#{url,jdbcType=VARCHAR},#{params,jdbcType=VARCHAR}
)
</insert>
<select id="selectAll" resultMap="BaseResultMap">
......
<?xml version="1.0" encoding="UTF-8"?>
<module org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule="true" version="4">
<module org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule="true" type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_5">
<output url="file://$MODULE_DIR$/target/classes" />
<output-test url="file://$MODULE_DIR$/target/test-classes" />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src/test/java" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
<excludeFolder url="file://$MODULE_DIR$/target" />
</content>
<orderEntry type="inheritedJdk" />
......
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