zhanghaijun 2 gadi atpakaļ
vecāks
revīzija
c0848de3c7

+ 1 - 0
.gitignore

@@ -2,6 +2,7 @@
 /store/
 /train-server/store
 target/
+**/license.*
 
 **/logs
 !.mvn/wrapper/maven-wrapper.jar

+ 14 - 2
train-common/train-common-core/src/main/java/top/haijunit/common/config/RunnerLog.java

@@ -38,9 +38,13 @@ public class RunnerLog implements ApplicationRunner {
 
                  ========== 启动服务 ==========
                 \t 授权时间已过期,请来及时联系管理员
+                \t 授权机器码:\t%s
                 \t 授权时间至:\t%s
                 \t 授权已过期:\t%s天
-                 ============================""", licenseOptional.map(LicenseService::getLicenseUntilStr).orElse(""), licenseOptional.map(LicenseService::licenseRemaining).orElse(0L)));
+                 ============================""",
+                licenseOptional.map(LicenseService::getMachineStr).orElse(""),
+                licenseOptional.map(LicenseService::getLicenseUntilStr).orElse(""),
+                licenseOptional.map(LicenseService::licenseRemaining).orElse(0L)));
             System.exit(SpringApplication.exit(ctx));
         }
         String appJvmName = ManagementFactory.getRuntimeMXBean().getName();
@@ -52,12 +56,20 @@ public class RunnerLog implements ApplicationRunner {
 
              ========== 启动服务 ==========
             \t 服务名称:\t%s
+            \t 授权机器码:\t%s
             \t 授权时间至:\t%s
             \t 授权剩余:\t%s天
             \t 进程ID: \t%s
             \t 启动时间:\t%s
             \t 访问路径:\t%s
-             ============================""", ctx.getEnvironment().getProperty("spring.application.name"), licenseOptional.map(LicenseService::getLicenseUntilStr).orElse(""), licenseOptional.map(LicenseService::licenseRemaining).orElse(0L), appJvmName.split("@")[0], DateUtil.format(new Date(ctx.getStartupDate()), DatePattern.NORM_DATETIME_MS_PATTERN), httpUrl);
+             ============================""",
+            ctx.getEnvironment().getProperty("spring.application.name"),
+            licenseOptional.map(LicenseService::getMachineStr).orElse(""),
+            licenseOptional.map(LicenseService::getLicenseUntilStr).orElse(""),
+            licenseOptional.map(LicenseService::licenseRemaining).orElse(0L),
+            appJvmName.split("@")[0],
+            DateUtil.format(new Date(ctx.getStartupDate()), DatePattern.NORM_DATETIME_MS_PATTERN),
+            httpUrl);
         log.info("\033[1;33m {} \033[0m", format);
     }
 

+ 25 - 5
train-common/train-common-core/src/main/java/top/haijunit/common/domain/LicenseService.java

@@ -1,6 +1,8 @@
 package top.haijunit.common.domain;
 
 import cn.hutool.core.date.DateUtil;
+import cn.hutool.http.HttpStatus;
+import top.haijunit.common.exception.ServiceException;
 
 import java.util.Date;
 import java.util.Optional;
