package com.ruoyi.other.service;
|
|
import com.ruoyi.common.core.domain.R;
|
import com.ruoyi.common.core.exception.ServiceException;
|
import com.ruoyi.common.security.service.TokenService;
|
import com.ruoyi.common.security.utils.SecurityUtils;
|
import com.ruoyi.system.api.domain.SysUser;
|
import com.ruoyi.system.api.feignClient.SysUserClient;
|
import com.ruoyi.system.api.model.LoginUser;
|
import lombok.extern.slf4j.Slf4j;
|
import org.springframework.stereotype.Service;
|
|
import javax.annotation.Resource;
|
import java.util.Objects;
|
|
/**
|
* 公司后台账号(roleType=5 且已绑定公司)数据范围及归属校验。
|
*/
|
@Slf4j
|
@Service
|
public class CompanyAccountAccessService {
|
|
private static final Integer COMPANY_ROLE_TYPE = 5;
|
|
@Resource
|
private TokenService tokenService;
|
@Resource
|
private SysUserClient sysUserClient;
|
|
/**
|
* 当前登录账号若为公司账号,返回其所属公司ID;非公司账号返回null。
|
*/
|
public Integer getCurrentCompanyId() {
|
SysUser sysUser = getCurrentSysUser();
|
if (!isCompany(sysUser)) {
|
return null;
|
}
|
return sysUser.getObjectId();
|
}
|
|
/**
|
* 数据范围强制:公司账号只允许访问本公司数据,覆盖前端传入的公司筛选;非公司账号保持原值。
|
*/
|
public Integer resolveCompanyFilter(Integer requestCompanyId) {
|
Integer currentCompanyId = getCurrentCompanyId();
|
return currentCompanyId != null ? currentCompanyId : requestCompanyId;
|
}
|
|
/**
|
* 公司账号数据归属校验:记录不属于本公司时拒绝操作;非公司账号不做限制。
|
*/
|
public void assertCompanyVisible(Integer recordCompanyId) {
|
Integer currentCompanyId = getCurrentCompanyId();
|
if (currentCompanyId == null) {
|
return;
|
}
|
if (!Objects.equals(currentCompanyId, recordCompanyId)) {
|
throw new ServiceException("无权操作其他公司的数据");
|
}
|
}
|
|
private boolean isCompany(SysUser sysUser) {
|
return sysUser != null && Objects.equals(COMPANY_ROLE_TYPE, sysUser.getRoleType())
|
&& sysUser.getObjectId() != null;
|
}
|
|
private SysUser getCurrentSysUser() {
|
LoginUser loginUser = null;
|
try {
|
loginUser = tokenService.getLoginUser();
|
} catch (Exception ignored) {
|
// 尝试从安全上下文继续获取。
|
}
|
if (loginUser == null) {
|
try {
|
loginUser = SecurityUtils.getLoginUser();
|
} catch (Exception ignored) {
|
// 当前请求不是管理后台登录上下文。
|
}
|
}
|
if (loginUser == null) {
|
return null;
|
}
|
if (loginUser.getSysUser() != null && loginUser.getSysUser().getRoleType() != null) {
|
return loginUser.getSysUser();
|
}
|
if (loginUser.getUserid() == null) {
|
return loginUser.getSysUser();
|
}
|
R<SysUser> userResult = sysUserClient.getSysUser(loginUser.getUserid());
|
return userResult != null && userResult.getData() != null ? userResult.getData() : loginUser.getSysUser();
|
}
|
}
|