diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/common/config/SecurityConfig.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/common/config/SecurityConfig.java index 85c25070..4199232b 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/common/config/SecurityConfig.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/common/config/SecurityConfig.java @@ -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") diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/sys/auth/controller/AuthController.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/sys/auth/controller/AuthController.java index 1eccd703..a4eb9be9 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/sys/auth/controller/AuthController.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/sys/auth/controller/AuthController.java @@ -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 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 switchCompany(@PathVariable Long companyId) { + LoginVO loginVO = userService.switchCompany(companyId); + return ApiResponse.success("切换公司成功", loginVO); } @Operation(summary = "获取用户权限码", description = "获取当前登录用户的权限码列表") diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/sys/auth/controller/SuperAuthController.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/sys/auth/controller/SuperAuthController.java new file mode 100644 index 00000000..fb242196 --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/sys/auth/controller/SuperAuthController.java @@ -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 switchAccount( + @Parameter(description = "目标公司ID") @PathVariable Long companyId, + @Parameter(description = "目标用户ID") @PathVariable Long userId) { + LoginVO loginVO = userService.switchAccount(userId, companyId); + return ApiResponse.success("账户切换成功", loginVO); + } +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/sys/user/controller/UserController.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/sys/user/controller/UserController.java index f925b3c6..2a3c3777 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/sys/user/controller/UserController.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/sys/user/controller/UserController.java @@ -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> getAvailableCompanies() { + List companies = userService.getAvailableCompanies(); + return ApiResponse.success("获取可用公司列表成功", companies); + } + @Operation(summary = "更新用户信息", description = "更新当前登录用户的基本信息") @PutMapping("/info") @RequirePermission(value = "system:user:update", description = "更新用户信息", allowSuper = true) diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/sys/user/model/vo/UserVO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/sys/user/model/vo/UserVO.java index 0147d1d1..1706b0ab 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/sys/user/model/vo/UserVO.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/sys/user/model/vo/UserVO.java @@ -20,6 +20,11 @@ public class UserVO { */ private UserCompanySummaryVO company; + /** + * 当前用户可切换的可用公司数量(成员正常且公司未停用/未过期) + */ + private Integer companyCount; + /** * 部门id */ diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/sys/user/service/UserService.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/sys/user/service/UserService.java index 299052c5..48ec7e8e 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/sys/user/service/UserService.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/sys/user/service/UserService.java @@ -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 { LoginVO refreshToken(RefreshTokenDTO refreshTokenDTO); /** - * 切换账户 + * 切换账户(超级管理员) + *

