VisitLogInterceptor.java 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. package com.fdkankan.manage.aop;
  2. import cn.dev33.satoken.stp.StpUtil;
  3. import cn.hutool.core.util.StrUtil;
  4. import cn.hutool.extra.servlet.ServletUtil;
  5. import cn.hutool.http.ContentType;
  6. import cn.hutool.http.useragent.UserAgent;
  7. import cn.hutool.http.useragent.UserAgentUtil;
  8. import com.alibaba.fastjson.JSON;
  9. import com.alibaba.fastjson.JSONObject;
  10. import com.fdkankan.common.constant.ServerCode;
  11. import com.fdkankan.common.util.SecurityUtil;
  12. import com.fdkankan.manage.config.SaTokenConfigure;
  13. import com.fdkankan.manage.entity.SysLog;
  14. import com.fdkankan.manage.entity.SysUser;
  15. import com.fdkankan.manage.service.ISysLogService;
  16. import com.fdkankan.manage.service.ISysUserService;
  17. import com.fdkankan.redis.util.RedisUtil;
  18. import org.aspectj.lang.JoinPoint;
  19. import org.aspectj.lang.ProceedingJoinPoint;
  20. import org.aspectj.lang.annotation.Around;
  21. import org.aspectj.lang.annotation.Aspect;
  22. import org.aspectj.lang.annotation.Pointcut;
  23. import org.aspectj.lang.reflect.MethodSignature;
  24. import org.springframework.beans.factory.annotation.Autowired;
  25. import org.springframework.beans.factory.annotation.Value;
  26. import org.springframework.stereotype.Component;
  27. import org.springframework.util.ObjectUtils;
  28. import org.springframework.util.StringUtils;
  29. import org.springframework.web.context.request.RequestContextHolder;
  30. import org.springframework.web.context.request.ServletRequestAttributes;
  31. import org.springframework.web.multipart.MultipartFile;
  32. import javax.servlet.http.HttpServletRequest;
  33. import java.util.*;
  34. @Component
  35. @Aspect
  36. public class VisitLogInterceptor {
  37. @Autowired
  38. private RedisUtil redisUtil;
  39. @Autowired
  40. ISysLogService sysLogService;
  41. @Autowired
  42. private ISysUserService userService;
  43. @Value("${server.servlet.context-path:null}")
  44. private String contextPath;
  45. // 切入点表达式
  46. @Pointcut("execution(public * com.fdkankan.manage.controller..*.*(..))")
  47. public void privilege() {
  48. }
  49. @Around("privilege()")
  50. public Object around(ProceedingJoinPoint pjp) throws Throwable {
  51. HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
  52. //获取客户端ip
  53. String clientIP = ServletUtil.getClientIP(request);
  54. //获取uri
  55. String uri = request.getRequestURI();
  56. if(StrUtil.isNotEmpty(contextPath)){
  57. uri = uri.replaceFirst(contextPath, "");
  58. }
  59. //获取请求方式
  60. String method = request.getMethod();
  61. //获取浏览器信息
  62. String browser = this.getBrowser(request);
  63. //获取操作路径
  64. String requestPath = this.getRequestPath(uri);
  65. //获取参数
  66. String params = this.getParams(pjp, request);
  67. //放行
  68. Object result = pjp.proceed();
  69. String msg = null;
  70. if(!ObjectUtils.isEmpty(result)){
  71. msg = "操作失败";
  72. String resultStr = JSON.toJSONString(result);
  73. JSONObject jsonObject = JSON.parseObject(resultStr);
  74. if(jsonObject.getInteger("code")== null || jsonObject.getInteger("code").equals(ServerCode.SUCCESS.code())){
  75. msg = "操作成功";
  76. }
  77. }
  78. //获取用户信息 如果已登录,从token中获取用户信息,如果是登录接口,查询数据库获取用户信息
  79. Long userId =null;
  80. String userName =null;
  81. String nickName =null;
  82. try {
  83. userId = Long.valueOf(StpUtil.getExtra("userId").toString());
  84. userName = (String)StpUtil.getExtra("userName");
  85. nickName = (String)StpUtil.getExtra("nickName");
  86. }catch (Exception e){
  87. e.printStackTrace();
  88. if(uri.contains("/login")){
  89. JSONObject paramObj = JSONObject.parseObject(params);
  90. userName = paramObj.getString("userName");
  91. SysUser sysUser = userService.getByUserName(userName);
  92. if(sysUser != null){
  93. userId = sysUser.getId();
  94. nickName = sysUser.getNickName();
  95. }
  96. }
  97. }
  98. // if("GET".equals(method)){
  99. // return result;
  100. // }
  101. //写入mongodb
  102. SysLog operLog = new SysLog();
  103. operLog.setUserId(userId);
  104. operLog.setUserName(userName);
  105. operLog.setNickName(nickName);
  106. operLog.setRequestPath(requestPath);
  107. operLog.setUri(uri);
  108. operLog.setMethod(method);
  109. operLog.setParams(params);
  110. operLog.setIp(clientIP);
  111. operLog.setBrowser(browser);
  112. operLog.setCreateTime(Calendar.getInstance().getTime());
  113. operLog.setResult(msg);
  114. operLog.setOperationType("manage");
  115. sysLogService.save(operLog);
  116. return result;
  117. }
  118. private String getRequestPath(String uri) {
  119. if(uri.contains("/login")){
  120. return "登录";
  121. }
  122. JSONObject jsonObject = SaTokenConfigure.manageMenuUrl.get(uri);
  123. if(StringUtils.isEmpty(jsonObject)){
  124. return null;
  125. }
  126. List<String> list = new ArrayList<>();
  127. getMenuName(list,jsonObject.getString("id"));
  128. Collections.reverse(list);
  129. StringBuilder requestPath = new StringBuilder();
  130. for (String path : list) {
  131. requestPath.append("[").append(path).append("]").append("->");
  132. }
  133. int i = requestPath.lastIndexOf("->");
  134. if(i < 0){
  135. return requestPath.toString();
  136. }
  137. return requestPath.substring(0,i);
  138. }
  139. private int getMenuName( List<String> list,String menuId){
  140. JSONObject jsonObject = SaTokenConfigure.manageMenuId.get(menuId);
  141. if(org.springframework.util.StringUtils.isEmpty(jsonObject)){
  142. return -1;
  143. }
  144. list.add( jsonObject.getString("name"));
  145. String parentId = jsonObject.getString("parentId");
  146. if(!StringUtils.isEmpty(parentId)){
  147. return getMenuName(list,parentId);
  148. }
  149. return 1;
  150. }
  151. private String getParams(JoinPoint pjp, HttpServletRequest request){
  152. try {
  153. // 获取参数名称
  154. String[] parameterNamesArgs = ((MethodSignature) pjp.getSignature()).getParameterNames();
  155. //获取请求参数值
  156. Object[] args = pjp.getArgs();
  157. Map<String, Object> paramMap = new HashMap<>();
  158. String contentType = request.getContentType();
  159. if(StringUtils.isEmpty(contentType)){
  160. return null;
  161. }
  162. if(ContentType.JSON.getValue().equals(contentType)){
  163. String param = args[0] .toString();
  164. return JSON.toJSONString(param);
  165. }else{
  166. for (int i = 0; i < args.length; i++) {
  167. if(args[i] instanceof MultipartFile){
  168. paramMap.put(parameterNamesArgs[i], ((MultipartFile) args[i]).getOriginalFilename());
  169. continue;
  170. }
  171. paramMap.put(parameterNamesArgs[i], args[i]);
  172. }
  173. }
  174. return JSON.toJSONString(paramMap);
  175. }catch (Exception e){
  176. e.printStackTrace();
  177. }
  178. return null;
  179. }
  180. private String getBrowser(HttpServletRequest request){
  181. String userAgentStr = request.getHeader("User-Agent");
  182. UserAgent userAgent = UserAgentUtil.parse(userAgentStr);
  183. String browserType = userAgent.getBrowser().toString();
  184. String browserVersion = userAgent.getVersion();
  185. String browserFormat = "%s(版本%s)";
  186. return String.format(browserFormat, browserType, browserVersion);
  187. }
  188. }