Pārlūkot izejas kodu

添加 AliyunController

reghao 5 mēneši atpakaļ
vecāks
revīzija
2fbb390d59

+ 5 - 0
web/pom.xml

@@ -255,6 +255,11 @@
             <artifactId>cdn20180510</artifactId>
             <version>3.2.0</version>
         </dependency>
+        <dependency>
+            <groupId>com.aliyun</groupId>
+            <artifactId>sts20150401</artifactId>
+            <version>1.1.4</version>
+        </dependency>
     </dependencies>
 
     <profiles>

+ 25 - 1
web/src/main/java/cn/reghao/bnt/web/devops/aliyun/controller/AliyunController.java

@@ -1,13 +1,21 @@
 package cn.reghao.bnt.web.devops.aliyun.controller;
 
+import cn.reghao.bnt.web.devops.aliyun.model.dto.GetSignedUrl;
 import cn.reghao.bnt.web.devops.aliyun.model.po.AliyunAccount;
+import cn.reghao.bnt.web.devops.aliyun.model.vo.StsToken;
 import cn.reghao.bnt.web.devops.aliyun.service.AliyunAccountService;
+import cn.reghao.bnt.web.devops.aliyun.service.AliyunService;
+import cn.reghao.jutil.web.WebResult;
 import io.swagger.v3.oas.annotations.tags.Tag;
 import io.swagger.v3.oas.annotations.Operation;
 import org.springframework.data.domain.Page;
+import org.springframework.http.MediaType;
 import org.springframework.stereotype.Controller;
 import org.springframework.ui.Model;
+import org.springframework.validation.annotation.Validated;
 import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
 import org.springframework.web.bind.annotation.RequestMapping;
 
 /**
@@ -19,9 +27,11 @@ import org.springframework.web.bind.annotation.RequestMapping;
 @RequestMapping("/bg/machine/aliyun")
 public class AliyunController {
     private final AliyunAccountService aliyunAccountService;
+    private final AliyunService aliyunService;
 
-    public AliyunController(AliyunAccountService aliyunAccountService) {
+    public AliyunController(AliyunAccountService aliyunAccountService, AliyunService aliyunService) {
         this.aliyunAccountService = aliyunAccountService;
+        this.aliyunService = aliyunService;
     }
 
     @Operation(summary = "阿里云 key 页面", description = "N")
@@ -33,4 +43,18 @@ public class AliyunController {
         model.addAttribute("list", page.getContent());
         return "/admin/devops/aliyun/key_list";
     }
+
+    @Operation(summary = "获取阿里云 sts token", description = "N")
+    @PostMapping(value = "/sts_token", produces = MediaType.APPLICATION_JSON_VALUE)
+    public String getUploadStore() {
+        StsToken stsToken = aliyunService.getStsToken();
+        return WebResult.success(stsToken);
+    }
+
+    @Operation(summary = "获取阿里云 oss 签名 url", description = "N")
+    @PostMapping(value = "/signed_url", produces = MediaType.APPLICATION_JSON_VALUE)
+    public String getSignedUrl(@RequestBody @Validated GetSignedUrl getSignedUrl) {
+        String signedUrl = aliyunService.getSignedUrl(getSignedUrl.getObjectName());
+        return WebResult.success(signedUrl);
+    }
 }

+ 17 - 0
web/src/main/java/cn/reghao/bnt/web/devops/aliyun/model/dto/GetSignedUrl.java

@@ -0,0 +1,17 @@
+package cn.reghao.bnt.web.devops.aliyun.model.dto;
+
+import lombok.Getter;
+import lombok.Setter;
+
+import javax.validation.constraints.NotBlank;
+
+/**
+ * @author reghao
+ * @date 2024-08-30 17:06:36
+ */
+@Setter
+@Getter
+public class GetSignedUrl {
+    @NotBlank
+    private String objectName;
+}