@@ -14,19 +16,37 @@ public interface LicenseService {
 
     LicenseItem getLicenseItem();
 
+    String getMachineStr();
+
     default Date getLicenseUntil() {
-        return Optional.of(this.getLicenseItem()).map(item -> new Date(item.getTime())).orElse(new Date());
+        LicenseItem licenseItem = this.getLicenseItem();
+        if (licenseItem != null) {
+            return new Date(licenseItem.getTime());
+        }
+        throw new ServiceException(HttpStatus.HTTP_UNAUTHORIZED, "license无效,请联系管理员");
     }
 
     default boolean licenseExpired() {
-        return DateUtil.compare(DateUtil.date(), getLicenseUntil()) > 0;
+        try {
+            return DateUtil.compare(DateUtil.date(), getLicenseUntil()) > 0;
+        } catch (Exception exception) {
+            return true;
+        }
     }
 
     default String getLicenseUntilStr() {
-        return DateUtil.formatDateTime(getLicenseUntil());
+        try {
+            return DateUtil.formatDateTime(getLicenseUntil());
+        } catch (Exception exception) {
+            return "";
+        }
     }
 
-    default long licenseRemaining() {
-        return DateUtil.betweenDay(getLicenseUntil(), DateUtil.date(), true);
+    default Long licenseRemaining() {
+        try {
+            return DateUtil.betweenDay(getLicenseUntil(), DateUtil.date(), true);
+        } catch (Exception exception) {
+            return null;
+        }
     }
 }

+ 10 - 6
train-server/src/main/java/top/haijunit/train/service/LicenseServiceImpl.java

@@ -1,9 +1,9 @@
 package top.haijunit.train.service;
 
 import cn.hutool.core.convert.Convert;
-import cn.hutool.core.date.DateUtil;
 import cn.hutool.core.io.FileUtil;
 import cn.hutool.core.util.StrUtil;
+import cn.hutool.http.HttpStatus;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.cache.annotation.CacheEvict;
 import org.springframework.cache.annotation.Cacheable;
@@ -11,6 +11,7 @@ import org.springframework.stereotype.Service;
 import top.haijunit.common.domain.LicenseItem;
 import top.haijunit.common.domain.LicenseService;
 import top.haijunit.common.domain.ResultData;
+import top.haijunit.common.exception.ServiceException;
 import top.haijunit.train.domain.constant.CacheNames;
 import top.haijunit.train.utils.LicenseUtil;
 
@@ -31,10 +32,14 @@ public class LicenseServiceImpl implements LicenseService {
      * 获取机器码+校验位
      * @return 机器码+校验位
      */
+    @Override
     @Cacheable(cacheNames = CacheNames.LICENSE, key = "'MachineStr'")
     public String getMachineStr() {
         String machineCode = getMachineCode();
-        return machineCode + LicenseUtil.MARK + LicenseUtil.generateCheckKey(machineCode);
+        String machineStr = machineCode + LicenseUtil.MARK + LicenseUtil.generateCheckKey(machineCode);
+        // 将机器码写入到文件中
+        FileUtil.writeUtf8String(machineStr, new File(LicenseUtil.LICENSE_MACHINE));
+        return machineStr;
     }
 
     @Cacheable(cacheNames = CacheNames.LICENSE, key = "'MachineCode'")
@@ -54,11 +59,11 @@ public class LicenseServiceImpl implements LicenseService {
             String licenseStr = FileUtil.readUtf8String(file);
             String string = LicenseUtil.licenseDecrypt(StrUtil.trim(licenseStr));
             String machine = StrUtil.subBefore(string, LicenseUtil.SEPARATOR, false);
-            if (StrUtil.equalsAnyIgnoreCase(machine, this.getMachineCode())) {
-                return new LicenseItem(machine, Convert.toLong(StrUtil.subAfter(string, LicenseUtil.SEPARATOR, false), 0L));
+            if (StrUtil.isBlank(machine) || StrUtil.equalsAnyIgnoreCase(machine, this.getMachineCode())) {
+                return new LicenseItem(this.getMachineCode(), Convert.toLong(StrUtil.subAfter(string, LicenseUtil.SEPARATOR, false), 0L));
             }
         }
-        return new LicenseItem(this.getMachineCode(), DateUtil.current());
+        throw new ServiceException(HttpStatus.HTTP_UNAUTHORIZED, "license无效,请联系管理员");
     }
 
     // 校验授权码
@@ -86,5 +91,4 @@ public class LicenseServiceImpl implements LicenseService {
         log.info("授权码写入文件:{}", file.getAbsoluteFile());
         return ResultData.success(machineStr);
     }
-
 }

+ 1 - 0
train-server/src/main/java/top/haijunit/train/utils/LicenseUtil.java

@@ -27,6 +27,7 @@ public class LicenseUtil {
     public static final String MARK = "+";
     public static final String SEPARATOR = ",";
     public static final String LICENSE_FILE = "license.lic";
+    public static final String LICENSE_MACHINE = "license.code";
 
     /**
      * license加密

+ 8 - 24
train-server/src/test/java/top/haijunit/train/test/LicenseTest.java

@@ -1,49 +1,33 @@
 package top.haijunit.train.test;
 
 
-import java.util.Arrays;
-import java.util.Date;
-import java.util.List;
-
 import cn.hutool.core.date.DatePattern;
 import cn.hutool.core.date.DateUtil;
 import cn.hutool.core.util.StrUtil;
 import lombok.extern.slf4j.Slf4j;
 import org.junit.jupiter.api.Assertions;
 import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.DisplayName;
 import org.junit.jupiter.api.Test;
 import org.junit.jupiter.params.ParameterizedTest;
 import org.junit.jupiter.params.provider.CsvSource;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.boot.test.context.SpringBootTest;
 import oshi.SystemInfo;
-import oshi.hardware.Baseboard;
-import oshi.hardware.CentralProcessor;
+import oshi.hardware.*;
 import oshi.hardware.CentralProcessor.TickType;
-import oshi.hardware.ComputerSystem;
-import oshi.hardware.Display;
-import oshi.hardware.Firmware;
-import oshi.hardware.GlobalMemory;
-import oshi.hardware.HWDiskStore;
-import oshi.hardware.HWPartition;
-import oshi.hardware.HardwareAbstractionLayer;
-import oshi.hardware.NetworkIF;
-import oshi.hardware.PowerSource;
-import oshi.hardware.Sensors;
-import oshi.hardware.UsbDevice;
-import oshi.software.os.FileSystem;
-import oshi.software.os.NetworkParams;
-import oshi.software.os.OSFileStore;
-import oshi.software.os.OSProcess;
-import oshi.software.os.OperatingSystem;
+import oshi.software.os.*;
 import oshi.util.FormatUtil;
 import oshi.util.Util;
-import org.junit.jupiter.api.DisplayName;
 import top.haijunit.common.domain.ResultData;
 import top.haijunit.train.TrainServerMain;
 import top.haijunit.train.service.LicenseServiceImpl;
 import top.haijunit.train.utils.LicenseUtil;
 
+import java.util.Arrays;
+import java.util.Date;
+import java.util.List;
+
 /**
  * @author zhanghaijun
  * @date 2023/12/19 21:41
@@ -65,7 +49,7 @@ public class LicenseTest {
 
     @DisplayName("生成授权")
     @ParameterizedTest
-    @CsvSource({"b6f35e941ae79841494fe2e3e7f961a9+876,2024-01-01", "b6f35e941ae79841494fe2e3e7f961a9+876,2024-12-31"})
+    @CsvSource({"'',2024-03-01", "b6f35e941ae79841494fe2e3e7f961a9+876,2024-01-01", "b6f35e941ae79841494fe2e3e7f961a9+876,2024-12-31"})
     void generateLicense(String machineStr, String dateStr) {
         if (machineStr.contains(LicenseUtil.MARK)) {
             String machineCode = StrUtil.subBefore(machineStr, LicenseUtil.MARK, false);