refactor(biji-houdaun): 重构用户认证方法并添加安全工具类

- 将 MarkdownController 中的 isUserAuthenticated 方法移至 SecurityUtil 工具类- 在 SecurityUtil 中添加以下新方法:
  - getCurrentUsername - getCurrentUserDetails
  - hasRole
  - hasPermission - isAdmin
- 更新 MarkdownController 中的相关调用,使用 SecurityUtil 的静态方法
This commit is contained in:
2025-08-06 15:22:00 +08:00
parent 4d2f65c23f
commit 67f189995e
2 changed files with 121 additions and 19 deletions

View File

@@ -5,14 +5,12 @@ import com.test.bijihoudaun.common.response.R;
import com.test.bijihoudaun.entity.MarkdownFile;
import com.test.bijihoudaun.entity.MarkdownFileVO;
import com.test.bijihoudaun.service.MarkdownFileService;
import com.test.bijihoudaun.util.SecurityUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;
import java.util.Date;
@@ -40,7 +38,7 @@ public class MarkdownController {
@GetMapping("/{id}")
public R<String> getMarkdownContent(@PathVariable Long id) {
// 获取当前认证状态
boolean isAuthenticated = isUserAuthenticated();
boolean isAuthenticated = SecurityUtil.isUserAuthenticated();
MarkdownFile file = markdownFileService.getMarkdownById(id, isAuthenticated);
if (ObjectUtil.isNotNull(file)) {
@@ -113,19 +111,4 @@ public class MarkdownController {
return R.success(files);
}
/**
* 检查用户是否已认证
* @return 是否已认证
*/
private boolean isUserAuthenticated() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null || !authentication.isAuthenticated()) {
return false;
}
Object principal = authentication.getPrincipal();
if (principal instanceof UserDetails) {
return true;
}
return false;
}
}