+ 2 - 0
web/src/main/java/cn/reghao/bnt/web/devops/aliyun/model/po/AliyunAccount.java

@@ -32,4 +32,6 @@ public class AliyunAccount extends BaseEntity {
     @Column(nullable = false, unique = true)
     private String type;
     private String bucketName;
+    private String region;
+    private String roleArn;
 }

+ 21 - 0
web/src/main/java/cn/reghao/bnt/web/devops/aliyun/model/vo/StsToken.java

@@ -0,0 +1,21 @@
+package cn.reghao.bnt.web.devops.aliyun.model.vo;
+
+import lombok.AllArgsConstructor;
+import lombok.Getter;
+
+/**
+ * @author reghao
+ * @date 2024-08-30 14:33:22
+ */
+@AllArgsConstructor
+@Getter
+public class StsToken {
+    private String bucket;
+    private String region;
+    private String ossUrl;
+    private String objectId;
+    private String accessKeyId;
+    private String accessKeySecret;
+    private String expiration;
+    private String securityToken;
+}

+ 12 - 0
web/src/main/java/cn/reghao/bnt/web/devops/aliyun/service/AliyunOss.java

@@ -11,12 +11,14 @@ import org.springframework.stereotype.Component;
 import javax.annotation.PostConstruct;
 import java.io.File;
 import java.io.IOException;
+import java.net.URL;
 import java.nio.file.FileVisitResult;
 import java.nio.file.FileVisitor;
 import java.nio.file.Files;
 import java.nio.file.Path;
 import java.nio.file.attribute.BasicFileAttributes;
 import java.util.ArrayList;
