feat(auth): 超管切换账户迁至 SuperAuthController,新增多公司切换与 companyCount 并收紧 auth 白名单

This commit is contained in:
小蟑螂
2026-05-25 22:47:25 +08:00
parent d4bfa4d257
commit 2ef5b9a41a
13 changed files with 402 additions and 19 deletions
@@ -42,7 +42,7 @@ public class SecurityConfig {
.csrf(AbstractHttpConfigurer::disable)
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(auth -> auth
.requestMatchers("/auth/**").permitAll()
.requestMatchers("/auth/login", "/auth/register", "/auth/refresh").permitAll()
.requestMatchers("/uploads/**").permitAll() // 允许直接访问上传的文件
.requestMatchers("/doc.html", "/webjars/**", "/v3/api-docs/**", "/swagger-resources/**",
"/swagger-ui/**", "/swagger-ui.html")
@@ -1,7 +1,6 @@
package top.xyquan.ecomdmbbackend.modules.sys.auth.controller;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;
@@ -55,12 +54,11 @@ public class AuthController {
return ApiResponse.success("令牌刷新成功", loginVO);
}
@Operation(summary = "切换账户", description = "超级管理员切换到指定用户账户,角色保持为super")
@PostMapping("/switch/{userId}")
public ApiResponse<LoginVO> switchAccount(
@Parameter(description = "目标用户ID") @PathVariable Long userId) {
LoginVO loginVO = userService.switchAccount(userId);
return ApiResponse.success("账户切换成功", loginVO);
@Operation(summary = "切换公司", description = "切换当前登录公司上下文并重新签发 token")
@PostMapping("/switch-company/{companyId}")
public ApiResponse<LoginVO> switchCompany(@PathVariable Long companyId) {
LoginVO loginVO = userService.switchCompany(companyId);
return ApiResponse.success("切换公司成功", loginVO);
}
@Operation(summary = "获取用户权限码", description = "获取当前登录用户的权限码列表")
@@ -0,0 +1,41 @@
package top.xyquan.ecomdmbbackend.modules.sys.auth.controller;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.xyquan.ecomdmbbackend.common.annotation.RequireRole;
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
import top.xyquan.ecomdmbbackend.modules.sys.auth.model.vo.LoginVO;
import top.xyquan.ecomdmbbackend.modules.sys.user.service.UserService;
/**
* 超级管理员认证控制器
*/
@Tag(name = "超级管理员-认证管理", description = "超级管理员专属认证相关接口")
@RestController
@RequestMapping("/super/auth")
public class SuperAuthController {
private final UserService userService;
public SuperAuthController(UserService userService) {
this.userService = userService;
}
/**
* 切换账户:以目标用户在指定公司下的身份登录,系统角色保持 super
*/
@Operation(summary = "切换账户", description = "超级管理员切换到指定用户在指定公司下的账户上下文,角色保持为super")
@PostMapping("/switch/company/{companyId}/user/{userId}")
@RequireRole(value = {"super"}, allowCompany = false, allowUser = false, description = "切换账户")
public ApiResponse<LoginVO> switchAccount(
@Parameter(description = "目标公司ID") @PathVariable Long companyId,
@Parameter(description = "目标用户ID") @PathVariable Long userId) {
LoginVO loginVO = userService.switchAccount(userId, companyId);
return ApiResponse.success("账户切换成功", loginVO);
}
}
@@ -13,6 +13,7 @@ import top.xyquan.ecomdmbbackend.modules.sys.auth.model.dto.ChangePasswordDTO;
import top.xyquan.ecomdmbbackend.modules.sys.user.model.dto.UpdateUserInfoDTO;
import top.xyquan.ecomdmbbackend.modules.sys.user.model.dto.UserFilterDTO;
import top.xyquan.ecomdmbbackend.modules.sys.menu.model.vo.UserMenuVO;
import top.xyquan.ecomdmbbackend.modules.sys.user.model.vo.UserCompanySummaryVO;
import top.xyquan.ecomdmbbackend.modules.sys.user.model.vo.UserVO;
import top.xyquan.ecomdmbbackend.modules.sys.menu.service.UserMenuService;
import top.xyquan.ecomdmbbackend.modules.sys.user.service.UserService;
@@ -43,6 +44,13 @@ public class UserController {
return ApiResponse.success("获取用户信息成功", userVO);
}
@Operation(summary = "获取可用公司列表", description = "获取当前用户可切换的可用公司列表")
@GetMapping("/companies")
public ApiResponse<List<UserCompanySummaryVO>> getAvailableCompanies() {
List<UserCompanySummaryVO> companies = userService.getAvailableCompanies();
return ApiResponse.success("获取可用公司列表成功", companies);
}
@Operation(summary = "更新用户信息", description = "更新当前登录用户的基本信息")
@PutMapping("/info")
@RequirePermission(value = "system:user:update", description = "更新用户信息", allowSuper = true)
@@ -20,6 +20,11 @@ public class UserVO {
*/
private UserCompanySummaryVO company;
/**
* 当前用户可切换的可用公司数量(成员正常且公司未停用/未过期)
*/
private Integer companyCount;
/**
* 部门id
*/
@@ -12,8 +12,11 @@ import top.xyquan.ecomdmbbackend.modules.sys.user.model.dto.UpdateUserInfoDTO;
import top.xyquan.ecomdmbbackend.modules.sys.user.model.dto.UserFilterDTO;
import top.xyquan.ecomdmbbackend.modules.sys.user.model.po.UserPO;
import top.xyquan.ecomdmbbackend.modules.sys.auth.model.vo.LoginVO;
import top.xyquan.ecomdmbbackend.modules.sys.user.model.vo.UserCompanySummaryVO;
import top.xyquan.ecomdmbbackend.modules.sys.user.model.vo.UserVO;
import java.util.List;
/**
* 系统用户服务接口
*/
@@ -82,12 +85,16 @@ public interface UserService extends IService<UserPO> {
LoginVO refreshToken(RefreshTokenDTO refreshTokenDTO);
/**
* 切换账户
* 切换账户(超级管理员)
* <p>
* 以目标用户身份生成 token,系统角色保持 super。
* 若传入 companyId,则校验目标用户是否为该公司成员,并以其作为登录公司上下文。
*
* @param userId 目标用户ID
* @param userId 目标用户ID
* @param companyId 目标公司ID(指定切换后的公司上下文)
* @return 登录响应
*/
LoginVO switchAccount(Long userId);
LoginVO switchAccount(Long userId, Long companyId);
/**
* 分页查询用户列表
@@ -96,4 +103,19 @@ public interface UserService extends IService<UserPO> {
* @return 分页结果
*/
PageResultVO<UserVO> getUserPage(PageQueryDTO<UserFilterDTO> pageQuery);
/**
* 获取当前用户可切换的可用公司列表
*
* @return 公司摘要列表
*/
List<UserCompanySummaryVO> getAvailableCompanies();
/**
* 切换当前登录公司上下文,重新签发 token
*
* @param companyId 目标公司ID
* @return 新的登录响应
*/
LoginVO switchCompany(Long companyId);
}
@@ -186,6 +186,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserPO> implements
UserVO userVO = new UserVO();
BeanUtils.copyProperties(user, userVO);
fillCompanyFromCurrentToken(userVO);
userVO.setCompanyCount(countAvailableCompanies(userId));
return userVO;
}
@@ -365,26 +366,102 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserPO> implements
/**
* 切换账户
* @param userId 用户ID
* <p>
* 超管以目标用户身份登录,JWT 中 role 保持 super。
* 公司上下文由 generateLoginResponseWithRole 决定:若传入 companyId 则优先使用该公司。
*
* @param userId 目标用户ID
* @param companyId 目标公司ID
* @return 登录VO
*/
@Override
public LoginVO switchAccount(Long userId) {
// 查询目标用户信息
public LoginVO switchAccount(Long userId, Long companyId) {
if (companyId == null) {
throw new BusinessException("目标公司不能为空");
}
UserPO targetUser = this.getById(userId);
if (targetUser == null) {
throw new BusinessException("目标用户不存在");
}
// 检查目标用户状态
if (targetUser.getStatus() != 1) {
throw new BusinessException("目标用户状态异常,无法切换");
}
// 生成登录响应,角色保持为super
// 校验成员关系并写入 lastCompanyId,供 token 生成时优先选用
var member = companyMemberService.getByUserIdAndCompanyId(userId, companyId);
if (member == null || member.getStatus() == null || member.getStatus() != 1) {
throw new BusinessException("目标用户不是该公司有效成员");
}
var company = companyService.getById(companyId);
if (!isCompanyAvailable(company)) {
throw new BusinessException("目标公司不可用");
}
targetUser.setLastCompanyId(companyId);
targetUser.setUpdateBy(currentUserContext.getCurrentUserId());
this.updateById(targetUser);
return generateLoginResponseWithRole(targetUser, "super");
}
/**
* 获取当前用户可切换的可用公司列表
*/
@Override
public List<UserCompanySummaryVO> getAvailableCompanies() {
Long userId = SecurityUtils.getCurrentUserId();
if (userId == null) {
throw new BusinessException("用户未登录");
}
return buildAvailableCompanySummaries(userId);
}
/**
* 切换当前登录公司上下文
* 更新 lastCompanyId 后按当前 token 角色重新签发 JWT
*/
@Override
public LoginVO switchCompany(Long companyId) {
if (companyId == null) {
throw new BusinessException("目标公司不能为空");
}
Long userId = SecurityUtils.getCurrentUserId();
if (userId == null) {
throw new BusinessException("用户未登录");
}
UserPO user = this.getById(userId);
if (user == null) {
throw new BusinessException("用户不存在");
}
if (user.getStatus() != 1) {
throw new BusinessException("用户状态异常,无法切换公司");
}
var member = companyMemberService.getByUserIdAndCompanyId(userId, companyId);
if (member == null || member.getStatus() == null || member.getStatus() != 1) {
throw new BusinessException("您不是该公司有效成员");
}
var company = companyService.getById(companyId);
if (!isCompanyAvailable(company)) {
throw new BusinessException("目标公司不可用");
}
Long currentCompanyId = currentUserContext.getCurrentCompanyId();
if (companyId.equals(currentCompanyId)) {
throw new BusinessException("当前已在该公司,无需切换");
}
user.setLastCompanyId(companyId);
user.setUpdateBy(userId);
this.updateById(user);
String role = currentUserContext.getCurrentUserPayload().getRole();
return generateLoginResponseWithRole(user, role);
}
/**
* 获取用户分页列表
* @param pageQuery 分页查询DTO
@@ -511,6 +588,27 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserPO> implements
userVO.setCompany(summary);
}
/** 统计用户可切换的可用公司数 */
private int countAvailableCompanies(Long userId) {
return buildAvailableCompanySummaries(userId).size();
}
/** 构建用户可切换的可用公司摘要列表 */
private List<UserCompanySummaryVO> buildAvailableCompanySummaries(Long userId) {
return companyMemberService.getByUserId(userId).stream()
.filter(member -> {
CompanyPO company = companyService.getById(member.getCompanyId());
return isCompanyAvailable(company);
})
.map(member -> {
UserCompanySummaryVO summary = new UserCompanySummaryVO();
summary.setId(member.getCompanyId());
summary.setName(member.getCompanyName());
return summary;
})
.collect(Collectors.toList());
}
/**
* 生成登录响应
*/