提交登录修改

This commit is contained in:
super
2026-05-23 18:32:45 +08:00
parent 7266d6dac9
commit cbe1014117
52 changed files with 2139 additions and 1572 deletions
@@ -0,0 +1,76 @@
package com.nanri.aiimage.modules.admin.controller;
import com.nanri.aiimage.common.api.ApiResponse;
import com.nanri.aiimage.modules.admin.model.dto.AdminUserCreateRequest;
import com.nanri.aiimage.modules.admin.model.dto.AdminUserUpdateRequest;
import com.nanri.aiimage.modules.admin.model.vo.AdminUserListVo;
import com.nanri.aiimage.modules.admin.service.AdminUserService;
import com.nanri.aiimage.modules.admin.support.AdminAuthSupport;
import com.nanri.aiimage.modules.permission.model.entity.AdminUserEntity;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/admin")
@Tag(name = "管理后台-用户", description = "用户列表、创建、更新、删除")
public class AdminUserController {
private final AdminAuthSupport adminAuthSupport;
private final AdminUserService adminUserService;
@GetMapping("/users")
@Operation(summary = "分页查询用户列表")
public ApiResponse<AdminUserListVo> listUsers(HttpServletRequest request,
@RequestParam(required = false, defaultValue = "1") Integer page,
@RequestParam(name = "page_size", required = false, defaultValue = "15") Integer pageSize,
@RequestParam(required = false) String username,
@RequestParam(name = "search", required = false) String search,
@RequestParam(name = "created_by_id", required = false) Long createdById,
@RequestParam(name = "admin_id", required = false) Long adminId) {
AdminUserEntity currentUser = adminAuthSupport.requireAdmin(request);
String kw = (username == null || username.isBlank()) ? search : username;
Long filterCreatedBy = createdById != null ? createdById : adminId;
AdminUserListVo vo = adminUserService.listUsers(currentUser, page, pageSize, kw, filterCreatedBy);
return ApiResponse.success(vo);
}
@PostMapping("/user")
@Operation(summary = "创建用户")
public ApiResponse<Void> createUser(HttpServletRequest request,
@RequestBody AdminUserCreateRequest body) {
AdminUserEntity currentUser = adminAuthSupport.requireAdmin(request);
adminUserService.createUser(currentUser, body);
return ApiResponse.success("用户创建成功", null);
}
@PutMapping("/user/{uid}")
@Operation(summary = "更新用户")
public ApiResponse<Void> updateUser(HttpServletRequest request,
@PathVariable Long uid,
@RequestBody AdminUserUpdateRequest body) {
AdminUserEntity currentUser = adminAuthSupport.requireAdmin(request);
adminUserService.updateUser(currentUser, uid, body);
return ApiResponse.success("更新成功", null);
}
@DeleteMapping("/user/{uid}")
@Operation(summary = "删除用户")
public ApiResponse<Void> deleteUser(HttpServletRequest request,
@PathVariable Long uid) {
AdminUserEntity currentUser = adminAuthSupport.requireAdmin(request);
adminUserService.deleteUser(currentUser, uid);
return ApiResponse.success("删除成功", null);
}
}
@@ -0,0 +1,11 @@
package com.nanri.aiimage.modules.admin.model.dto;
import lombok.Data;
@Data
public class AdminUserCreateRequest {
private String username;
private String password;
private String role;
private Long createdById;
}
@@ -0,0 +1,9 @@
package com.nanri.aiimage.modules.admin.model.dto;
import lombok.Data;
@Data
public class AdminUserUpdateRequest {
private String password;
private String role;
}
@@ -0,0 +1,13 @@
package com.nanri.aiimage.modules.admin.model.vo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class AdminBriefVo {
private Long id;
private String username;
}
@@ -0,0 +1,19 @@
package com.nanri.aiimage.modules.admin.model.vo;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
@Data
public class AdminUserItemVo {
private Long id;
private String username;
@JsonProperty("is_admin")
private boolean admin;
private String role;
@JsonProperty("created_by_id")
private Long createdById;
@JsonProperty("creator_username")
private String creatorUsername;
@JsonProperty("created_at")
private String createdAt;
}
@@ -0,0 +1,18 @@
package com.nanri.aiimage.modules.admin.model.vo;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import java.util.List;
@Data
public class AdminUserListVo {
private List<AdminUserItemVo> items;
private Long total;
private Integer page;
@JsonProperty("page_size")
private Integer pageSize;
@JsonProperty("current_user_role")
private String currentUserRole;
private List<AdminBriefVo> admins;
}
@@ -0,0 +1,269 @@
package com.nanri.aiimage.modules.admin.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.modules.admin.model.dto.AdminUserCreateRequest;
import com.nanri.aiimage.modules.admin.model.dto.AdminUserUpdateRequest;
import com.nanri.aiimage.modules.admin.model.vo.AdminBriefVo;
import com.nanri.aiimage.modules.admin.model.vo.AdminUserItemVo;
import com.nanri.aiimage.modules.admin.model.vo.AdminUserListVo;
import com.nanri.aiimage.modules.admin.support.AdminAuthSupport;
import com.nanri.aiimage.modules.auth.util.WerkzeugPasswordEncoder;
import com.nanri.aiimage.modules.permission.mapper.AdminUserMapper;
import com.nanri.aiimage.modules.permission.model.entity.AdminUserEntity;
import lombok.RequiredArgsConstructor;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
@Service
@RequiredArgsConstructor
public class AdminUserService {
private static final DateTimeFormatter CREATED_AT_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
private final AdminUserMapper adminUserMapper;
private final WerkzeugPasswordEncoder passwordEncoder;
private final AdminAuthSupport adminAuthSupport;
public AdminUserListVo listUsers(AdminUserEntity currentUser, Integer page, Integer pageSize,
String username, Long createdById) {
String role = adminAuthSupport.currentRole(currentUser);
if (role == null) {
throw new BusinessException(403, "需要管理员权限");
}
int safePage = page == null || page < 1 ? 1 : page;
int safeSize = pageSize == null ? 15 : pageSize;
if (safeSize < 5) safeSize = 5;
if (safeSize > 50) safeSize = 50;
String kw = username == null ? "" : username.trim();
Long filterCreatedBy = "super_admin".equals(role) ? createdById : null;
LambdaQueryWrapper<AdminUserEntity> query = new LambdaQueryWrapper<>();
if ("super_admin".equals(role)) {
if (!kw.isEmpty()) {
query.like(AdminUserEntity::getUsername, kw);
}
if (filterCreatedBy != null) {
query.eq(AdminUserEntity::getCreatedById, filterCreatedBy);
}
} else {
Long adminId = currentUser.getId();
query.and(w -> w
.eq(AdminUserEntity::getId, adminId)
.or(inner -> inner
.eq(AdminUserEntity::getRole, "normal")
.eq(AdminUserEntity::getCreatedById, adminId)));
if (!kw.isEmpty()) {
query.like(AdminUserEntity::getUsername, kw);
}
}
query.orderByAsc(AdminUserEntity::getId);
Long total = adminUserMapper.selectCount(query);
int offset = (safePage - 1) * safeSize;
query.last("LIMIT " + safeSize + " OFFSET " + offset);
List<AdminUserEntity> rows = adminUserMapper.selectList(query);
Map<Long, String> creatorMap = loadCreatorMap(rows);
List<AdminUserItemVo> items = rows.stream().map(r -> toItem(r, creatorMap)).toList();
List<AdminBriefVo> admins = "super_admin".equals(role)
? adminUserMapper.selectList(new LambdaQueryWrapper<AdminUserEntity>()
.eq(AdminUserEntity::getRole, "admin")
.orderByAsc(AdminUserEntity::getId)).stream()
.map(u -> new AdminBriefVo(u.getId(), u.getUsername()))
.toList()
: List.of();
AdminUserListVo vo = new AdminUserListVo();
vo.setItems(items);
vo.setTotal(total == null ? 0L : total);
vo.setPage(safePage);
vo.setPageSize(safeSize);
vo.setCurrentUserRole(role);
vo.setAdmins(admins);
return vo;
}
public void createUser(AdminUserEntity currentUser, AdminUserCreateRequest request) {
String role = adminAuthSupport.currentRole(currentUser);
if (role == null) {
throw new BusinessException(403, "需要管理员权限");
}
String username = request.getUsername() == null ? "" : request.getUsername().trim();
String password = request.getPassword() == null ? "" : request.getPassword();
String wantRole = request.getRole() == null ? "normal" : request.getRole().trim();
if (wantRole.isEmpty()) wantRole = "normal";
if (!"admin".equals(wantRole) && !"normal".equals(wantRole)) {
wantRole = "normal";
}
if ("admin".equals(role) && "admin".equals(wantRole)) {
throw new BusinessException("仅超级管理员可创建管理员");
}
if (username.isEmpty() || password.isEmpty()) {
throw new BusinessException("用户名和密码不能为空");
}
if (username.length() < 2) {
throw new BusinessException("用户名至少2个字符");
}
if (password.length() < 6) {
throw new BusinessException("密码至少6个字符");
}
Long wantCreatedBy;
if ("admin".equals(wantRole)) {
wantCreatedBy = currentUser.getId();
} else if ("super_admin".equals(role)) {
wantCreatedBy = request.getCreatedById();
if (wantCreatedBy == null) {
AdminUserEntity firstAdmin = adminUserMapper.selectOne(new LambdaQueryWrapper<AdminUserEntity>()
.eq(AdminUserEntity::getRole, "admin")
.orderByAsc(AdminUserEntity::getId)
.last("LIMIT 1"));
wantCreatedBy = firstAdmin != null ? firstAdmin.getId() : currentUser.getId();
}
} else {
wantCreatedBy = currentUser.getId();
}
int isAdmin = ("super_admin".equals(wantRole) || "admin".equals(wantRole)) ? 1 : 0;
AdminUserEntity entity = new AdminUserEntity();
entity.setUsername(username);
entity.setPasswordHash(passwordEncoder.hash(password));
entity.setIsAdmin(isAdmin);
entity.setRole(wantRole);
entity.setCreatedById(wantCreatedBy);
try {
adminUserMapper.insert(entity);
} catch (DuplicateKeyException e) {
throw new BusinessException("用户名已存在");
}
}
public void updateUser(AdminUserEntity currentUser, Long uid, AdminUserUpdateRequest request) {
String role = adminAuthSupport.currentRole(currentUser);
if (role == null) {
throw new BusinessException(403, "需要管理员权限");
}
String password = request.getPassword();
String wantRole = request.getRole() == null ? null : request.getRole().trim();
if ((password == null || password.isEmpty()) && (wantRole == null || wantRole.isEmpty())) {
throw new BusinessException("请提供要修改的内容");
}
AdminUserEntity target = adminUserMapper.selectById(uid);
if (target == null) {
throw new BusinessException("用户不存在");
}
String targetRole = target.getRole() == null ? "" : target.getRole();
if ("admin".equals(role)) {
if (!"normal".equals(targetRole) || !currentUser.getId().equals(target.getCreatedById())) {
throw new BusinessException(403, "只能编辑自己创建的普通用户");
}
wantRole = null;
} else {
if ("super_admin".equals(targetRole)) {
throw new BusinessException("不能修改超级管理员");
}
if ("super_admin".equals(wantRole)) {
throw new BusinessException("不能将用户设为超级管理员");
}
if (wantRole != null && !"admin".equals(wantRole) && !"normal".equals(wantRole) && !wantRole.isEmpty()) {
wantRole = null;
}
}
LambdaUpdateWrapper<AdminUserEntity> update = new LambdaUpdateWrapper<AdminUserEntity>()
.eq(AdminUserEntity::getId, uid);
boolean dirty = false;
if (password != null && !password.isEmpty()) {
if (password.length() < 6) {
throw new BusinessException("密码至少6个字符");
}
update.set(AdminUserEntity::getPasswordHash, passwordEncoder.hash(password));
dirty = true;
}
if (wantRole != null && !wantRole.isEmpty()) {
int isAdmin = "admin".equals(wantRole) ? 1 : 0;
update.set(AdminUserEntity::getIsAdmin, isAdmin);
update.set(AdminUserEntity::getRole, wantRole);
dirty = true;
}
if (dirty) {
adminUserMapper.update(null, update);
}
}
public void deleteUser(AdminUserEntity currentUser, Long uid) {
String role = adminAuthSupport.currentRole(currentUser);
if (role == null) {
throw new BusinessException(403, "需要管理员权限");
}
if (currentUser.getId().equals(uid)) {
throw new BusinessException("不能删除当前登录账号");
}
AdminUserEntity target = adminUserMapper.selectById(uid);
if (target == null) {
throw new BusinessException("用户不存在");
}
String targetRole = target.getRole() == null ? "" : target.getRole();
if ("super_admin".equals(targetRole)) {
throw new BusinessException("不能删除超级管理员");
}
if ("admin".equals(role)) {
if (!"normal".equals(targetRole) || !currentUser.getId().equals(target.getCreatedById())) {
throw new BusinessException(403, "只能删除自己创建的普通用户");
}
}
int affected = adminUserMapper.deleteById(uid);
if (affected == 0) {
throw new BusinessException("用户不存在");
}
}
private Map<Long, String> loadCreatorMap(List<AdminUserEntity> rows) {
Set<Long> creatorIds = new LinkedHashSet<>();
for (AdminUserEntity r : rows) {
if (r.getCreatedById() != null && r.getCreatedById() > 0) {
creatorIds.add(r.getCreatedById());
}
}
if (creatorIds.isEmpty()) {
return Map.of();
}
List<AdminUserEntity> creators = adminUserMapper.selectList(new LambdaQueryWrapper<AdminUserEntity>()
.in(AdminUserEntity::getId, new ArrayList<>(creatorIds)));
Map<Long, String> map = new HashMap<>(creators.size() * 2);
for (AdminUserEntity c : creators) {
map.put(c.getId(), c.getUsername() == null ? "" : c.getUsername());
}
return map;
}
private AdminUserItemVo toItem(AdminUserEntity entity, Map<Long, String> creatorMap) {
AdminUserItemVo vo = new AdminUserItemVo();
vo.setId(entity.getId());
vo.setUsername(entity.getUsername());
vo.setAdmin(entity.getIsAdmin() != null && entity.getIsAdmin() == 1);
vo.setRole(entity.getRole() == null || entity.getRole().isEmpty() ? "normal" : entity.getRole());
vo.setCreatedById(entity.getCreatedById());
vo.setCreatorUsername(creatorMap.getOrDefault(entity.getCreatedById(), ""));
LocalDateTime createdAt = entity.getCreatedAt();
vo.setCreatedAt(createdAt == null ? "" : createdAt.format(CREATED_AT_FORMATTER));
return vo;
}
}
@@ -0,0 +1,109 @@
package com.nanri.aiimage.modules.admin.support;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.modules.auth.service.JwtService;
import com.nanri.aiimage.modules.permission.mapper.AdminUserMapper;
import com.nanri.aiimage.modules.permission.model.entity.AdminUserEntity;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import com.nanri.aiimage.modules.auth.config.AuthProperties;
@Component
@RequiredArgsConstructor
public class AdminAuthSupport {
private final JwtService jwtService;
private final AdminUserMapper adminUserMapper;
private final AuthProperties authProperties;
/** 解析当前请求的用户;token 缺失或无效抛 401。 */
public AdminUserEntity requireUser(HttpServletRequest request) {
String token = resolveToken(request);
if (token == null || token.isBlank()) {
throw new BusinessException(401, "未登录");
}
Claims claims = jwtService.parse(token);
if (claims == null) {
throw new BusinessException(401, "登录已过期,请重新登录");
}
Long userId;
try {
userId = Long.parseLong(claims.getSubject());
} catch (NumberFormatException e) {
throw new BusinessException(401, "登录态无效");
}
AdminUserEntity user = adminUserMapper.selectById(userId);
if (user == null) {
throw new BusinessException(401, "用户不存在");
}
return user;
}
/** 当前用户必须是管理员或超级管理员,否则抛 403。 */
public AdminUserEntity requireAdmin(HttpServletRequest request) {
AdminUserEntity user = requireUser(request);
String role = currentRole(user);
if (role == null) {
throw new BusinessException(403, "需要管理员权限");
}
return user;
}
/** 计算当前用户的管理角色:super_admin / admin / null。 */
public String currentRole(AdminUserEntity user) {
if (user == null) {
return null;
}
String storedRole = user.getRole() == null ? "" : user.getRole().trim().toLowerCase();
if ("super_admin".equals(storedRole)) {
return "super_admin";
}
if ("admin".equals(storedRole)) {
return resolveAdminRole(user);
}
boolean isAdminFlag = user.getIsAdmin() != null && user.getIsAdmin() == 1;
if (isAdminFlag) {
return resolveAdminRole(user);
}
return null;
}
/** 数据库里 role='admin' 中 id 最小者视作超级管理员(与 Python 行为一致)。 */
private String resolveAdminRole(AdminUserEntity user) {
AdminUserEntity superAdmin = adminUserMapper.selectOne(new LambdaQueryWrapper<AdminUserEntity>()
.eq(AdminUserEntity::getRole, "admin")
.orderByAsc(AdminUserEntity::getId)
.last("LIMIT 1"));
if (superAdmin != null && superAdmin.getId().equals(user.getId())) {
return "super_admin";
}
return "admin";
}
private String resolveToken(HttpServletRequest request) {
String authHeader = request.getHeader(HttpHeaders.AUTHORIZATION);
if (authHeader != null && authHeader.startsWith("Bearer ")) {
String t = authHeader.substring(7).trim();
if (!t.isEmpty()) {
return t;
}
}
Cookie[] cookies = request.getCookies();
if (cookies == null) {
return null;
}
String cookieName = authProperties.getCookieName();
for (Cookie cookie : cookies) {
if (cookieName.equals(cookie.getName())) {
return cookie.getValue();
}
}
return null;
}
}