+import java.util.Date;
 import java.util.List;
 
 /**
@@ -28,9 +30,11 @@ import java.util.List;
 public class AliyunOss {
     private OSS ossClient;
     private final AliyunAccountRepository aliyunAccountRepository;
+    private String bucketName;
 
     public AliyunOss(AliyunAccountRepository aliyunAccountRepository) {
         this.aliyunAccountRepository = aliyunAccountRepository;
+        this.bucketName = "";
     }
 
     @PostConstruct
@@ -143,6 +147,14 @@ public class AliyunOss {
         } while (objectListing.isTruncated());
     }
 
+    public String getSignedUrl(String objectName) {
+        int expireSecond = 3600;
+        long timestamp = System.currentTimeMillis() + expireSecond*1000L;
+        Date expiration = new Date(timestamp);
+        URL url = ossClient.generatePresignedUrl(bucketName, objectName, expiration);
+        return url.toString();
+    }
+
     public void close() {
         ossClient.shutdown();
     }

+ 90 - 0
web/src/main/java/cn/reghao/bnt/web/devops/aliyun/service/AliyunService.java

@@ -0,0 +1,90 @@
+package cn.reghao.bnt.web.devops.aliyun.service;
+
+import cn.reghao.bnt.web.devops.aliyun.model.po.AliyunAccount;
+import cn.reghao.bnt.web.devops.aliyun.model.vo.StsToken;
+import com.aliyun.sts20150401.models.AssumeRoleResponse;
+import com.aliyun.sts20150401.models.AssumeRoleResponseBody;
+import com.aliyun.tea.TeaException;
+import org.springframework.stereotype.Service;
+
+import java.util.UUID;
+
+/**
+ * @author reghao
+ * @date 2024-08-30 14:31:24
+ */
+@Service
+public class AliyunService {
+    private AliyunOss aliyunOss;
+    private com.aliyun.sts20150401.Client stsClient;
+    private String bucket;
+    private String region;
+    private String roleArn;
+    private String ossDomain;
+    private String myDomain;
+
+    // TODO 使用 AliyunService 前需要先调用 AliyunService#init 初始化
+    public void init(AliyunOss aliyunOss, AliyunAccount aliyunAccount) throws Exception {
+        this.aliyunOss = aliyunOss;
+        String stsEndpoint = aliyunAccount.getEndpoint();
+        String accessKeyId = aliyunAccount.getAccessKeyId();
+        String accessKeySecret = aliyunAccount.getAccessKeySecret();
+        this.bucket = aliyunAccount.getBucketName();
+        this.region = aliyunAccount.getRegion();
+        this.roleArn = aliyunAccount.getRoleArn();
+        this.ossDomain = String.format("%s.%s.aliyuncs.com", bucket, region);
+        this.myDomain = System.getenv("MY_DOMAIN");
+
+        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
+                .setAccessKeyId(accessKeyId)
+                .setAccessKeySecret(accessKeySecret);
+        config.endpoint = stsEndpoint;
+        this.stsClient = new com.aliyun.sts20150401.Client(config);
+    }
+
+    public StsToken getStsToken() {
+        com.aliyun.sts20150401.models.AssumeRoleRequest assumeRoleRequest = new com.aliyun.sts20150401.models.AssumeRoleRequest();
+        assumeRoleRequest.setRoleArn(roleArn);
+        assumeRoleRequest.setRoleSessionName("role_session_test");
+        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
+        try {
+            // 复制代码运行请自行打印 API 的返回值
+            AssumeRoleResponse roleResponse = stsClient.assumeRoleWithOptions(assumeRoleRequest, runtime);
+            AssumeRoleResponseBody.AssumeRoleResponseBodyCredentials credentials = roleResponse.getBody().getCredentials();
+            String accessKeyId = credentials.getAccessKeyId();
+            String accessKeySecret = credentials.getAccessKeySecret();
+            String expiration = credentials.getExpiration();
+            String securityToken = credentials.getSecurityToken();
+
+            String ossUrl = String.format("http://%s.%s.aliyuncs.com/", bucket, region);
+            String objectId = UUID.randomUUID().toString().replace("-", "");
+            return new StsToken(bucket, region, ossUrl, objectId, accessKeyId, accessKeySecret, expiration, securityToken);
+        } catch (TeaException error) {
+            // 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。
+            // 错误 message
+            System.out.println(error.getMessage());
+            // 诊断地址
+            System.out.println(error.getData().get("Recommend"));
+            com.aliyun.teautil.Common.assertAsString(error.message);
+        } catch (Exception _error) {
+            TeaException error = new TeaException(_error.getMessage(), _error);
+            // 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。
+            // 错误 message
+            System.out.println(error.getMessage());
+            // 诊断地址
+            System.out.println(error.getData().get("Recommend"));
+            com.aliyun.teautil.Common.assertAsString(error.message);
+        }
+
+        return null;
+    }
+
+    public String getSignedUrl(String objectName) {
+        String signedUrl = aliyunOss.getSignedUrl(objectName);
+        if (signedUrl != null) {
+            return signedUrl.replace(ossDomain, myDomain);
+        }
+
+        return null;
+    }
+}

+ 0 - 4
web/src/test/java/RbacTest.java

@@ -11,7 +11,6 @@ import cn.reghao.bnt.web.admin.service.AccountSessionService;
 import cn.reghao.bnt.web.admin.service.MenuService;
 import cn.reghao.bnt.web.blog.controller.ForegroundController;
 import cn.reghao.bnt.web.config.web.exception.ControllerErrorHandler;
-import cn.reghao.bnt.web.console.controller.OssSdkController;
 import io.swagger.v3.oas.annotations.Operation;
 import lombok.extern.slf4j.Slf4j;
 import org.junit.jupiter.api.Test;
@@ -92,9 +91,6 @@ public class RbacTest {
             } else if (className.equals(ForegroundController.class.getName())) {
                 log.info("skip ForegroundController");
                 continue;
-            } else if (className.equals(OssSdkController.class.getName())) {
-                log.info("skip OssSdkController");
-                continue;
             } else if (className.equals(ControllerErrorHandler.class.getName())) {
                 log.info("skip ControllerErrorHandler");
                 continue;