mrbird il y a 6 ans
Parent
commit
3471cce83e

+ 1 - 2
febs-auth/src/main/java/cc/mrbird/febs/auth/service/impl/SocialLoginServiceImpl.java

@@ -13,7 +13,6 @@ import cc.mrbird.febs.common.entity.constant.SocialConstant;
 import cc.mrbird.febs.common.entity.system.SystemUser;
 import cc.mrbird.febs.common.exception.FebsException;
 import cc.mrbird.febs.common.utils.FebsUtil;
-import cc.mrbird.febs.common.utils.HttpContextUtil;
 import cn.hutool.core.util.StrUtil;
 import com.xkcoding.justauth.AuthRequestFactory;
 import me.zhyd.oauth.config.AuthSource;
@@ -193,7 +192,7 @@ public class SocialLoginServiceImpl implements SocialLoginService {
     }
 
     private OAuth2AccessToken getOAuth2AccessToken(SystemUser user) throws FebsException {
-        final HttpServletRequest httpServletRequest = HttpContextUtil.getHttpServletRequest();
+        final HttpServletRequest httpServletRequest = FebsUtil.getHttpServletRequest();
         httpServletRequest.setAttribute(ParamsConstant.LOGIN_TYPE, SocialConstant.SOCIAL_LOGIN);
         String socialLoginClientId = properties.getSocialLoginClientId();
         ClientDetails clientDetails = null;

+ 5 - 0
febs-common/pom.xml

@@ -29,6 +29,11 @@
             <artifactId>xml-apis</artifactId>
             <version>1.4.01</version>
         </dependency>
+        <dependency>
+            <groupId>org.lionsoul</groupId>
+            <artifactId>ip2region</artifactId>
+            <version>1.7</version>
+        </dependency>
         <dependency>
             <groupId>org.apache.commons</groupId>
             <artifactId>commons-lang3</artifactId>

+ 3 - 0
febs-common/src/main/java/cc/mrbird/febs/common/entity/constant/FebsConstant.java

@@ -57,4 +57,7 @@ public class FebsConstant {
      */
     public static final Long REGISTER_ROLE_ID = 2L;
 
+    public static final String LOCALHOST = "localhost";
+    public static final String LOCALHOST_IP = "127.0.0.1";
+
 }

+ 15 - 1
febs-common/src/main/java/cc/mrbird/febs/common/handler/BaseExceptionHandler.java

@@ -9,6 +9,8 @@ import org.springframework.http.HttpStatus;
 import org.springframework.security.access.AccessDeniedException;
 import org.springframework.validation.BindException;
 import org.springframework.validation.FieldError;
+import org.springframework.web.HttpMediaTypeNotSupportedException;
+import org.springframework.web.HttpRequestMethodNotSupportedException;
 import org.springframework.web.bind.annotation.ExceptionHandler;
 import org.springframework.web.bind.annotation.ResponseStatus;
 
@@ -84,8 +86,20 @@ public class BaseExceptionHandler {
 
     @ExceptionHandler(value = AccessDeniedException.class)
     @ResponseStatus(HttpStatus.FORBIDDEN)
-    public FebsResponse handleAccessDeniedException(){
+    public FebsResponse handleAccessDeniedException() {
         return new FebsResponse().message("没有权限访问该资源");
     }
 
+    @ExceptionHandler(value = HttpMediaTypeNotSupportedException.class)
+    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
+    public FebsResponse handleHttpMediaTypeNotSupportedException(HttpMediaTypeNotSupportedException e) {
+        return new FebsResponse().message("改方法不支持" + StringUtils.substringBetween(e.getMessage(), "'", "'") + "媒体类型");
+    }
+
+    @ExceptionHandler(value = HttpRequestMethodNotSupportedException.class)
+    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
+    public FebsResponse handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
+        return new FebsResponse().message("该方法不支持" + StringUtils.substringBetween(e.getMessage(), "'", "'") + "请求方法");
+    }
+
 }

+ 1 - 5
febs-server/febs-server-system/src/main/java/cc/mrbird/febs/server/system/utils/AddressUtil.java → febs-common/src/main/java/cc/mrbird/febs/common/utils/AddressUtil.java

@@ -1,4 +1,4 @@
-package cc.mrbird.febs.server.system.utils;
+package cc.mrbird.febs.common.utils;
 
 import cc.mrbird.febs.common.entity.constant.FebsConstant;
 import org.apache.commons.io.FileUtils;
@@ -6,7 +6,6 @@ import org.apache.commons.lang3.StringUtils;
 import org.lionsoul.ip2region.DataBlock;
 import org.lionsoul.ip2region.DbConfig;
 import org.lionsoul.ip2region.DbSearcher;
-import org.lionsoul.ip2region.Util;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -41,9 +40,6 @@ public class AddressUtil {
             DbConfig config = new DbConfig();
             searcher = new DbSearcher(config, file.getPath());
             Method method = searcher.getClass().getMethod("btreeSearch", String.class);
-            if (!Util.isIpAddress(ip)) {
-                log.error("Error: Invalid ip address");
-            }
             DataBlock dataBlock = (DataBlock) method.invoke(searcher, ip);
             return dataBlock.getRegion();
         } catch (Exception e) {

+ 13 - 0
febs-common/src/main/java/cc/mrbird/febs/common/utils/DateUtil.java

@@ -4,6 +4,7 @@ import java.text.ParseException;
 import java.text.SimpleDateFormat;
 import java.time.Instant;
 import java.time.LocalDateTime;
+import java.time.LocalTime;
 import java.time.ZoneId;
 import java.time.format.DateTimeFormatter;
 import java.util.Date;
@@ -81,4 +82,16 @@ public class DateUtil {
         LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
         return localDateTime.format(DateTimeFormatter.ofPattern(format));
     }
+
+    /**
+     * 判断当前时间是否在指定时间范围
+     *
+     * @param from 开始时间
+     * @param to   结束时间
+     * @return 结果
+     */
+    public static boolean between(LocalTime from, LocalTime to) {
+        LocalTime now = LocalTime.now();
+        return now.isAfter(from) && now.isBefore(to);
+    }
 }

+ 89 - 10
febs-common/src/main/java/cc/mrbird/febs/common/utils/FebsUtil.java

@@ -7,11 +7,19 @@ import com.baomidou.mybatisplus.core.metadata.IPage;
 import com.fasterxml.jackson.databind.ObjectMapper;
 import lombok.extern.slf4j.Slf4j;
 import org.apache.commons.lang3.StringUtils;
+import org.springframework.core.io.buffer.DataBuffer;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.server.reactive.ServerHttpRequest;
+import org.springframework.http.server.reactive.ServerHttpResponse;
 import org.springframework.security.core.Authentication;
 import org.springframework.security.core.GrantedAuthority;
 import org.springframework.security.core.context.SecurityContextHolder;
 import org.springframework.security.oauth2.provider.OAuth2Authentication;
 import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
+import org.springframework.web.context.request.RequestContextHolder;
+import org.springframework.web.context.request.ServletRequestAttributes;
+import reactor.core.publisher.Mono;
 
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
@@ -106,6 +114,23 @@ public class FebsUtil {
         response.getOutputStream().write(JSONObject.toJSONString(value).getBytes());
     }
 
+    /**
+     * 设置webflux模型响应
+     *
+     * @param response    ServerHttpResponse
+     * @param contentType content-type
+     * @param status      http状态码
+     * @param value       响应内容
+     * @return Mono<Void>
+     */
+    public static Mono<Void> makeWebFluxResponse(ServerHttpResponse response, String contentType,
+                                                 HttpStatus status, Object value) {
+        response.setStatusCode(status);
+        response.getHeaders().add(HttpHeaders.CONTENT_TYPE, contentType);
+        DataBuffer dataBuffer = response.bufferFactory().wrap(JSONObject.toJSONString(value).getBytes());
+        return response.writeWith(Mono.just(dataBuffer));
+    }
+
     /**
      * 封装前端分页表格所需数据
      *
@@ -119,6 +144,70 @@ public class FebsUtil {
         return data;
     }
 
+    /**
+     * 获取HttpServletRequest
+     *
+     * @return HttpServletRequest
+     */
+    public static HttpServletRequest getHttpServletRequest() {
+        return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
+    }
+
+    /**
+     * 获取请求IP
+     *
+     * @return String IP
+     */
+    public static String getHttpServletRequestIpAddress() {
+        HttpServletRequest request = getHttpServletRequest();
+        String ip = request.getHeader("x-forwarded-for");
+        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
+            ip = request.getHeader("Proxy-Client-IP");
+        }
+        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
+            ip = request.getHeader("WL-Proxy-Client-IP");
+        }
+        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
+            ip = request.getRemoteAddr();
+        }
+        return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
+    }
+
+    /**
+     * 获取请求IP
+     *
+     * @param request ServerHttpRequest
+     * @return String IP
+     */
+    public static String getServerHttpRequestIpAddress(ServerHttpRequest request) {
+        HttpHeaders headers = request.getHeaders();
+        String ip = headers.getFirst("x-forwarded-for");
+        if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
+            if (ip.contains(",")) {
+                ip = ip.split(",")[0];
+            }
+        }
+        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
+            ip = headers.getFirst("Proxy-Client-IP");
+        }
+        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
+            ip = headers.getFirst("WL-Proxy-Client-IP");
+        }
+        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
+            ip = headers.getFirst("HTTP_CLIENT_IP");
+        }
+        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
+            ip = headers.getFirst("HTTP_X_FORWARDED_FOR");
+        }
+        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
+            ip = headers.getFirst("X-Real-IP");
+        }
+        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
+            ip = Objects.requireNonNull(request.getRemoteAddress()).getAddress().getHostAddress();
+        }
+        return ip;
+    }
+
     /**
      * 判断是否包含中文
      *
@@ -176,16 +265,6 @@ public class FebsUtil {
         return details.getTokenValue();
     }
 
-    /**
-     * 获取当前请求IP地址
-     *
-     * @return String IP地址
-     */
-    public static String getCurrentRequestIpAddress() {
-        OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) getOAuth2Authentication().getDetails();
-        return details.getRemoteAddress();
-    }
-
     private static OAuth2Authentication getOAuth2Authentication() {
         Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
         return (OAuth2Authentication) authentication;

+ 0 - 19
febs-common/src/main/java/cc/mrbird/febs/common/utils/HttpContextUtil.java

@@ -1,19 +0,0 @@
-package cc.mrbird.febs.common.utils;
-
-import org.springframework.web.context.request.RequestContextHolder;
-import org.springframework.web.context.request.ServletRequestAttributes;
-
-import javax.servlet.http.HttpServletRequest;
-import java.util.Objects;
-
-/**
- * 用于获取 HTTP请求上下文
- *
- * @author MrBird
- */
-public class HttpContextUtil {
-
-    public static HttpServletRequest getHttpServletRequest() {
-        return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
-    }
-}

+ 0 - 32
febs-common/src/main/java/cc/mrbird/febs/common/utils/ServletRequestIPUtil.java

@@ -1,32 +0,0 @@
-package cc.mrbird.febs.common.utils;
-
-import javax.servlet.http.HttpServletRequest;
-
-/**
- * @author MrBird
- */
-public class ServletRequestIPUtil {
-
-	private static final String UNKNOWN = "unknown";
-
-	/**
-	 * 获取 IP地址
-	 * 使用 Nginx等反向代理软件, 则不能通过 request.getRemoteAddr()获取 IP地址
-	 * 如果使用了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP地址,
-	 * X-Forwarded-For中第一个非 unknown的有效IP字符串,则为真实IP地址
-	 */
-	public static String getIpAddr(HttpServletRequest request) {
-		String ip = request.getHeader("x-forwarded-for");
-		if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
-			ip = request.getHeader("Proxy-Client-IP");
-		}
-		if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
-			ip = request.getHeader("WL-Proxy-Client-IP");
-		}
-		if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
-			ip = request.getRemoteAddr();
-		}
-		return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
-	}
-
-}

