VisitLogInterceptor.java 6.5 KB

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