Skip to content

Commit

Permalink
fix: change oss from public read to private
Browse files Browse the repository at this point in the history
  • Loading branch information
Pleasurecruise committed Nov 21, 2024
1 parent 0a0cd65 commit 46e5a5c
Show file tree
Hide file tree
Showing 23 changed files with 220 additions and 110 deletions.
3 changes: 2 additions & 1 deletion backend/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
<commons.lang>2.6</commons.lang>
<druid>1.2.1</druid>
<pagehelper>1.3.0</pagehelper>
<aliyun.sdk.oss>3.10.2</aliyun.sdk.oss>
<aliyun.sdk.oss>3.16.3</aliyun.sdk.oss>
<knife4j>3.0.2</knife4j>
<aspectj>1.9.4</aspectj>
<jjwt>0.9.1</jjwt>
Expand Down Expand Up @@ -98,6 +98,7 @@
<artifactId>aliyun-sdk-oss</artifactId>
<version>${aliyun.sdk.oss}</version>
</dependency>

<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
Expand Down
8 changes: 7 additions & 1 deletion backend/wall-common/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.16.3</version>
<version>3.17.4</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
Expand All @@ -59,6 +59,7 @@
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.17.4</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
Expand All @@ -75,5 +76,10 @@
<artifactId>spring-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.17.4</version>
</dependency>
</dependencies>
</project>
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
package cn.yiming1234.NottinghamWall.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyun.oss.*;
import com.aliyun.oss.common.comm.SignVersion;

import com.aliyun.oss.model.CannedAccessControlList;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
Expand All @@ -13,6 +12,9 @@
import java.net.URL;
import java.util.Date;

/**
* 阿里云OSS工具类
*/
@Data
@AllArgsConstructor
@Slf4j
Expand All @@ -34,6 +36,7 @@ public String upload(byte[] bytes, String objectName) {

try {
ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(bytes));
ossClient.setBucketAcl(bucketName, CannedAccessControlList.Private);
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
Expand All @@ -52,21 +55,17 @@ public String upload(byte[] bytes, String objectName) {
}
}

StringBuilder stringBuilder = new StringBuilder("https://");
stringBuilder
.append(bucketName)
.append(".")
.append(endpoint)
.append("/")
.append(objectName);
Date expiration = new Date(new Date().getTime() + 3600 * 1000L);
URL url = ossClient.generatePresignedUrl(bucketName, objectName, expiration);

log.info("文件上传到:{}", stringBuilder);
log.info("文件上传到:{}", url);

return stringBuilder.toString();
return url.toString();
}

