VisitLogInterceptor.java 7.4 KB

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