+ 0 - 5
febs-server/febs-server-system/pom.xml

@@ -16,11 +16,6 @@
     <description>FEBS-Server-System微服务系统模块</description>
 
     <dependencies>
-        <dependency>
-            <groupId>org.lionsoul</groupId>
-            <artifactId>ip2region</artifactId>
-            <version>1.7</version>
-        </dependency>
         <dependency>
             <groupId>io.springfox</groupId>
             <artifactId>springfox-swagger2</artifactId>

+ 3 - 7
febs-server/febs-server-system/src/main/java/cc/mrbird/febs/server/system/aspect/ControllerEndpointAspect.java

@@ -10,9 +10,6 @@ import org.aspectj.lang.annotation.Around;
 import org.aspectj.lang.annotation.Aspect;
 import org.aspectj.lang.annotation.Pointcut;
 import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.security.core.context.SecurityContextHolder;
-import org.springframework.security.oauth2.provider.OAuth2Authentication;
-import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
 import org.springframework.stereotype.Component;
 
 import java.lang.reflect.Method;
@@ -41,10 +38,9 @@ public class ControllerEndpointAspect extends AspectSupport {
         try {
             result = point.proceed();
             if (StringUtils.isNotBlank(operation)) {
-                OAuth2Authentication authentication = (OAuth2Authentication) SecurityContextHolder.getContext().getAuthentication();
-                OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) authentication.getDetails();
-                String username = (String) authentication.getPrincipal();
-                logService.saveLog(point, targetMethod, details.getRemoteAddress(), operation, username, start);
+                String username = FebsUtil.getCurrentUsername();
+                String ip = FebsUtil.getHttpServletRequestIpAddress();
+                logService.saveLog(point, targetMethod, ip, operation, username, start);
             }
             return result;
         } catch (Throwable throwable) {

+ 3 - 6
febs-server/febs-server-system/src/main/java/cc/mrbird/febs/server/system/service/impl/LoginLogServiceImpl.java

@@ -4,12 +4,11 @@ import cc.mrbird.febs.common.entity.QueryRequest;
 import cc.mrbird.febs.common.entity.constant.FebsConstant;
 import cc.mrbird.febs.common.entity.system.LoginLog;
 import cc.mrbird.febs.common.entity.system.SystemUser;
-import cc.mrbird.febs.common.utils.HttpContextUtil;
-import cc.mrbird.febs.common.utils.ServletRequestIPUtil;
+import cc.mrbird.febs.common.utils.AddressUtil;
+import cc.mrbird.febs.common.utils.FebsUtil;
 import cc.mrbird.febs.common.utils.SortUtil;
 import cc.mrbird.febs.server.system.mapper.LoginLogMapper;
 import cc.mrbird.febs.server.system.service.ILoginLogService;
-import cc.mrbird.febs.server.system.utils.AddressUtil;
 import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
 import com.baomidou.mybatisplus.core.metadata.IPage;
 import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
@@ -19,7 +18,6 @@ import org.springframework.stereotype.Service;
 import org.springframework.transaction.annotation.Propagation;
 import org.springframework.transaction.annotation.Transactional;
 
-import javax.servlet.http.HttpServletRequest;
 import java.util.Arrays;
 import java.util.Date;
 import java.util.List;
@@ -55,8 +53,7 @@ public class LoginLogServiceImpl extends ServiceImpl<LoginLogMapper, LoginLog> i
     @Transactional
     public void saveLoginLog(LoginLog loginLog) {
         loginLog.setLoginTime(new Date());
-        HttpServletRequest request = HttpContextUtil.getHttpServletRequest();
-        String ip = ServletRequestIPUtil.getIpAddr(request);
+        String ip = FebsUtil.getHttpServletRequestIpAddress();
         loginLog.setIp(ip);
         loginLog.setLocation(AddressUtil.getCityInfo(ip));
         this.save(loginLog);

+ 1 - 1
febs-server/febs-server-test/src/main/java/cc/mrbird/febs/server/test/controller/TestController.java

@@ -41,7 +41,7 @@ public class TestController {
         map.put("currentUsername", FebsUtil.getCurrentUsername());
         map.put("currentUserAuthority", FebsUtil.getCurrentUserAuthority());
         map.put("currentTokenValue", FebsUtil.getCurrentTokenValue());
-        map.put("currentRequestIpAddress", FebsUtil.getCurrentRequestIpAddress());
+        map.put("currentRequestIpAddress", FebsUtil.getHttpServletRequestIpAddress());
         return map;
     }
 }