mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 23:09:19 +08:00
feat(auth): 超管切换账户迁至 SuperAuthController,新增多公司切换与 companyCount 并收紧 auth 白名单
This commit is contained in:
+1
-1
@@ -42,7 +42,7 @@ public class SecurityConfig {
|
|||||||
.csrf(AbstractHttpConfigurer::disable)
|
.csrf(AbstractHttpConfigurer::disable)
|
||||||
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||||
.authorizeHttpRequests(auth -> auth
|
.authorizeHttpRequests(auth -> auth
|
||||||
.requestMatchers("/auth/**").permitAll()
|
.requestMatchers("/auth/login", "/auth/register", "/auth/refresh").permitAll()
|
||||||
.requestMatchers("/uploads/**").permitAll() // 允许直接访问上传的文件
|
.requestMatchers("/uploads/**").permitAll() // 允许直接访问上传的文件
|
||||||
.requestMatchers("/doc.html", "/webjars/**", "/v3/api-docs/**", "/swagger-resources/**",
|
.requestMatchers("/doc.html", "/webjars/**", "/v3/api-docs/**", "/swagger-resources/**",
|
||||||
"/swagger-ui/**", "/swagger-ui.html")
|
"/swagger-ui/**", "/swagger-ui.html")
|
||||||
|
|||||||
+5
-7
@@ -1,7 +1,6 @@
|
|||||||
package top.xyquan.ecomdmbbackend.modules.sys.auth.controller;
|
package top.xyquan.ecomdmbbackend.modules.sys.auth.controller;
|
||||||
|
|
||||||
import io.swagger.v3.oas.annotations.Operation;
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
import io.swagger.v3.oas.annotations.Parameter;
|
|
||||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
import jakarta.validation.Valid;
|
import jakarta.validation.Valid;
|
||||||
import org.springframework.web.bind.annotation.*;
|
import org.springframework.web.bind.annotation.*;
|
||||||
@@ -55,12 +54,11 @@ public class AuthController {
|
|||||||
return ApiResponse.success("令牌刷新成功", loginVO);
|
return ApiResponse.success("令牌刷新成功", loginVO);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "切换账户", description = "超级管理员切换到指定用户账户,角色保持为super")
|
@Operation(summary = "切换公司", description = "切换当前登录公司上下文并重新签发 token")
|
||||||
@PostMapping("/switch/{userId}")
|
@PostMapping("/switch-company/{companyId}")
|
||||||
public ApiResponse<LoginVO> switchAccount(
|
public ApiResponse<LoginVO> switchCompany(@PathVariable Long companyId) {
|
||||||
@Parameter(description = "目标用户ID") @PathVariable Long userId) {
|
LoginVO loginVO = userService.switchCompany(companyId);
|
||||||
LoginVO loginVO = userService.switchAccount(userId);
|
return ApiResponse.success("切换公司成功", loginVO);
|
||||||
return ApiResponse.success("账户切换成功", loginVO);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "获取用户权限码", description = "获取当前登录用户的权限码列表")
|
@Operation(summary = "获取用户权限码", description = "获取当前登录用户的权限码列表")
|
||||||
|
|||||||
+41
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
+8
@@ -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.UpdateUserInfoDTO;
|
||||||
import top.xyquan.ecomdmbbackend.modules.sys.user.model.dto.UserFilterDTO;
|
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.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.user.model.vo.UserVO;
|
||||||
import top.xyquan.ecomdmbbackend.modules.sys.menu.service.UserMenuService;
|
import top.xyquan.ecomdmbbackend.modules.sys.menu.service.UserMenuService;
|
||||||
import top.xyquan.ecomdmbbackend.modules.sys.user.service.UserService;
|
import top.xyquan.ecomdmbbackend.modules.sys.user.service.UserService;
|
||||||
@@ -43,6 +44,13 @@ public class UserController {
|
|||||||
return ApiResponse.success("获取用户信息成功", userVO);
|
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 = "更新当前登录用户的基本信息")
|
@Operation(summary = "更新用户信息", description = "更新当前登录用户的基本信息")
|
||||||
@PutMapping("/info")
|
@PutMapping("/info")
|
||||||
@RequirePermission(value = "system:user:update", description = "更新用户信息", allowSuper = true)
|
@RequirePermission(value = "system:user:update", description = "更新用户信息", allowSuper = true)
|
||||||
|
|||||||
+5
@@ -20,6 +20,11 @@ public class UserVO {
|
|||||||
*/
|
*/
|
||||||
private UserCompanySummaryVO company;
|
private UserCompanySummaryVO company;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 当前用户可切换的可用公司数量(成员正常且公司未停用/未过期)
|
||||||
|
*/
|
||||||
|
private Integer companyCount;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 部门id
|
* 部门id
|
||||||
*/
|
*/
|
||||||
|
|||||||
+25
-3
@@ -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.dto.UserFilterDTO;
|
||||||
import top.xyquan.ecomdmbbackend.modules.sys.user.model.po.UserPO;
|
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.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 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);
|
LoginVO refreshToken(RefreshTokenDTO refreshTokenDTO);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 切换账户
|
* 切换账户(超级管理员)
|
||||||
|
* <p>
|
||||||
|
* 以目标用户身份生成 token,系统角色保持 super。
|
||||||
|
* 若传入 companyId,则校验目标用户是否为该公司成员,并以其作为登录公司上下文。
|
||||||
*
|
*
|
||||||
* @param userId 目标用户ID
|
* @param userId 目标用户ID
|
||||||
|
* @param companyId 目标公司ID(指定切换后的公司上下文)
|
||||||
* @return 登录响应
|
* @return 登录响应
|
||||||
*/
|
*/
|
||||||
LoginVO switchAccount(Long userId);
|
LoginVO switchAccount(Long userId, Long companyId);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 分页查询用户列表
|
* 分页查询用户列表
|
||||||
@@ -96,4 +103,19 @@ public interface UserService extends IService<UserPO> {
|
|||||||
* @return 分页结果
|
* @return 分页结果
|
||||||
*/
|
*/
|
||||||
PageResultVO<UserVO> getUserPage(PageQueryDTO<UserFilterDTO> pageQuery);
|
PageResultVO<UserVO> getUserPage(PageQueryDTO<UserFilterDTO> pageQuery);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取当前用户可切换的可用公司列表
|
||||||
|
*
|
||||||
|
* @return 公司摘要列表
|
||||||
|
*/
|
||||||
|
List<UserCompanySummaryVO> getAvailableCompanies();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 切换当前登录公司上下文,重新签发 token
|
||||||
|
*
|
||||||
|
* @param companyId 目标公司ID
|
||||||
|
* @return 新的登录响应
|
||||||
|
*/
|
||||||
|
LoginVO switchCompany(Long companyId);
|
||||||
}
|
}
|
||||||
|
|||||||
+103
-5
@@ -186,6 +186,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserPO> implements
|
|||||||
UserVO userVO = new UserVO();
|
UserVO userVO = new UserVO();
|
||||||
BeanUtils.copyProperties(user, userVO);
|
BeanUtils.copyProperties(user, userVO);
|
||||||
fillCompanyFromCurrentToken(userVO);
|
fillCompanyFromCurrentToken(userVO);
|
||||||
|
userVO.setCompanyCount(countAvailableCompanies(userId));
|
||||||
return userVO;
|
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
|
* @return 登录VO
|
||||||
*/
|
*/
|
||||||
@Override
|
@Override
|
||||||
public LoginVO switchAccount(Long userId) {
|
public LoginVO switchAccount(Long userId, Long companyId) {
|
||||||
// 查询目标用户信息
|
if (companyId == null) {
|
||||||
|
throw new BusinessException("目标公司不能为空");
|
||||||
|
}
|
||||||
|
|
||||||
UserPO targetUser = this.getById(userId);
|
UserPO targetUser = this.getById(userId);
|
||||||
if (targetUser == null) {
|
if (targetUser == null) {
|
||||||
throw new BusinessException("目标用户不存在");
|
throw new BusinessException("目标用户不存在");
|
||||||
}
|
}
|
||||||
|
|
||||||
// 检查目标用户状态
|
|
||||||
if (targetUser.getStatus() != 1) {
|
if (targetUser.getStatus() != 1) {
|
||||||
throw new BusinessException("目标用户状态异常,无法切换");
|
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");
|
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
|
* @param pageQuery 分页查询DTO
|
||||||
@@ -511,6 +588,27 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserPO> implements
|
|||||||
userVO.setCompany(summary);
|
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());
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 生成登录响应
|
* 生成登录响应
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -117,8 +117,19 @@ export async function getAccessCodesApi() {
|
|||||||
/**
|
/**
|
||||||
* 切换账户(超级管理员功能)
|
* 切换账户(超级管理员功能)
|
||||||
*/
|
*/
|
||||||
export async function switchAccountApi(userId: number) {
|
export async function switchAccountApi(companyId: number, userId: number) {
|
||||||
return requestClient.post<AuthApi.LoginResult>(`/auth/switch/${userId}`);
|
return requestClient.post<AuthApi.LoginResult>(
|
||||||
|
`/super/auth/switch/company/${companyId}/user/${userId}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 切换公司(重新签发 token)
|
||||||
|
*/
|
||||||
|
export async function switchCompanyApi(companyId: number) {
|
||||||
|
return requestClient.post<AuthApi.LoginResult>(
|
||||||
|
`/auth/switch-company/${companyId}`,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -14,6 +14,13 @@ export async function getUserInfoApi() {
|
|||||||
return requestClient.get<UserVO.UserInfoVO>('/user/info');
|
return requestClient.get<UserVO.UserInfoVO>('/user/info');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取当前用户可切换的可用公司列表
|
||||||
|
*/
|
||||||
|
export async function getAvailableCompaniesApi() {
|
||||||
|
return requestClient.get<Array<{ id: number; name: string }>>('/user/companies');
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 更新用户信息
|
* 更新用户信息
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -12,6 +12,8 @@ export namespace UserVO {
|
|||||||
id: number;
|
id: number;
|
||||||
name: string;
|
name: string;
|
||||||
};
|
};
|
||||||
|
/** 可切换的可用公司数量 */
|
||||||
|
companyCount?: number;
|
||||||
/** 部门id */
|
/** 部门id */
|
||||||
departmentId?: number;
|
departmentId?: number;
|
||||||
/** 岗位id */
|
/** 岗位id */
|
||||||
|
|||||||
@@ -217,11 +217,18 @@ const handleSwitchAccount = async () => {
|
|||||||
message.warning('请选择要切换的用户');
|
message.warning('请选择要切换的用户');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if (!formData.value.companyId) {
|
||||||
|
message.warning('请选择要切换的公司');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
modalApi.setState({ loading: true });
|
modalApi.setState({ loading: true });
|
||||||
|
|
||||||
const result = await switchAccountApi(formData.value.userId);
|
const result = await switchAccountApi(
|
||||||
|
formData.value.companyId,
|
||||||
|
formData.value.userId,
|
||||||
|
);
|
||||||
|
|
||||||
// 设置新的token
|
// 设置新的token
|
||||||
const accessStore = useAccessStore();
|
const accessStore = useAccessStore();
|
||||||
|
|||||||
@@ -0,0 +1,161 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, ref } from 'vue';
|
||||||
|
import { useRouter } from 'vue-router';
|
||||||
|
|
||||||
|
import { useVbenModal } from '@vben/common-ui';
|
||||||
|
import { useTabs } from '@vben/hooks';
|
||||||
|
import { preferences } from '@vben/preferences';
|
||||||
|
import { useAccessStore, useUserStore } from '@vben/stores';
|
||||||
|
|
||||||
|
import { message, Radio, Spin } from 'ant-design-vue';
|
||||||
|
|
||||||
|
import { getAccessCodesApi, switchCompanyApi } from '#/api/core/auth';
|
||||||
|
import { getAvailableCompaniesApi } from '#/api/system/user';
|
||||||
|
import { useAuthStore } from '#/store';
|
||||||
|
|
||||||
|
interface CompanyOption {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const userStore = useUserStore();
|
||||||
|
const accessStore = useAccessStore();
|
||||||
|
const authStore = useAuthStore();
|
||||||
|
const { closeAllTabs } = useTabs();
|
||||||
|
const router = useRouter();
|
||||||
|
|
||||||
|
const loading = ref(false);
|
||||||
|
const companyList = ref<CompanyOption[]>([]);
|
||||||
|
const selectedCompanyId = ref<number>();
|
||||||
|
|
||||||
|
const currentCompanyId = computed(() => {
|
||||||
|
const info = userStore.userInfo as null | { company?: { id?: number } };
|
||||||
|
return info?.company?.id;
|
||||||
|
});
|
||||||
|
|
||||||
|
const companyOptions = computed(() =>
|
||||||
|
companyList.value.map((company) => ({
|
||||||
|
label: company.name,
|
||||||
|
value: company.id,
|
||||||
|
disabled: company.id === currentCompanyId.value,
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
|
||||||
|
async function loadCompanies() {
|
||||||
|
loading.value = true;
|
||||||
|
try {
|
||||||
|
companyList.value = await getAvailableCompaniesApi();
|
||||||
|
selectedCompanyId.value = companyList.value.find(
|
||||||
|
(item) => item.id !== currentCompanyId.value,
|
||||||
|
)?.id;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('加载公司列表失败:', error);
|
||||||
|
message.error('加载公司列表失败');
|
||||||
|
} finally {
|
||||||
|
loading.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleSwitchCompany() {
|
||||||
|
if (!selectedCompanyId.value) {
|
||||||
|
message.warning('请选择要切换的公司');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (selectedCompanyId.value === currentCompanyId.value) {
|
||||||
|
message.warning('当前已在该公司,无需切换');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
modalApi.setState({ loading: true });
|
||||||
|
|
||||||
|
const result = await switchCompanyApi(selectedCompanyId.value);
|
||||||
|
|
||||||
|
accessStore.setTokens(
|
||||||
|
result.accessToken,
|
||||||
|
result.refreshToken,
|
||||||
|
result.accessTokenExpiresAt,
|
||||||
|
result.refreshTokenExpiresAt,
|
||||||
|
);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const accessCodes = await getAccessCodesApi();
|
||||||
|
accessStore.setAccessCodes(accessCodes);
|
||||||
|
} catch (error) {
|
||||||
|
console.warn('获取用户权限码失败:', error);
|
||||||
|
accessStore.setAccessCodes([]);
|
||||||
|
}
|
||||||
|
|
||||||
|
await authStore.fetchUserInfo();
|
||||||
|
accessStore.setIsAccessChecked(false);
|
||||||
|
await closeAllTabs();
|
||||||
|
await router.replace(preferences.app.defaultHomePath);
|
||||||
|
|
||||||
|
message.success('切换公司成功');
|
||||||
|
modalApi.close();
|
||||||
|
window.location.reload();
|
||||||
|
} catch (error: any) {
|
||||||
|
console.error('切换公司失败:', error);
|
||||||
|
message.error(error?.message || '切换公司失败');
|
||||||
|
} finally {
|
||||||
|
modalApi.setState({ loading: false });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const [ModalComponent, modalApi] = useVbenModal({
|
||||||
|
onCancel() {
|
||||||
|
modalApi.close();
|
||||||
|
},
|
||||||
|
onConfirm: async () => {
|
||||||
|
await handleSwitchCompany();
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
function openModal() {
|
||||||
|
modalApi.open();
|
||||||
|
selectedCompanyId.value = undefined;
|
||||||
|
loadCompanies();
|
||||||
|
}
|
||||||
|
|
||||||
|
function closeModal() {
|
||||||
|
modalApi.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
defineExpose({
|
||||||
|
open: openModal,
|
||||||
|
close: closeModal,
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<ModalComponent title="切换公司" width="520px">
|
||||||
|
<div v-if="loading" class="py-8 text-center">
|
||||||
|
<Spin />
|
||||||
|
<div class="mt-2 text-gray-500">加载中...</div>
|
||||||
|
</div>
|
||||||
|
<div v-else-if="companyOptions.length === 0" class="py-8 text-center text-gray-400">
|
||||||
|
暂无可用公司
|
||||||
|
</div>
|
||||||
|
<Radio.Group
|
||||||
|
v-else
|
||||||
|
v-model:value="selectedCompanyId"
|
||||||
|
class="mt-4 flex w-full flex-col gap-3"
|
||||||
|
>
|
||||||
|
<Radio
|
||||||
|
v-for="option in companyOptions"
|
||||||
|
:key="option.value"
|
||||||
|
:value="option.value"
|
||||||
|
:disabled="option.disabled"
|
||||||
|
class="!mr-0 rounded-md border px-3 py-2"
|
||||||
|
>
|
||||||
|
<span>{{ option.label }}</span>
|
||||||
|
<span
|
||||||
|
v-if="option.value === currentCompanyId"
|
||||||
|
class="ml-2 text-xs text-gray-400"
|
||||||
|
>
|
||||||
|
当前
|
||||||
|
</span>
|
||||||
|
</Radio>
|
||||||
|
</Radio.Group>
|
||||||
|
</ModalComponent>
|
||||||
|
</template>
|
||||||
@@ -18,6 +18,7 @@ import { useAccessStore, useUserStore } from '@vben/stores';
|
|||||||
|
|
||||||
import ImportTaskButton from '#/components/ImportTaskButton.vue';
|
import ImportTaskButton from '#/components/ImportTaskButton.vue';
|
||||||
import SwitchAccountModal from '#/components/SwitchAccountModal.vue';
|
import SwitchAccountModal from '#/components/SwitchAccountModal.vue';
|
||||||
|
import SwitchCompanyModal from '#/components/SwitchCompanyModal.vue';
|
||||||
import { useAuthStore, useImportTaskStore } from '#/store';
|
import { useAuthStore, useImportTaskStore } from '#/store';
|
||||||
import LoginForm from '#/views/_core/authentication/login.vue';
|
import LoginForm from '#/views/_core/authentication/login.vue';
|
||||||
|
|
||||||
@@ -70,7 +71,10 @@ onMounted(() => {
|
|||||||
|
|
||||||
// 切换账户模态框引用
|
// 切换账户模态框引用
|
||||||
const switchAccountModalRef = ref();
|
const switchAccountModalRef = ref();
|
||||||
|
const switchCompanyModalRef = ref();
|
||||||
|
|
||||||
|
// 切换公司图标
|
||||||
|
const SwitchCompanyIcon = createIconifyIcon('lucide:building-2');
|
||||||
// 切换账户图标
|
// 切换账户图标
|
||||||
const SwitchAccountIcon = createIconifyIcon('lucide:arrow-left-right');
|
const SwitchAccountIcon = createIconifyIcon('lucide:arrow-left-right');
|
||||||
// 用户图标
|
// 用户图标
|
||||||
@@ -78,6 +82,12 @@ const UserIcon = createIconifyIcon('lucide:user');
|
|||||||
// 锁图标
|
// 锁图标
|
||||||
const LockIcon = createIconifyIcon('lucide:lock');
|
const LockIcon = createIconifyIcon('lucide:lock');
|
||||||
|
|
||||||
|
/** 当前用户可切换的可用公司数 */
|
||||||
|
const companyCount = computed(() => {
|
||||||
|
const info = userStore.userInfo as null | { companyCount?: number };
|
||||||
|
return info?.companyCount ?? 0;
|
||||||
|
});
|
||||||
|
|
||||||
const menus = computed(() => {
|
const menus = computed(() => {
|
||||||
const menuItems = [];
|
const menuItems = [];
|
||||||
|
|
||||||
@@ -98,6 +108,17 @@ const menus = computed(() => {
|
|||||||
text: '修改密码',
|
text: '修改密码',
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// 可切换公司数大于 1 时显示切换公司
|
||||||
|
if (companyCount.value > 1) {
|
||||||
|
menuItems.push({
|
||||||
|
handler: () => {
|
||||||
|
switchCompanyModalRef.value?.open();
|
||||||
|
},
|
||||||
|
icon: SwitchCompanyIcon,
|
||||||
|
text: '切换公司',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
// 只有超级管理员才显示切换账户功能
|
// 只有超级管理员才显示切换账户功能
|
||||||
if (accessStore.userRole === 'super') {
|
if (accessStore.userRole === 'super') {
|
||||||
menuItems.push({
|
menuItems.push({
|
||||||
@@ -197,6 +218,8 @@ watch(
|
|||||||
</template>
|
</template>
|
||||||
</BasicLayout>
|
</BasicLayout>
|
||||||
|
|
||||||
|
<!-- 切换公司模态框 -->
|
||||||
|
<SwitchCompanyModal ref="switchCompanyModalRef" />
|
||||||
<!-- 切换账户模态框 -->
|
<!-- 切换账户模态框 -->
|
||||||
<SwitchAccountModal ref="switchAccountModalRef" />
|
<SwitchAccountModal ref="switchAccountModalRef" />
|
||||||
</template>
|
</template>
|
||||||
|
|||||||
Reference in New Issue
Block a user