/**
* 文件删除
* @param objectName 文件名
*/
public void delete(String objectName) {
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
Expand Down Expand Up @@ -95,24 +94,25 @@ public void delete(String objectName) {
/**
* 生成文件访问URL
* @param objectName 文件名
* @param expiration 过期时间(毫秒)
* @return 文件访问URL
*/
public String generatePresignedUrl(String objectName, long expiration) {
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
public String generatePresignedUrl(String objectName) {
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret, clientBuilderConfiguration);

try {
Date expirationDate = new Date(System.currentTimeMillis() + expiration);
GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, objectName);
request.setExpiration(expirationDate);
URL signedUrl = ossClient.generatePresignedUrl(request);
return signedUrl.toString();
} catch (Exception e) {
log.error("生成签名URL失败: {}", e.getMessage());
return null;
Date expiration = new Date(new Date().getTime() + 3600 * 1000L);
URL url = ossClient.generatePresignedUrl(bucketName, objectName, expiration);
log.info("File access URL: {}", url);
return url.toString();
} catch (OSSException oe) {
log.error("Caught an OSSException: {}", oe.getErrorMessage());
} catch (ClientException ce) {
log.error("Caught a ClientException: {}", ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
ossClient.shutdown();
}
return null;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
import java.util.Map;

/**
* 内容安全性检测工具类
* 微信内容安全性检测工具类
*/
@Data
@Slf4j
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@
import java.util.Map;
import java.util.UUID;

/**
* 阿里云图片内容审核工具类
*/
@Slf4j
public class ImageCheckUtil {

Expand Down Expand Up @@ -42,7 +45,7 @@ public static ImageModerationResponse invokeFunction(String accessKeyId, String
response = client.imageModerationWithOptions(request, runtime);
log.info("response:{}", response.toString());
} catch (Exception e) {
e.printStackTrace();
log.error("invoke function error:{}", e.getMessage());
}
return response;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,4 @@ public class Topic implements Serializable {
private LocalDateTime updatedAt;
private Boolean isDraft;

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import cn.yiming1234.NottinghamWall.result.PageResult;
import cn.yiming1234.NottinghamWall.result.Result;
import cn.yiming1234.NottinghamWall.service.StudentService;
import com.aliyuncs.exceptions.ClientException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
Expand Down Expand Up @@ -35,7 +36,7 @@ public Result<PageResult> page(PageQueryDTO pageQueryDTO){
*/
@GetMapping("/{id}")
@ApiOperation("根据id查询学生")
public Result<Student> getById(@PathVariable Integer id){
public Result<Student> getById(@PathVariable Integer id) throws ClientException {
Student student = studentService.getById(id);
return Result.success(student);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,6 @@ public CommentController(CommentService commentService, JwtProperties jwtPropert

/**
* 从请求头中提取用户id
* @param request
* @return
*/
private Integer extractUserId(HttpServletRequest request) {
return getaLong(request, jwtProperties);
Expand All @@ -50,15 +48,12 @@ public Result<Void> commentTopic(@PathVariable Integer id, @RequestBody CommentD
log.info("评论话题:{}", id);
Integer userId = extractUserId(request);
commentDTO.setUserId(Math.toIntExact(userId));
commentDTO.setTopicId(Integer.valueOf(id));
commentDTO.setTopicId(id);
commentService.commentTopic(commentDTO);
return Result.success(null);
}

/**
* 回复评论
*/
// TODO
// TODO 回复评论

/**
* 删除评论
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,8 @@ public Result<List<String>> upload(@RequestParam("files") MultipartFile[] files)
compressedBytes = file.getBytes();
}
String objectName = UUID.randomUUID() + extension;
String filePath = aliOssUtil.upload(compressedBytes, objectName);
aliOssUtil.upload(compressedBytes, objectName);
String filePath = aliOssUtil.generatePresignedUrl(objectName);
filePaths.add(filePath);
log.info("图片上传成功: {}", filePath);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import cn.yiming1234.NottinghamWall.service.StudentService;
import cn.yiming1234.NottinghamWall.utils.JwtUtil;
import cn.yiming1234.NottinghamWall.vo.StudentLoginVO;
import com.aliyuncs.exceptions.ClientException;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
Expand All @@ -22,7 +23,6 @@
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/student")
Expand Down Expand Up @@ -100,7 +100,7 @@ public Result<Map<String, Object>> getCurrentUserInfo(HttpServletRequest request
*/
@ApiOperation(value = "获取学生信息")
@GetMapping("/get/info")
public Result<Student> getStudentInfo(HttpServletRequest request) {
public Result<Student> getStudentInfo(HttpServletRequest request) throws ClientException {
Integer id = getCurrentStudentId(request);
Student student = studentService.getById(id);
return Result.success(student);
Expand All @@ -111,7 +111,7 @@ public Result<Student> getStudentInfo(HttpServletRequest request) {
*/
@ApiOperation(value = "根据id获取学生信息")
@GetMapping("/get/info/{id}")
public Result<Student> getStudentInfoById(@PathVariable Integer id) {
public Result<Student> getStudentInfoById(@PathVariable Integer id) throws ClientException {
log.info("根据id获取学生信息:{}", id);
Student student = studentService.getById(id);
return Result.success(student);
Expand All @@ -133,7 +133,7 @@ public Result<Student> getStudentInfoByUsername(@PathVariable String username) {
*/
@ApiOperation(value = "更新学生信息")
@PutMapping("/update/info")
public Result update(@RequestBody StudentDTO studentDTO, HttpServletRequest request) throws Exception {
public Result<Void> update(@RequestBody StudentDTO studentDTO, HttpServletRequest request) throws Exception {
Integer id = getCurrentStudentId(request);
Student student = studentService.getById(id);
log.info("当前学生信息:{}", student);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/student")
Expand Down Expand Up @@ -68,6 +69,13 @@ static Integer getaLong(HttpServletRequest request, JwtProperties jwtProperties,
public Result<Void> createTopic(@RequestBody TopicDTO topicDTO, HttpServletRequest request) throws Exception {
Integer userId = Math.toIntExact(extractUserId(request));
topicDTO.setAuthorID(userId);

List<String> imgURLs = topicDTO.getImgURLs();
List<String> imgNames = imgURLs.stream()
.map(url -> url.substring(url.lastIndexOf("/") + 1, url.indexOf("?")))
.collect(Collectors.toList());
topicDTO.setImgURLs(imgNames);

topicService.addTopic(topicDTO);
log.info("提交话题或草稿:{}", topicDTO);
return Result.success(null);
Expand Down Expand Up @@ -145,9 +153,9 @@ public Result<Boolean> isExistDraft(HttpServletRequest request) {
*/
@GetMapping("/get/topic")
@ApiOperation(value = "实现话题无限滚动")
public Result<PageResult> getTopic(PageQueryDTO pageQueryDTO) {
public Result<PageResult<Topic>> getTopic(PageQueryDTO pageQueryDTO) {
log.info("获取话题列表:{}", pageQueryDTO);
PageResult pageResult = topicService.pageQuery(pageQueryDTO);
PageResult<Topic> pageResult = topicService.pageQuery(pageQueryDTO);
return Result.success(pageResult);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import cn.yiming1234.NottinghamWall.entity.Student;
import cn.yiming1234.NottinghamWall.entity.Topic;
import cn.yiming1234.NottinghamWall.result.PageResult;
import com.aliyuncs.exceptions.ClientException;

import java.io.IOException;

Expand All @@ -27,7 +28,7 @@ public interface StudentService {
* 分页查询学生
* @param pageQueryDTO 分页查询条件
*/
PageResult pageQuery(PageQueryDTO pageQueryDTO);
PageResult<Student> pageQuery(PageQueryDTO pageQueryDTO);

/**
* 更新学生信息
Expand All @@ -45,7 +46,7 @@ public interface StudentService {
* 根据id查询学生
* @param id 学生id
*/
Student getById(Integer id);
Student getById(Integer id) throws ClientException;

/**
* 根据用户名查询学生
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public interface TopicService {
* 分页查询话题
* @param pageQueryDTO 分页查询DTO
*/
PageResult pageQuery(PageQueryDTO pageQueryDTO);
PageResult<Topic> pageQuery(PageQueryDTO pageQueryDTO);

/**
* 根据id获取话题
Expand Down
Loading

0 comments on commit 46e5a5c

Please sign in to comment.