浏览代码

web 模块更改为 restful 服务

reghao 3 月之前
父节点
当前提交
221f2a79e8

+ 6 - 18
web/src/main/java/cn/reghao/bnt/web/admin/controller/AccountPageController.java → web/src/main/java/cn/reghao/bnt/web/admin/controller/AccountController.java

@@ -13,7 +13,6 @@ 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.ui.Model;
 import org.springframework.validation.annotation.Validated;
 import org.springframework.web.bind.annotation.*;
 
@@ -26,15 +25,15 @@ import java.util.List;
 @Tag(name = "用户帐号页面")
 @RestController
 @RequestMapping("/api/devops/account")
-public class AccountPageController {
+public class AccountController {
     private final AccountService accountService;
     private final AccountSessionService accountSessionService;
     private final UserMessageService userMessageService;
     private final LoginAttemptService loginAttemptService;
     private final int pageSize = 10;
 
-    public AccountPageController(AccountService accountService, AccountSessionService accountSessionService,
-                                 UserMessageService userMessageService, LoginAttemptService loginAttemptService) {
+    public AccountController(AccountService accountService, AccountSessionService accountSessionService,
+                             UserMessageService userMessageService, LoginAttemptService loginAttemptService) {
         this.accountService = accountService;
         this.accountSessionService = accountSessionService;
         this.userMessageService = userMessageService;
@@ -42,7 +41,7 @@ public class AccountPageController {
     }
 
     @Operation(summary = "修改帐号", description = "N")
-    @PostMapping(value = "/profile/update/username", produces = MediaType.APPLICATION_JSON_VALUE)
+    @PostMapping(value = "/update/username", produces = MediaType.APPLICATION_JSON_VALUE)
     public String updateUsername(@Validated UpdateUsernameDto updateUsernameDto) {
         Result result = accountService.updateMyUsername(updateUsernameDto);
         if (result.getCode() == ResultStatus.SUCCESS.getCode()) {
@@ -53,7 +52,7 @@ public class AccountPageController {
     }
 
     @Operation(summary = "修改密码", description = "N")
-    @PostMapping(value = "/profile/update/passwd", produces = MediaType.APPLICATION_JSON_VALUE)
+    @PostMapping(value = "/update/passwd", produces = MediaType.APPLICATION_JSON_VALUE)
     public String updatePasswd(@Validated UpdatePasswordDto updatePasswordDto) {
         Result result = accountService.updateMyPassword(updatePasswordDto);
         if (result.getCode() == ResultStatus.SUCCESS.getCode()) {
@@ -65,7 +64,7 @@ public class AccountPageController {
 
     @Operation(summary = "帐号登入记录列表页面", description = "N")
     @GetMapping("/record")
-    public String loginRecordPage(Model model) {
+    public String loginRecordPage() {
         List<LoginRecordInfo> list = loginAttemptService.getActiveLogin();
         return WebResult.success(list);
     }
@@ -93,17 +92,6 @@ public class AccountPageController {
         return PageList.pageList(pageNumber, pageSize, (int) total, list);
     }
 
-    @Operation(summary = "用户消息内容页面", description = "N")
-    @GetMapping("/message/detail")
-    public String messageDetail(@RequestParam("id") int id) {
-        UserMessage userMessage = userMessageService.getMessage(id);
-        String content = "";
-        if (userMessage != null) {
-            content = userMessage.getContent();
-        }
-        return WebResult.success(content);
-    }
-
     @Operation(summary = "删除用户所有消息", description = "N")
     @PostMapping(value = "/message/clear", produces = MediaType.APPLICATION_JSON_VALUE)
     public String clearUserMessage() {

+ 2 - 7
web/src/main/java/cn/reghao/bnt/web/admin/controller/RoleController.java

@@ -51,7 +51,6 @@ public class RoleController {
 
     @Operation(summary = "获取角色可访问的资源", description = "N")
     @GetMapping(value = "/menus", produces = MediaType.APPLICATION_JSON_VALUE)
-    @ResponseBody
     public String getRoleMenus(@RequestParam("id") Role role) {
         List<Integer> roleMenuIds = role.getMenus().stream().map(Menu::getId).collect(Collectors.toList());
         List<ResourceTree> allMenus = menuService.getMenuTreeByRole1(role);
@@ -64,13 +63,9 @@ public class RoleController {
 
     @Operation(summary = "设置角色可访问的资源", description = "N")
     @PostMapping(value = "/menus", produces = MediaType.APPLICATION_JSON_VALUE)
-    @ResponseBody
     public String setRoleMenus(@RequestParam(value = "id") Integer roleId,
-                               @RequestParam(value = "menuId", required = false) Set<Menu> menus) {
-        if (menus == null) {
-            menus = Collections.emptySet();
-        }
-        roleService.updateRoleMenus(roleId, menus);
+                               @RequestParam(value = "menuIds") Set<Integer> menuIds) {
+        roleService.updateRoleMenus(roleId, menuIds);
         return WebResult.success();
     }
 }

+ 2 - 6
web/src/main/java/cn/reghao/bnt/web/admin/controller/SysNotifyController.java

@@ -59,12 +59,8 @@ public class SysNotifyController {
     @PostMapping(value = "/delete", produces = MediaType.APPLICATION_JSON_VALUE)
     public String deleteReceiver(Integer id) {
         Webhook webhook = webhookRepository.getById(id);
-        if (webhook != null) {
-            log.info("delete webhook {}", webhook.getName());
-            //webhookRepository.delete(webhook);
-        }
-
-        return WebResult.failWithMsg("not implement");
+        webhookRepository.delete(webhook);
+        return WebResult.success();
     }
 
     @Operation(summary = "测试 webhook 是否可用", description = "N")

+ 19 - 19
web/src/main/java/cn/reghao/bnt/web/admin/controller/UserController.java

@@ -73,13 +73,6 @@ public class UserController {
         return PageList.pageList(pageNumber, pageSize, (int) total, list);
     }
 
-    @Operation(summary = "新增帐号页面", description = "N")
-    @GetMapping(value = "/add", produces = MediaType.APPLICATION_JSON_VALUE)
-    public String addUserPage() {
-        List<String> allRoles = roleService.getAllRoles().stream().map(RoleVO::getName).collect(Collectors.toList());
-        return WebResult.success(allRoles);
-    }
-
     @Operation(summary = "用户会话列表页面", description = "N")
     @GetMapping("/session")
     public String userSessionPage(@RequestParam("id") Integer userId) {
@@ -103,7 +96,7 @@ public class UserController {
         return WebResult.success(map);
     }
 
-    @Operation(summary = "分配帐号角色", description = "N")
+    @Operation(summary = "修改帐号角色", description = "N")
     @PostMapping(value = "/role", produces = MediaType.APPLICATION_JSON_VALUE)
     public String updateRole(@Validated AccountRole accountRole) {
         Result result = accountService.updateAccountRole(accountRole);
@@ -114,6 +107,24 @@ public class UserController {
         return WebResult.result(result);
     }
 
+    @Operation(summary = "修改帐号密码", description = "N")
+    @PostMapping(value = "/passwd", produces = MediaType.APPLICATION_JSON_VALUE)
+    public String updatePassword(@Validated AccountPassword accountPassword) {
+        int userId = accountPassword.getUserId();
+        String password = accountPassword.getPassword();
+        accountService.updateAccountPassword(userId, password);
+        // 登出当前会话
+        accountSessionService.deactivateUserSession(userId);
+        return WebResult.success();
+    }
+
+    @Operation(summary = "新增帐号页面", description = "N")
+    @GetMapping(value = "/add", produces = MediaType.APPLICATION_JSON_VALUE)
+    public String addUserPage() {
+        List<String> allRoles = roleService.getAllRoles().stream().map(RoleVO::getName).collect(Collectors.toList());
+        return WebResult.success(allRoles);
+    }
+
     @Operation(summary = "创建帐号", description = "N")
     @PostMapping(value = "/add", produces = MediaType.APPLICATION_JSON_VALUE)
     public String createUser(@Validated CreateAccountDto createAccountDto) {
@@ -131,15 +142,4 @@ public class UserController {
         }
         return WebResult.result(result);
     }
-
-    @Operation(summary = "修改帐号密码", description = "N")
-    @PostMapping(value = "/passwd", produces = MediaType.APPLICATION_JSON_VALUE)
-    public String updatePassword(@Validated AccountPassword accountPassword) {
-        int userId = accountPassword.getUserId();
-        String password = accountPassword.getPassword();
-        accountService.updateAccountPassword(userId, password);
-        // 登出当前会话
-        accountSessionService.deactivateUserSession(userId);
-        return WebResult.success();
-    }
 }

+ 5 - 3
web/src/main/java/cn/reghao/bnt/web/admin/model/dto/CreateAccountDto.java

@@ -1,5 +1,6 @@
 package cn.reghao.bnt.web.admin.model.dto;
 
+import jakarta.validation.constraints.Size;
 import lombok.Getter;
 import lombok.Setter;
 import org.hibernate.validator.constraints.Length;
@@ -7,6 +8,8 @@ import org.hibernate.validator.constraints.Length;
 import jakarta.validation.constraints.NotBlank;
 import jakarta.validation.constraints.NotNull;
 
+import java.util.Set;
+
 /**
  * @author reghao
  * @date 2023-10-23 17:38:19
@@ -20,12 +23,11 @@ public class CreateAccountDto {
     @NotNull(message = "密码不能为 null")
     @Length(min = 8, max = 16, message = "密码长度在 8 ~ 16 个字符")
     private String password;
-    @NotNull(message = "必须选择用户角色")
-    private Integer roleId;
+    @Size(min = 1, max = 10, message = "用户角色数量为 1~10")
+    private Set<String> roles;
 
     public CreateAccountDto(String username, String password) {
         this.username = username;
         this.password = password;
-        this.roleId = 1;
     }
 }

+ 13 - 0
web/src/main/java/cn/reghao/bnt/web/admin/model/po/User.java

@@ -47,6 +47,7 @@ public class User extends BaseEntity implements UserDetails {
     private String avatarUrl;
     private String mobile;
 
+    @Deprecated
     public User(String username, String password, String salt, Role role) {
         this.username = username;
         this.encodedPassword = password;
@@ -59,6 +60,18 @@ public class User extends BaseEntity implements UserDetails {
         this.avatarUrl = "/dist/images/avatar.jpg";
     }
 
+    public User(String username, String password, String salt, Set<String> roles) {
+        this.username = username;
+        this.encodedPassword = password;
+        this.salt = salt;
+        this.createAt = LocalDateTime.now();
+        this.role = roles;
+        this.enabled = true;
+        this.locked = false;
+        this.screenName = username;
+        this.avatarUrl = "/dist/images/avatar.jpg";
+    }
+
     @Override
     public String getUsername() {
         return username;

+ 1 - 6
web/src/main/java/cn/reghao/bnt/web/admin/service/RoleService.java

@@ -1,12 +1,7 @@
 package cn.reghao.bnt.web.admin.service;
 
-import cn.reghao.bnt.web.admin.model.po.Menu;
 import cn.reghao.bnt.web.admin.model.po.Role;
-import cn.reghao.bnt.web.admin.model.po.User;
 import cn.reghao.bnt.web.admin.model.vo.RoleVO;
-import cn.reghao.jutil.jdk.web.result.Result;
-import org.springframework.data.domain.Page;
-import org.springframework.data.domain.PageRequest;
 
 import java.util.List;
 import java.util.Set;
@@ -23,7 +18,7 @@ public interface RoleService {
      * @return
      * @date 2025-09-30 20:09:715
      */
-    void updateRoleMenus(Integer roleId, Set<Menu> menus);
+    void updateRoleMenus(Integer roleId, Set<Integer> menuIds);
     List<RoleVO> getAllRoles();
     /**
      * 获取某个用户拥有的所有角色

+ 0 - 30
web/src/main/java/cn/reghao/bnt/web/admin/service/SiteOptionService.java

@@ -31,36 +31,6 @@ public class SiteOptionService {
         return siteOptionRepo.getAll();
     }
 
-    public boolean getCheckDomain() {
-        String propKey = "site.domain.check";
-        String propValue = siteOptionRepo.getPropValue(propKey);
-        return Boolean.parseBoolean(propValue);
-    }
-
-    public String getForegroundDomain() {
-        String propKey = "site.foreground.domain";
-        String propValue = siteOptionRepo.getPropValue(propKey);
-        return propValue;
-    }
-
-    public Set<String> getBackgroundDomain() {
-        String propKey = "site.background.domain";
-        String propValue = siteOptionRepo.getPropValue(propKey);
-        return Arrays.stream(propValue.split(",")).collect(Collectors.toSet());
-    }
-
-    public boolean getAccessLogEnabled() {
-        String propKey = "site.access_log.enabled";
-        String propValue = siteOptionRepo.getPropValue(propKey);
-        return Boolean.parseBoolean(propValue);
-    }
-
-    public boolean getRuntimeLogEnabled() {
-        String propKey = "site.runtime_log.enabled";
-        String propValue = siteOptionRepo.getPropValue(propKey);
-        return Boolean.parseBoolean(propValue);
-    }
-
     public String getDevopsWebhook() {
         String propKey = "site.devops.webhook_name";
         String propValue = siteOptionRepo.getPropValue(propKey);

+ 12 - 6
web/src/main/java/cn/reghao/bnt/web/admin/service/impl/AccountServiceImpl.java

@@ -52,30 +52,36 @@ public class AccountServiceImpl implements AccountService {
 
     @Override
     public Result createAccount(CreateAccountDto createAccountDto) {
-        int roleId = createAccountDto.getRoleId();
-        Role role = roleRepository.findById(roleId).orElse(null);
-        if (role == null) {
+        List<Role> roles = createAccountDto.getRoles().stream()
+                .map(name -> {
+                    String role = "ROLE_" + name.toUpperCase(Locale.ROOT);
+                    return roleRepository.findByName(role);
+                })
+                .filter(Objects::nonNull)
+                .collect(Collectors.toList());
+        if (roles.isEmpty()) {
             return Result.fail("role 不存在");
         }
 
-        if (role.getName().equals(RoleType.ROLE_ADMIN.name())) {
+        String adminRole = RoleType.ROLE_ADMIN.name().replace("ROLE_", "").toLowerCase(Locale.ROOT);
+        if (createAccountDto.getRoles().contains(adminRole)) {
             return Result.fail("只有 admin 用户才能拥有 admin role");
         }
 
+        Set<String> roleNames = roles.stream().map(Role::getName).collect(Collectors.toSet());
         String username = createAccountDto.getUsername();
         User user = userRepository.findByUsername(username);
         if (user == null) {
             String password = createAccountDto.getPassword();
             String salt = RandomString.getSalt(64);
             String encodedPassword = passwordEncoder.encode(password + salt);
-            user = new User(username, encodedPassword, salt, role);
+            user = new User(username, encodedPassword, salt, roleNames);
             userRepository.save(user);
             return Result.success();
         }
 
         String errMsg = String.format("帐号 %s 已存在", username);
         return Result.fail(errMsg);
-
     }
 
     @Override

+ 6 - 2
web/src/main/java/cn/reghao/bnt/web/admin/service/impl/RoleServiceImpl.java

@@ -1,5 +1,6 @@
 package cn.reghao.bnt.web.admin.service.impl;
 
+import cn.reghao.bnt.web.admin.db.repository.MenuRepository;
 import cn.reghao.bnt.web.admin.model.po.Menu;
 import cn.reghao.bnt.web.admin.model.po.Role;
 import cn.reghao.bnt.web.admin.model.po.User;
@@ -27,16 +28,19 @@ import java.util.stream.Collectors;
 @Service
 public class RoleServiceImpl implements RoleService {
     private final RoleRepository roleRepository;
+    private final MenuRepository menuRepository;
     private final AccountService accountService;
     private final int pageSize = 100;
 
-    public RoleServiceImpl(RoleRepository roleRepository, AccountService accountService) {
+    public RoleServiceImpl(RoleRepository roleRepository, MenuRepository menuRepository, AccountService accountService) {
         this.roleRepository = roleRepository;
+        this.menuRepository = menuRepository;
         this.accountService = accountService;
     }
 
     @Override
-    public void updateRoleMenus(Integer roleId, Set<Menu> menus) {
+    public void updateRoleMenus(Integer roleId, Set<Integer> menuIds) {
+        Set<Menu> menus = new HashSet<>(menuRepository.findAllById(menuIds));
         Role role = roleRepository.getOne(roleId);
         role.setMenus(menus);
         roleRepository.save(role);

+ 1 - 14
web/src/main/java/cn/reghao/bnt/web/blog/controller/ForegroundController.java

@@ -1,7 +1,6 @@
 package cn.reghao.bnt.web.blog.controller;
 
 import cn.reghao.bnt.web.admin.service.FileService;
-import cn.reghao.bnt.web.admin.service.SiteOptionService;
 import cn.reghao.bnt.web.blog.hibernate.HibernateQuery;
 import cn.reghao.bnt.web.blog.model.po.AboutView;
 import cn.reghao.bnt.web.blog.model.vo.*;
@@ -44,19 +43,16 @@ public class ForegroundController extends BaseController {
     private final ArticleQuery articleQuery;
     private final HibernateQuery hibernateQuery;
     private final ArticleViewService articleViewService;
-    private final SiteOptionService siteOptionService;
     private final FileService fileService;
     private final JarFileResources jarFileResources;
 
     public ForegroundController(CategoryService categoryService, ArticleQuery articleQuery,
                                 HibernateQuery hibernateQuery, ArticleViewService articleViewService,
-                                SiteOptionService siteOptionService, FileService fileService,
-                                JarFileResources jarFileResources) {
+                                FileService fileService, JarFileResources jarFileResources) {
         this.categoryService = categoryService;
         this.articleQuery = articleQuery;
         this.hibernateQuery = hibernateQuery;
         this.articleViewService = articleViewService;
-        this.siteOptionService = siteOptionService;
         this.fileService = fileService;
         this.jarFileResources = jarFileResources;
     }
@@ -64,15 +60,6 @@ public class ForegroundController extends BaseController {
     @Operation(summary = "前台首页", description = "N")
     @GetMapping(value = "/")
     public String index(ModelMap model, HttpServletRequest request) {
-        boolean checkDomain = siteOptionService.getCheckDomain();
-        if (checkDomain) {
-            String host = request.getHeader("host");
-            Set<String> domainSet = siteOptionService.getBackgroundDomain();
-            if (domainSet.contains(host)) {
-                return "redirect:/bg";
-            }
-        }
-
         // 调用 ContentsDirective
         String order = ServletRequestUtils.getStringParameter(request, "order", "newest");
         int pageNo = ServletRequestUtils.getIntParameter(request, "pageNo", 1);

+ 2 - 5
web/src/main/java/cn/reghao/bnt/web/blog/service/ArticleQuery.java

@@ -1,6 +1,5 @@
 package cn.reghao.bnt.web.blog.service;
 
-import cn.reghao.bnt.web.admin.service.SiteOptionService;
 import cn.reghao.bnt.web.blog.db.repository.AboutViewRepository;
 import cn.reghao.bnt.web.blog.db.repository.ArticleRepository;
 import cn.reghao.bnt.web.blog.db.repository.ArticleTagRepository;
@@ -33,17 +32,15 @@ public class ArticleQuery {
     private final CategoryRepository categoryRepository;
     private final ArticleViewService articleViewService;
     private final AboutViewRepository aboutViewRepository;
-    private final SiteOptionService siteOptionService;
 
     public ArticleQuery(ArticleRepository articleRepository, ArticleTagRepository articleTagRepository,
                         CategoryRepository categoryRepository, ArticleViewService articleViewService,
-                        AboutViewRepository aboutViewRepository, SiteOptionService siteOptionService) {
+                        AboutViewRepository aboutViewRepository) {
         this.articleRepository = articleRepository;
         this.articleTagRepository = articleTagRepository;
         this.categoryRepository = categoryRepository;
         this.articleViewService = articleViewService;
         this.aboutViewRepository = aboutViewRepository;
-        this.siteOptionService = siteOptionService;
     }
 
     public EditArticle getEditArticle(String articleId) {
@@ -245,7 +242,7 @@ public class ArticleQuery {
             return cb.and(predicates.toArray(new Predicate[0]));
         };
 
-        String domain = siteOptionService.getForegroundDomain();
+        String domain = "";
         Pageable pageable = PageRequest.of(pageNumber-1, pageSize, Sort.by(Sort.Direction.DESC, "createTime"));
         Page<Article> page = articleRepository.findAll(specification, pageable);
         List<AdminArticle> list1 = page.stream().map(article -> {