package com.yuanchu.mom.config; import cn.hutool.json.JSONObject; import cn.hutool.json.JSONUtil; import com.alibaba.fastjson.JSON; import com.yuanchu.mom.annotation.ValueAuth; import com.yuanchu.mom.exception.ErrorException; import com.yuanchu.mom.exception.MyFileException; import com.yuanchu.mom.mapper.AuthMapper; import com.yuanchu.mom.utils.JackSonUtil; import com.yuanchu.mom.utils.Jwt; import com.yuanchu.mom.utils.ServletUtils; import org.apache.catalina.User; import org.springframework.stereotype.Component; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Map; @Component public class PowerConfig implements HandlerInterceptor { @Resource private AuthMapper authMapper; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if(handler instanceof HandlerMethod) { if(request.getRequestURL().toString().equals("http://127.0.0.1:8001/error")){ return HandlerInterceptor.super.preHandle(request, response, handler); } HandlerMethod h = (HandlerMethod)handler; ValueAuth annotation = h.getMethodAnnotation(ValueAuth.class); if(annotation!=null){ return HandlerInterceptor.super.preHandle(request, response, handler); } JSONObject obj = JSONUtil.parseObj(new Jwt().readJWT(request.getHeader("token")).get("data")); Integer userId = Integer.parseInt(obj.get("id") + ""); int i = authMapper.isPower(userId, h.getMethod().getName()); if (i == 0){ throw new ErrorException(obj.get("name") + " 无权限访问 " + h.getMethod().getName() + " 接口"); } } return HandlerInterceptor.super.preHandle(request, response, handler); } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { HandlerInterceptor.super.postHandle(request, response, handler, modelAndView); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { HandlerInterceptor.super.afterCompletion(request, response, handler, ex); } }