packagespring.cloud.common.interceptor;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;importorg.springframework.web.servlet.ModelAndView;importorg.springframework.web.servlet.handler.HandlerInterceptorAdapter;importcom.alibaba.fastjson.JSON;importspring.cloud.common.context.UserContextHolder;importspring.cloud.common.util.UserPermissionUtil;importspring.cloud.common.vo.User;public class UserContextInterceptor extendsHandlerInterceptorAdapter {private static final Logger log = LoggerFactory.getLogger(UserContextInterceptor.class);
@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse respone, Object arg2) throwsException {
User user=getUser(request);//TODO 日常测试先关闭服务间的资源权限校验//UserPermissionUtil.permission(user);//if(!UserPermissionUtil.verify(user,request)) {//respone.setHeader("Content-Type", "application/json");//String jsonstr = JSON.toJSONString("no permisson access service, please check");//respone.getWriter().write(jsonstr);//respone.getWriter().flush();//respone.getWriter().close();//throw new PermissionException("no permisson access service, please check");//}
UserContextHolder.set(user);return true;
}
@Overridepublic voidpostHandle(HttpServletRequest request, HttpServletResponse respone, Object arg2, ModelAndView arg3)throwsException {//DOING NOTHING
}
@Overridepublic voidafterCompletion(HttpServletRequest request, HttpServletResponse respone, Object arg2, Exception arg3)throwsException {
UserContextHolder.shutdown();
}privateUser getUser(HttpServletRequest request){
String userid= request.getHeader("x-user-id");
String username= request.getHeader("x-user-name");
User user= newUser();
user.setUserId(userid);
user.setUserName(username);returnuser;
}static class PermissionException extendsRuntimeException {private static final long serialVersionUID = 1L;publicPermissionException(String msg) {super(msg);
}
}
}