|
| 1 | +package com.yqz.openblog.user.controller; |
| 2 | + |
| 3 | +import com.baomidou.mybatisplus.core.toolkit.Wrappers; |
| 4 | +import com.yqz.openblog.common.ApiResponse; |
| 5 | +import com.yqz.openblog.common.BizException; |
| 6 | +import com.yqz.openblog.user.dto.PendingUserResponse; |
| 7 | +import com.yqz.openblog.user.entity.User; |
| 8 | +import com.yqz.openblog.user.entity.UserRole; |
| 9 | +import com.yqz.openblog.user.repo.UserMapper; |
| 10 | +import org.springframework.security.access.prepost.PreAuthorize; |
| 11 | +import org.springframework.web.bind.annotation.CrossOrigin; |
| 12 | +import org.springframework.web.bind.annotation.GetMapping; |
| 13 | +import org.springframework.web.bind.annotation.PathVariable; |
| 14 | +import org.springframework.web.bind.annotation.PostMapping; |
| 15 | +import org.springframework.web.bind.annotation.RequestMapping; |
| 16 | +import org.springframework.web.bind.annotation.RestController; |
| 17 | + |
| 18 | +import java.util.List; |
| 19 | + |
| 20 | +@RestController |
| 21 | +@RequestMapping("/api/v1") |
| 22 | +@CrossOrigin(origins = "*") |
| 23 | +public class UserAdminController { |
| 24 | + |
| 25 | + private final UserMapper userMapper; |
| 26 | + |
| 27 | + public UserAdminController(UserMapper userMapper) { |
| 28 | + this.userMapper = userMapper; |
| 29 | + } |
| 30 | + |
| 31 | + @GetMapping("/admin/users/pending") |
| 32 | + @PreAuthorize("hasRole('ADMIN')") |
| 33 | + public ApiResponse<List<PendingUserResponse>> listPendingReaders() { |
| 34 | + List<User> users = userMapper.selectList( |
| 35 | + Wrappers.lambdaQuery(User.class) |
| 36 | + .eq(User::getStatus, "PENDING") |
| 37 | + .eq(User::getRole, UserRole.READER) |
| 38 | + .orderByDesc(User::getCreatedAt)); |
| 39 | + List<PendingUserResponse> list = users.stream().map(this::toPending).toList(); |
| 40 | + return ApiResponse.ok(list); |
| 41 | + } |
| 42 | + |
| 43 | + @PostMapping("/admin/users/{userId}/approve") |
| 44 | + @PreAuthorize("hasRole('ADMIN')") |
| 45 | + public ApiResponse<Void> approveReader(@PathVariable("userId") Long userId) { |
| 46 | + User u = userMapper.selectById(userId); |
| 47 | + if (u == null) { |
| 48 | + throw new BizException(4041, "用户不存在"); |
| 49 | + } |
| 50 | + if (u.getRole() != UserRole.READER) { |
| 51 | + throw new BizException(4000, "仅支持审核读者账号"); |
| 52 | + } |
| 53 | + if (!"PENDING".equals(u.getStatus())) { |
| 54 | + throw new BizException(4000, "该账号不在待审核状态"); |
| 55 | + } |
| 56 | + u.setStatus("ACTIVE"); |
| 57 | + userMapper.updateById(u); |
| 58 | + return ApiResponse.ok(); |
| 59 | + } |
| 60 | + |
| 61 | + private PendingUserResponse toPending(User u) { |
| 62 | + PendingUserResponse r = new PendingUserResponse(); |
| 63 | + r.setUserId(u.getId()); |
| 64 | + r.setUsername(u.getUsername()); |
| 65 | + r.setEmail(u.getEmail()); |
| 66 | + r.setCreatedAt(u.getCreatedAt()); |
| 67 | + return r; |
| 68 | + } |
| 69 | +} |
0 commit comments