+ * 以目标用户身份生成 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 { * @return 分页结果 */ PageResultVO getUserPage(PageQueryDTO pageQuery); + + /** + * 获取当前用户可切换的可用公司列表 + * + * @return 公司摘要列表 + */ + List getAvailableCompanies(); + + /** + * 切换当前登录公司上下文,重新签发 token + * + * @param companyId 目标公司ID + * @return 新的登录响应 + */ + LoginVO switchCompany(Long companyId); } diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/sys/user/service/impl/UserServiceImpl.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/sys/user/service/impl/UserServiceImpl.java index e6f34479..90b57fec 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/sys/user/service/impl/UserServiceImpl.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/sys/user/service/impl/UserServiceImpl.java @@ -186,6 +186,7 @@ public class UserServiceImpl extends ServiceImpl 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 implements /** * 切换账户 - * @param userId 用户ID + *

+ * 超管以目标用户身份登录,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 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 implements userVO.setCompany(summary); } + /** 统计用户可切换的可用公司数 */ + private int countAvailableCompanies(Long userId) { + return buildAvailableCompanySummaries(userId).size(); + } + + /** 构建用户可切换的可用公司摘要列表 */ + private List 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()); + } + /** * 生成登录响应 */ diff --git a/ecom-dmb-frontend/apps/web-antd/src/api/core/auth.ts b/ecom-dmb-frontend/apps/web-antd/src/api/core/auth.ts index 6ec7e16a..6d9d375e 100644 --- a/ecom-dmb-frontend/apps/web-antd/src/api/core/auth.ts +++ b/ecom-dmb-frontend/apps/web-antd/src/api/core/auth.ts @@ -117,8 +117,19 @@ export async function getAccessCodesApi() { /** * 切换账户(超级管理员功能) */ -export async function switchAccountApi(userId: number) { - return requestClient.post(`/auth/switch/${userId}`); +export async function switchAccountApi(companyId: number, userId: number) { + return requestClient.post( + `/super/auth/switch/company/${companyId}/user/${userId}`, + ); +} + +/** + * 切换公司(重新签发 token) + */ +export async function switchCompanyApi(companyId: number) { + return requestClient.post( + `/auth/switch-company/${companyId}`, + ); } /** diff --git a/ecom-dmb-frontend/apps/web-antd/src/api/system/user/apis.ts b/ecom-dmb-frontend/apps/web-antd/src/api/system/user/apis.ts index 610b5513..f99dfa81 100644 --- a/ecom-dmb-frontend/apps/web-antd/src/api/system/user/apis.ts +++ b/ecom-dmb-frontend/apps/web-antd/src/api/system/user/apis.ts @@ -14,6 +14,13 @@ export async function getUserInfoApi() { return requestClient.get('/user/info'); } +/** + * 获取当前用户可切换的可用公司列表 + */ +export async function getAvailableCompaniesApi() { + return requestClient.get>('/user/companies'); +} + /** * 更新用户信息 */ diff --git a/ecom-dmb-frontend/apps/web-antd/src/api/system/user/types/types.vo.ts b/ecom-dmb-frontend/apps/web-antd/src/api/system/user/types/types.vo.ts index da5e52cc..cae05cee 100644 --- a/ecom-dmb-frontend/apps/web-antd/src/api/system/user/types/types.vo.ts +++ b/ecom-dmb-frontend/apps/web-antd/src/api/system/user/types/types.vo.ts @@ -12,6 +12,8 @@ export namespace UserVO { id: number; name: string; }; + /** 可切换的可用公司数量 */ + companyCount?: number; /** 部门id */ departmentId?: number; /** 岗位id */ diff --git a/ecom-dmb-frontend/apps/web-antd/src/components/SwitchAccountModal.vue b/ecom-dmb-frontend/apps/web-antd/src/components/SwitchAccountModal.vue index 47fd4b38..0623aaae 100644 --- a/ecom-dmb-frontend/apps/web-antd/src/components/SwitchAccountModal.vue +++ b/ecom-dmb-frontend/apps/web-antd/src/components/SwitchAccountModal.vue @@ -217,11 +217,18 @@ const handleSwitchAccount = async () => { message.warning('请选择要切换的用户'); return; } + if (!formData.value.companyId) { + message.warning('请选择要切换的公司'); + return; + } try { modalApi.setState({ loading: true }); - const result = await switchAccountApi(formData.value.userId); + const result = await switchAccountApi( + formData.value.companyId, + formData.value.userId, + ); // 设置新的token const accessStore = useAccessStore(); diff --git a/ecom-dmb-frontend/apps/web-antd/src/components/SwitchCompanyModal.vue b/ecom-dmb-frontend/apps/web-antd/src/components/SwitchCompanyModal.vue new file mode 100644 index 00000000..5db44571 --- /dev/null +++ b/ecom-dmb-frontend/apps/web-antd/src/components/SwitchCompanyModal.vue @@ -0,0 +1,161 @@ + + + diff --git a/ecom-dmb-frontend/apps/web-antd/src/layouts/basic.vue b/ecom-dmb-frontend/apps/web-antd/src/layouts/basic.vue index 910e252c..2cacf01e 100644 --- a/ecom-dmb-frontend/apps/web-antd/src/layouts/basic.vue +++ b/ecom-dmb-frontend/apps/web-antd/src/layouts/basic.vue @@ -18,6 +18,7 @@ import { useAccessStore, useUserStore } from '@vben/stores'; import ImportTaskButton from '#/components/ImportTaskButton.vue'; import SwitchAccountModal from '#/components/SwitchAccountModal.vue'; +import SwitchCompanyModal from '#/components/SwitchCompanyModal.vue'; import { useAuthStore, useImportTaskStore } from '#/store'; import LoginForm from '#/views/_core/authentication/login.vue'; @@ -70,7 +71,10 @@ onMounted(() => { // 切换账户模态框引用 const switchAccountModalRef = ref(); +const switchCompanyModalRef = ref(); +// 切换公司图标 +const SwitchCompanyIcon = createIconifyIcon('lucide:building-2'); // 切换账户图标 const SwitchAccountIcon = createIconifyIcon('lucide:arrow-left-right'); // 用户图标 @@ -78,6 +82,12 @@ const UserIcon = createIconifyIcon('lucide:user'); // 锁图标 const LockIcon = createIconifyIcon('lucide:lock'); +/** 当前用户可切换的可用公司数 */ +const companyCount = computed(() => { + const info = userStore.userInfo as null | { companyCount?: number }; + return info?.companyCount ?? 0; +}); + const menus = computed(() => { const menuItems = []; @@ -98,6 +108,17 @@ const menus = computed(() => { text: '修改密码', }); + // 可切换公司数大于 1 时显示切换公司 + if (companyCount.value > 1) { + menuItems.push({ + handler: () => { + switchCompanyModalRef.value?.open(); + }, + icon: SwitchCompanyIcon, + text: '切换公司', + }); + } + // 只有超级管理员才显示切换账户功能 if (accessStore.userRole === 'super') { menuItems.push({ @@ -197,6 +218,8 @@ watch( + +