优化权限

This commit is contained in:
guoshengxiong 2025-09-12 13:41:52 +08:00
parent 2316971b56
commit bd1c89670a
21 changed files with 478 additions and 123 deletions

View File

@ -8,6 +8,7 @@ import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.handler.DataPermissionHandler;
import com.zhgd.annotation.DataScope;
import com.zhgd.xmgl.modules.basicdata.enums.SystemUserAccountTypeEnum;
import com.zhgd.xmgl.modules.basicdata.service.ICompanyService;
import com.zhgd.xmgl.modules.ocr.service.IOcrBuildLogService;
import com.zhgd.xmgl.modules.video.service.IAiAnalyseHardWareRecordService;
import com.zhgd.xmgl.modules.worker.entity.EnterpriseInfo;
@ -59,6 +60,9 @@ public class DataScopeHandler implements DataPermissionHandler {
IAiAnalyseHardWareRecordService aiAnalyseHardWareRecordService;
@Lazy
@Autowired
ICompanyService companyService;
@Lazy
@Autowired
private XzSupplierQualificationApplyServiceImpl xzSupplierQualificationApplyService;
@Lazy
@Autowired
@ -127,6 +131,12 @@ public class DataScopeHandler implements DataPermissionHandler {
return tables;
}
private HashMap<String, String> getFieldProjectSnTables() {
HashMap<String, String> tables = new HashMap<>(16);
tables.put("notice_remind_sound", getProjectSn());
return tables;
}
private HashMap<String, String> getFieldAiTables() {
HashMap<String, String> tables = new HashMap<>(16);
if (!environmentUtil.isBaise()) {
@ -155,120 +165,36 @@ public class DataScopeHandler implements DataPermissionHandler {
init(plainSelect);
//expressions
List<Expression> expressions = new ArrayList<>();
Long userId = SecurityUtils.getUser().getUserId();
if (!DataScopeInterceptor.findIgnoreDataScope(parameter, ds)) {
if (Objects.equals(user.getAccountType(), SystemUserAccountTypeEnum.ENTERPRISE_ADMINISTRATOR_ACCOUNT.getValue())) {
filterForCompanyOrProject(plainSelect, ds, expressions, userId, (userFilterItem) -> get1CompanySql(userId, userFilterItem));
filterForCompanyOrProject(plainSelect, ds, expressions, SecurityUtils.getUser().getUserId(), (userFilterItem) -> get1CompanySql(SecurityUtils.getUser().getUserId(), userFilterItem));
} else if (Objects.equals(user.getAccountType(), SystemUserAccountTypeEnum.ENTERPRISE_DISTRICT_ACCOUNT.getValue())) {
filterForCompanyOrProject(plainSelect, ds, expressions, userId, (userFilterItem) -> get2CompanySql(userId, userFilterItem));
filterForCompanyOrProject(plainSelect, ds, expressions, SecurityUtils.getUser().getUserId(), (userFilterItem) -> get2CompanySql(SecurityUtils.getUser().getUserId(), userFilterItem));
} else if (Objects.equals(user.getAccountType(), SystemUserAccountTypeEnum.ENTERPRISE_CITY_ACCOUNT.getValue())) {
filterForCompanyOrProject(plainSelect, ds, expressions, userId, (userFilterItem) -> get3CompanySql(userId, userFilterItem));
filterForCompanyOrProject(plainSelect, ds, expressions, SecurityUtils.getUser().getUserId(), (userFilterItem) -> get3CompanySql(SecurityUtils.getUser().getUserId(), userFilterItem));
} else if (Objects.equals(user.getAccountType(), SystemUserAccountTypeEnum.ENTERPRISE_SUB_ACCOUNT.getValue())) {
filterForCompanyOrProject(plainSelect, ds, expressions, userId, (userFilterItem) -> get4CompanySql(userId, userFilterItem));
filterForCompanyOrProject(plainSelect, ds, expressions, SecurityUtils.getUser().getUserId(), (userFilterItem) -> get4CompanySql(SecurityUtils.getUser().getUserId(), userFilterItem));
List<String> projectSns = companyService.getProjectSnsBySn(SecurityUtils.getUser().getSn());
// List<String> filterProjectItems = getNeedFilterLeftExpression(plainSelect, getFieldProjectSnTables(), ds);
// if (CollUtil.isNotEmpty(filterProjectItems)) {
// for (String item : filterProjectItems) {
// inExpression(item, , plainSelect);
// }
// }
} else if (Objects.equals(user.getAccountType(), SystemUserAccountTypeEnum.PROJECT_ACCOUNT.getValue())) {
filterForCompanyOrProject(plainSelect, ds, expressions, userId, (userFilterItem) -> {
filterForCompanyOrProject(plainSelect, ds, expressions, SecurityUtils.getUser().getUserId(), (userFilterItem) -> {
return StrUtil.format(" \n" +
" {} in (\n" +
" select u.sn\n" +
" from system_user u\n" +
" WHERE u.user_id={}\n" +
" ) and {}.account_type = 6", userFilterItem, userId, StrUtil.subBefore(userFilterItem, ".", true));
" ) and {}.account_type = 6", userFilterItem, SecurityUtils.getUser().getUserId(), StrUtil.subBefore(userFilterItem, ".", true));
});
filterProjectForProject(plainSelect, ds);
} else if (Objects.equals(user.getAccountType(), SystemUserAccountTypeEnum.PROJECT_SUB_ACCOUNT.getValue())) {
List<String> authEnterpriseIds = userEnterpriseService.getEnterpriseIdsIfSubProject();
authEnterpriseIds.add("0");
List<String> filterEnterprises = getNeedFilterLeftExpression(plainSelect, getFieldEnterpriseTables(), ds);
if (CollUtil.isNotEmpty(filterEnterprises)) {
for (String filterEnterprise : filterEnterprises) {
inExpression(filterEnterprise, authEnterpriseIds, plainSelect);
}
}
List<String> filterItems = getNeedFilterLeftExpression(plainSelect, getFieldVideoTables(), ds);
if (CollUtil.isNotEmpty(filterItems)) {
List<String> videoItems = userDevAuthorityService.getVideoItemsIfSubProject();
for (String item : filterItems) {
inExpression(item, videoItems, plainSelect);
}
}
List<String> filterAis = getNeedFilterLeftExpression(plainSelect, getFieldAiTables(), ds, true);
if (CollUtil.isNotEmpty(filterAis)) {
List<String> videoItems = aiAnalyseHardWareRecordService.getAiAnalyseHardIdsByUserId();
if (CollUtil.isEmpty(videoItems)) {
videoItems.add("0");
}
videoItems = videoItems.stream().map(s -> "'" + s + "'").collect(Collectors.toList());
for (String filterAi : filterAis) {
String sql = StrUtil.format(" ({}.hardware_id in ({}) OR ({}.quality_region_id in (select distinct quality_region_id from quality_region_to_user where user_id = {}))) ",
filterAi, StrUtil.join(",", videoItems), filterAi, userId);
expressions.add(parseCondExpression(sql));
}
}
//ocr施工日志施工单位
HashMap<String, String> ocrBuildLogTables = new HashMap<>();
ocrBuildLogTables.put("ocr_build_log", "id");
List<String> filterOcrBuildLogTables = getNeedFilterLeftExpression(plainSelect, ocrBuildLogTables, ds);
if (CollUtil.isNotEmpty(filterOcrBuildLogTables)) {
for (String filterEnterprise : filterOcrBuildLogTables) {
String uploaderIdField = StrUtil.subBefore(filterEnterprise, ".", false) + "." + "uploader_id";
String sql = StrUtil.format(" ( ({} in (select ocr_build_log_id from ocr_build_log_enterprise where enterprise_id in ({}))) OR ( {} = {}))",
filterEnterprise, StrUtil.join(",", authEnterpriseIds), uploaderIdField, userId);
try {
Expression expression = CCJSqlParserUtil.parseCondExpression(sql);
expressions.add(expression);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
}
//安全隐患
HashMap<String, String> xzSecurityTables = new HashMap<>();
xzSecurityTables.put("xz_security_quality_inspection_record", "id");
List<String> filterXzSecurityEnterprises = getNeedFilterLeftExpression(plainSelect, xzSecurityTables, ds);
if (CollUtil.isNotEmpty(filterXzSecurityEnterprises)) {
List<String> enterpriseIds = userEnterpriseService.getEnterpriseIdsIfSubProject();
enterpriseIds.add("0");
List<Long> rids = xzSecurityQualityInspectionEnterpriseService.list(new LambdaQueryWrapper<XzSecurityQualityInspectionEnterprise>()
.in(XzSecurityQualityInspectionEnterprise::getEnterpriseId, enterpriseIds)).stream().map(XzSecurityQualityInspectionEnterprise::getInspectionId).collect(Collectors.toList());
rids.add(0L);
for (String item : filterXzSecurityEnterprises) {
inExpression(item, rids.stream().map(Convert::toStr).collect(Collectors.toList()), plainSelect);
}
}
filterByProjectSubAccount(plainSelect, ds, expressions);
} else if (Objects.equals(user.getAccountType(), SystemUserAccountTypeEnum.SUPPLIER.getValue())) {
List<String> filterEnterprises = getNeedFilterLeftExpression(plainSelect, getFieldEnterpriseTables(), ds);
EnterpriseInfo ei = enterpriseInfoMapper.getXzSupplierByUserId(userId);
Long id;
if (ei == null) {
id = -1L;
} else {
id = ei.getId();
}
for (String filterEnterprise : filterEnterprises) {
String sql = StrUtil.format(" ({} = {} OR {} IN ( SELECT DISTINCT t.enterprise_id FROM " +
"(SELECT t.id FROM project_enterprise t WHERE t.enterprise_id = {}) t2 join project_enterprise t on find_in_set( t2.id, ancestors ) )) ",
filterEnterprise, id, filterEnterprise, id);
expressions.add(parseCondExpression(sql));
}
//解析ai预警
List<String> filterAis = getNeedFilterLeftExpression(plainSelect, getFieldAiTables(), ds, true);
if (CollUtil.isNotEmpty(filterAis)) {
List<String> videoItems = aiAnalyseHardWareRecordService.getAiAnalyseHardIdsByEnterpriseId(id);
if (CollUtil.isEmpty(videoItems)) {
videoItems.add("0");
}
videoItems = videoItems.stream().map(s -> "'" + s + "'").collect(Collectors.toList());
for (String filterAi : filterAis) {
String sql = StrUtil.format(" ({}.hardware_id in ({}) OR ({}.quality_region_id in (select distinct quality_region_id from quality_region_to_user where user_id = {}))) ",
filterAi, StrUtil.join(",", videoItems), filterAi, userId);
expressions.add(parseCondExpression(sql));
}
}
filterBySupplier(plainSelect, ds, expressions);
}
if (expressions.size() > 0) {
Expression dataExpression;
@ -338,6 +264,134 @@ public class DataScopeHandler implements DataPermissionHandler {
return plainSelect;
}
/**
* 过滤供应商
*
* @param plainSelect
* @param ds
* @param expressions
*/
private void filterBySupplier(PlainSelect plainSelect, DataScope ds, List<Expression> expressions) {
List<String> filterEnterprises = getNeedFilterLeftExpression(plainSelect, getFieldEnterpriseTables(), ds);
EnterpriseInfo ei = enterpriseInfoMapper.getXzSupplierByUserId(SecurityUtils.getUser().getUserId());
Long id;
if (ei == null) {
id = -1L;
} else {
id = ei.getId();
}
for (String filterEnterprise : filterEnterprises) {
String sql = StrUtil.format(" ({} = {} OR {} IN ( SELECT DISTINCT t.enterprise_id FROM " +
"(SELECT t.id FROM project_enterprise t WHERE t.enterprise_id = {}) t2 join project_enterprise t on find_in_set( t2.id, ancestors ) )) ",
filterEnterprise, id, filterEnterprise, id);
expressions.add(parseCondExpression(sql));
}
//解析ai预警
List<String> filterAis = getNeedFilterLeftExpression(plainSelect, getFieldAiTables(), ds, true);
if (CollUtil.isNotEmpty(filterAis)) {
List<String> videoItems = aiAnalyseHardWareRecordService.getAiAnalyseHardIdsByEnterpriseId(id);
if (CollUtil.isEmpty(videoItems)) {
videoItems.add("0");
}
videoItems = videoItems.stream().map(s -> "'" + s + "'").collect(Collectors.toList());
for (String filterAi : filterAis) {
String sql = StrUtil.format(" ({}.hardware_id in ({}) OR ({}.quality_region_id in (select distinct quality_region_id from quality_region_to_user where user_id = {}))) ",
filterAi, StrUtil.join(",", videoItems), filterAi, SecurityUtils.getUser().getUserId());
expressions.add(parseCondExpression(sql));
}
}
}
/**
* 过滤项目子账号
*
* @param plainSelect
* @param ds
* @param expressions
*/
private void filterByProjectSubAccount(PlainSelect plainSelect, DataScope ds, List<Expression> expressions) {
filterProjectForProject(plainSelect, ds);
List<String> authEnterpriseIds = userEnterpriseService.getEnterpriseIdsIfSubProject();
authEnterpriseIds.add("0");
List<String> filterEnterprises = getNeedFilterLeftExpression(plainSelect, getFieldEnterpriseTables(), ds);
if (CollUtil.isNotEmpty(filterEnterprises)) {
for (String filterEnterprise : filterEnterprises) {
inExpression(filterEnterprise, authEnterpriseIds, plainSelect);
}
}
List<String> filterItems = getNeedFilterLeftExpression(plainSelect, getFieldVideoTables(), ds);
if (CollUtil.isNotEmpty(filterItems)) {
List<String> videoItems = userDevAuthorityService.getVideoItemsIfSubProject();
for (String item : filterItems) {
inExpression(item, videoItems, plainSelect);
}
}
List<String> filterAis = getNeedFilterLeftExpression(plainSelect, getFieldAiTables(), ds, true);
if (CollUtil.isNotEmpty(filterAis)) {
List<String> videoItems = aiAnalyseHardWareRecordService.getAiAnalyseHardIdsByUserId();
if (CollUtil.isEmpty(videoItems)) {
videoItems.add("0");
}
videoItems = videoItems.stream().map(s -> "'" + s + "'").collect(Collectors.toList());
for (String filterAi : filterAis) {
String sql = StrUtil.format(" ({}.hardware_id in ({}) OR ({}.quality_region_id in (select distinct quality_region_id from quality_region_to_user where user_id = {}))) ",
filterAi, StrUtil.join(",", videoItems), filterAi, SecurityUtils.getUser().getUserId());
expressions.add(parseCondExpression(sql));
}
}
//ocr施工日志施工单位
HashMap<String, String> ocrBuildLogTables = new HashMap<>();
ocrBuildLogTables.put("ocr_build_log", "id");
List<String> filterOcrBuildLogTables = getNeedFilterLeftExpression(plainSelect, ocrBuildLogTables, ds);
if (CollUtil.isNotEmpty(filterOcrBuildLogTables)) {
for (String filterEnterprise : filterOcrBuildLogTables) {
String uploaderIdField = StrUtil.subBefore(filterEnterprise, ".", false) + "." + "uploader_id";
String sql = StrUtil.format(" ( ({} in (select ocr_build_log_id from ocr_build_log_enterprise where enterprise_id in ({}))) OR ( {} = {}))",
filterEnterprise, StrUtil.join(",", authEnterpriseIds), uploaderIdField, SecurityUtils.getUser().getUserId());
try {
Expression expression = CCJSqlParserUtil.parseCondExpression(sql);
expressions.add(expression);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
}
//安全隐患
HashMap<String, String> xzSecurityTables = new HashMap<>();
xzSecurityTables.put("xz_security_quality_inspection_record", "id");
List<String> filterXzSecurityEnterprises = getNeedFilterLeftExpression(plainSelect, xzSecurityTables, ds);
if (CollUtil.isNotEmpty(filterXzSecurityEnterprises)) {
List<String> enterpriseIds = userEnterpriseService.getEnterpriseIdsIfSubProject();
enterpriseIds.add("0");
List<Long> rids = xzSecurityQualityInspectionEnterpriseService.list(new LambdaQueryWrapper<XzSecurityQualityInspectionEnterprise>()
.in(XzSecurityQualityInspectionEnterprise::getEnterpriseId, enterpriseIds)).stream().map(XzSecurityQualityInspectionEnterprise::getInspectionId).collect(Collectors.toList());
rids.add(0L);
for (String item : filterXzSecurityEnterprises) {
inExpression(item, rids.stream().map(Convert::toStr).collect(Collectors.toList()), plainSelect);
}
}
}
/**
* 项目账号过滤项目sn
*
* @param plainSelect
* @param ds
*/
private void filterProjectForProject(PlainSelect plainSelect, DataScope ds) {
List<String> filterProjectItems = getNeedFilterLeftExpression(plainSelect, getFieldProjectSnTables(), ds);
if (CollUtil.isNotEmpty(filterProjectItems)) {
for (String item : filterProjectItems) {
equalsTo(item, SecurityUtils.getUser().getSn(), plainSelect);
}
}
}
/**
* 过滤企业或项目的用户权限
*

View File

@ -19,6 +19,7 @@ import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;
@ -89,6 +90,7 @@ public class BaseModuleController {
@ApiImplicitParam(name = "projectSn", value = "项目sn", paramType = "body", required = true, dataType = "String"),
})
@PostMapping(value = "/getProjectModuleList")
@PreAuthorize("@perm.hasProjectSnAccess(#map['projectSn'])")
public Result<List<BaseModule>> getProjectModuleList(@RequestBody Map<String, Object> map) {
return Result.success(baseModuleService.getProjectModuleList(map));
}

View File

@ -9,6 +9,7 @@ import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
@ -42,6 +43,7 @@ public class BaseModuleProjectController {
@ApiImplicitParam(name = "moduleIdStr", value = "模块ID,多个时逗号分割", paramType = "body", required = true, dataType = "String"),
})
@PostMapping(value = "/edit")
@PreAuthorize("@perm.hasSnAccess(#map['sn'])")
public Result edit(@RequestBody Map<String, Object> map) {
baseModuleProjectService.editBaseModuleProject(map);
return Result.ok();

View File

@ -17,6 +17,7 @@ import org.apache.commons.collections.MapUtils;
import org.simpleframework.xml.core.Validate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;
@ -64,6 +65,7 @@ public class CompanyBigScreenConfigController {
@OperLog(operModul = "企业大屏配置管理", operType = "列表查询", operDesc = "列表查询企业大屏配置信息")
@ApiOperation(value = "列表查询企业大屏配置信息", notes = "列表查询企业大屏配置信息", httpMethod = "GET")
@GetMapping(value = "/list")
@PreAuthorize("@perm.hasSnAccess(#param['sn'])")
public Result<List<CompanyBigScreenConfigVo>> queryList(@ApiIgnore @RequestParam HashMap<String, Object> param) {
return Result.success(companyBigScreenConfigService.queryList(param));
}

View File

@ -19,6 +19,7 @@ import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
@ -64,6 +65,7 @@ public class CompanyBigScreenStatisticsController {
@ApiImplicitParam(name = "sn", value = "公司sn", paramType = "body", required = true, dataType = "String"),
})
@PostMapping("/selectCooperateEnterpriseList")
@PreAuthorize("@perm.hasCompanySnAccess(#map['sn'])")
public Result<List<Map<String, Object>>> selectCooperateEnterpriseList(@RequestBody Map<String, Object> map) {
return Result.success(companyBigScreenStatisticsService.selectCooperateEnterpriseList(map));
}

View File

@ -12,6 +12,7 @@ import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
@ -56,11 +57,12 @@ public class CompanyFileController {
@ApiOperation(value = "分页查询自己企业的文件资料记录", notes = "分页查询自己企业的文件资料记录")
@ApiImplicitParams({
@ApiImplicitParam(name = "fileName", value = "文件名称", paramType = "body", required = false, dataType = "String"),
@ApiImplicitParam(name = "companySn", value = "企业总部sn", paramType = "body", required = false, dataType = "String"),
@ApiImplicitParam(name = "companySn", value = "企业总部sn", paramType = "body", required = true, dataType = "String"),
@ApiImplicitParam(name = "pageNo", value = "第几页", paramType = "body", required = true, dataType = "Integer"),
@ApiImplicitParam(name = "pageSize", value = "每页显示条数", paramType = "body", required = true, dataType = "Integer"),
})
@PostMapping("/my/list")
@PreAuthorize("@perm.hasCompanySnAccess(#map['companySn'])")
public Result<Map<String, Object>> selectMyCompanyFileList(@RequestBody Map<String, Object> map) {
return Result.success(companyFileService.selectMyCompanyFileList(map));
}
@ -74,6 +76,7 @@ public class CompanyFileController {
@OperLog(operModul = "企业文件资料管理", operType = "添加企业文件资料信息", operDesc = "添加企业文件资料信息")
@ApiOperation(value = "添加企业文件资料信息", notes = "添加企业文件资料信息", httpMethod = "POST")
@PostMapping(value = "/add")
@PreAuthorize("@perm.hasCompanySnAccess(#companyFile.companySn)")
public Result<CompanyFile> add(@RequestBody CompanyFile companyFile) {
companyFileService.add(companyFile);
return Result.ok();
@ -88,6 +91,7 @@ public class CompanyFileController {
@OperLog(operModul = "企业文件资料管理", operType = "编辑企业文件资料信息", operDesc = "编辑企业文件资料信息")
@ApiOperation(value = "编辑企业文件资料信息", notes = "编辑企业文件资料信息", httpMethod = "POST")
@PostMapping(value = "/edit")
@PreAuthorize("@perm.hasIdAccess('CompanyFile', 'companySn', #companyFile.id)")
public Result<CompanyFile> edit(@RequestBody CompanyFile companyFile) {
companyFileService.edit(companyFile);
return Result.ok();
@ -103,6 +107,7 @@ public class CompanyFileController {
@ApiOperation(value = "删除企业文件资料信息", notes = "删除企业文件资料信息", httpMethod = "POST")
@ApiImplicitParam(name = "id", value = "企业文件资料ID", paramType = "body", required = true, dataType = "Integer")
@PostMapping(value = "/delete")
@PreAuthorize("@perm.hasIdAccess('CompanyFile', 'companySn', #map['id'])")
public Result<CompanyFile> delete(@RequestBody Map<String, Object> map) {
Result<CompanyFile> result = new Result<CompanyFile>();
CompanyFile companyFile = companyFileService.getById(MapUtils.getString(map, "id"));

View File

@ -12,6 +12,7 @@ import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
@ -46,6 +47,7 @@ public class NoticeRemindSoundController {
@ApiImplicitParam(name = "projectSn", value = "项目sn", paramType = "body", required = true, dataType = "String"),
})
@PostMapping(value = "/list")
@PreAuthorize("@perm.hasProjectSnAccess(#map['projectSn'])")
public Result<List<NoticeRemindSound>> selectList(@RequestBody Map<String, Object> map) {
QueryWrapper<NoticeRemindSound> queryWrapper = new QueryWrapper<>();
queryWrapper.lambda().eq(NoticeRemindSound::getProjectSn, MapUtils.getString(map, "projectSn"));
@ -61,6 +63,7 @@ public class NoticeRemindSoundController {
*/
@ApiOperation(value = "添加通知提示音信息", notes = "添加通知提示音信息", httpMethod = "POST")
@PostMapping(value = "/add")
@PreAuthorize("@perm.hasProjectSnAccess(#noticeRemindSound.projectSn)")
public Result<NoticeRemindSound> add(@RequestBody NoticeRemindSound noticeRemindSound) {
noticeRemindSoundService.saveNoticeRemindSound(noticeRemindSound);
return Result.ok();
@ -74,6 +77,7 @@ public class NoticeRemindSoundController {
*/
@ApiOperation(value = "编辑通知提示音信息", notes = "编辑通知提示音信息", httpMethod = "POST")
@PostMapping(value = "/edit")
@PreAuthorize("@perm.hasIdAccess('NoticeRemindSound', 'projectSn', #noticeRemindSound.id)")
public Result<NoticeRemindSound> edit(@RequestBody NoticeRemindSound noticeRemindSound) {
noticeRemindSoundService.editNoticeRemindSound(noticeRemindSound);
return Result.ok();
@ -87,6 +91,7 @@ public class NoticeRemindSoundController {
@ApiOperation(value = "删除通知提示音信息", notes = "删除通知提示音信息", httpMethod = "POST")
@ApiImplicitParam(name = "id", value = "通知提示音ID", paramType = "body", required = true, dataType = "Integer")
@PostMapping(value = "/delete")
@PreAuthorize("@perm.hasIdAccess('NoticeRemindSound', 'projectSn', #map['id'])")
public Result<NoticeRemindSound> delete(@RequestBody Map<String, Object> map) {
Result<NoticeRemindSound> result = new Result<NoticeRemindSound>();
NoticeRemindSound noticeRemindSound = noticeRemindSoundService.getById(MapUtils.getString(map, "id"));
@ -110,6 +115,7 @@ public class NoticeRemindSoundController {
@ApiOperation(value = "通过id查询通知提示音信息", notes = "通过id查询通知提示音信息", httpMethod = "POST")
@ApiImplicitParam(name = "id", value = "通知提示音ID", paramType = "body", required = true, dataType = "Integer")
@PostMapping(value = "/queryById")
@PreAuthorize("@perm.hasIdAccess('NoticeRemindSound', 'projectSn', #map['id'])")
public Result<NoticeRemindSound> queryById(@RequestBody Map<String, Object> map) {
Result<NoticeRemindSound> result = new Result<NoticeRemindSound>();
NoticeRemindSound noticeRemindSound = noticeRemindSoundService.getById(MapUtils.getString(map, "id"));
@ -124,6 +130,7 @@ public class NoticeRemindSoundController {
@ApiOperation(value = "保存通知提示音信息", notes = "保存通知提示音信息", httpMethod = "POST")
@PostMapping(value = "/saveSound")
@PreAuthorize("@perm.hasProjectSnAccess(#noticeRemindSound.projectSn)")
public Result<NoticeRemindSound> saveSound(@RequestBody NoticeRemindSound noticeRemindSound) {
QueryWrapper<NoticeRemindSound> queryWrapper = new QueryWrapper<>();
queryWrapper.lambda()

View File

@ -79,6 +79,7 @@ public class OrganizationJobController {
@OperLog(operModul = "组织岗位", operType = "添加组织岗位信息", operDesc = "添加组织岗位信息")
@ApiOperation(value = "添加组织岗位信息", notes = "添加组织岗位信息", httpMethod = "POST")
@PostMapping(value = "/add")
@PreAuthorize("@perm.hasSnAccess(#organizationJob.sn)")
public Result<OrganizationJob> add(@RequestBody OrganizationJob organizationJob) {
organizationJobService.addOrganizationJob(organizationJob);
return Result.ok();
@ -93,6 +94,7 @@ public class OrganizationJobController {
@OperLog(operModul = "组织岗位", operType = "编辑组织岗位信息", operDesc = "编辑组织岗位信息")
@ApiOperation(value = "编辑组织岗位信息", notes = "编辑组织岗位信息", httpMethod = "POST")
@PostMapping(value = "/edit")
@PreAuthorize("@perm.hasIdAccess('OrganizationJob', 'sn', #organizationJob.id)")
public Result<OrganizationJob> edit(@RequestBody OrganizationJob organizationJob) {
organizationJobService.editOrganizationJob(organizationJob);
return Result.ok();
@ -108,6 +110,7 @@ public class OrganizationJobController {
@ApiOperation(value = "删除组织岗位信息", notes = "删除组织岗位信息", httpMethod = "POST")
@ApiImplicitParam(name = "id", value = "组织岗位ID", paramType = "body", required = true, dataType = "Integer")
@PostMapping(value = "/delete")
@PreAuthorize("@perm.hasIdAccess('OrganizationJob', 'sn', #map['id'])")
public Result<OrganizationJob> delete(@RequestBody Map<String, Object> map) {
Result<OrganizationJob> result = new Result<OrganizationJob>();
OrganizationJob organizationJob = organizationJobService.getById(MapUtils.getString(map, "id"));

View File

@ -73,7 +73,7 @@ public class SystemUserController {
@OperLog(operModul = "账号管理", operType = "编辑账号信息", operDesc = "编辑账号信息")
@ApiOperation(value = "编辑账号信息", notes = "编辑账号信息", httpMethod = "POST")
@PostMapping(value = "/edit")
@PreAuthorize("@perm.hasSnAccess(#systemUser.sn)")
@PreAuthorize("@perm.hasSnAccess(#systemUser.sn) and @perm.hasUserAccess(#systemUser.userId)")
public Result<SystemUser> edit(@RequestBody SystemUser systemUser) {
systemUserService.editSystemUser(systemUser);
return Result.ok();
@ -106,6 +106,7 @@ public class SystemUserController {
@ApiImplicitParam(name = "id", value = "账号ID", paramType = "body", required = true, dataType = "Integer")
})
@PostMapping(value = "/delete")
@PreAuthorize("@perm.hasUserAccess(#map['id'])")
public Result<SystemUser> delete(@RequestBody Map<String, Object> map) {
systemUserService.delete(map);
return Result.ok();

View File

@ -191,4 +191,6 @@ public interface CompanyMapper extends BaseMapper<Company> {
boolean hasProjectSnAccessBy4(@Param("userId") Long userId, @Param("sn") String sn);
List<String> getProjectSnsBySn(@Param("sn") String sn);
}

View File

@ -1,6 +1,7 @@
package com.zhgd.xmgl.modules.basicdata.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.zhgd.annotation.DataScope;
import com.zhgd.xmgl.modules.basicdata.entity.NoticeRemindSound;
import org.apache.ibatis.annotations.Mapper;
@ -11,6 +12,7 @@ import org.apache.ibatis.annotations.Mapper;
* @version V1.0
*/
@Mapper
@DataScope
public interface NoticeRemindSoundMapper extends BaseMapper<NoticeRemindSound> {
}

View File

@ -411,4 +411,12 @@
JOIN system_user u on c.company_sn=u.sn
WHERE u.user_id=#{userId} and p.project_sn = #{sn}
</select>
<select id="getProjectSnsBySn" resultType="java.lang.String">
SELECT distinct a.project_sn
FROM project a
INNER JOIN company cp ON a.company_sn = cp.company_sn
INNER JOIN company b ON cp.parent_id = b.company_id
LEFT JOIN company f ON b.parent_id = f.company_id
</select>
</mapper>

View File

@ -211,4 +211,6 @@ public interface ICompanyService extends IService<Company> {
boolean hasProjectSnAccessBy3(Long userId, String sn);
boolean hasProjectSnAccessBy4(Long userId, String sn);
List<String> getProjectSnsBySn(String sn);
}

View File

@ -1014,6 +1014,11 @@ public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, Company> impl
return baseMapper.hasProjectSnAccessBy4(userId, sn);
}
@Override
public List<String> getProjectSnsBySn(String sn) {
return baseMapper.getProjectSnsBySn(sn);
}
private void recursionFilterData(Map<String, Object> existSnMap, JSONObject clJo, JSONArray rtJa) {
String sn = getSn(clJo);
if (!existSnMap.containsKey(sn)) {

View File

@ -184,6 +184,11 @@ public class SystemUserServiceImpl extends ServiceImpl<SystemUserMapper, SystemU
private XzSystemUserToCompanyProjectMapper xzSystemUserToCompanyProjectMapper;
@Value("${mqtt-scope}")
private String scope;
/**
* 1每次登录都需要验证码
*/
@Value("${needEveryLoginCodeValid:0}")
private String needEveryLoginCodeValid;
@Autowired
private HistoryService historyService;
@Autowired
@ -1639,10 +1644,10 @@ public class SystemUserServiceImpl extends ServiceImpl<SystemUserMapper, SystemU
);
if (CollUtil.isNotEmpty(registryList)) {
//账号待审核
throw new OpenAlertException("用户名或密码错误");
failedPrompt(num);
} else {
//账号不存在
throw new OpenAlertException("用户名或密码错误");
failedPrompt(num);
}
} else {
if (!StringUtils.equalsIgnoreCase(SecureUtil.md5(SecureUtil.md5(systemUser.getShowPassword()) + timestamp), md5Password)) {
@ -1929,7 +1934,7 @@ public class SystemUserServiceImpl extends ServiceImpl<SystemUserMapper, SystemU
Integer failCount = (Integer) redisRepository.get(failedCountKey);
// 如果失败次数3但请求没带验证码或验证码错误则拒绝
needCode = failCount != null && failCount >= 2;
if (needCode) {
if (needCode || Objects.equals(needEveryLoginCodeValid, "1")) {
if (StrUtil.isBlank(code)) {
throw new OpenAlertException("请输入验证码");
}

View File

@ -16,6 +16,7 @@ import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
@ -196,6 +197,7 @@ public class LargeScreenConfigController {
@ApiOperation(value = " 通过项目SN查询", notes = "通过项目SN查询", httpMethod = "POST")
@ApiImplicitParam(name = "projectSn", value = "项目SN", paramType = "body", required = false)
@PostMapping(value = "/queryByProject")
@PreAuthorize("@perm.hasSnAccess(#largeScreenConfig.projectSn)")
public Result<LargeScreenConfig> queryByProject(@ApiIgnore @RequestBody LargeScreenConfig largeScreenConfig) {
QueryWrapper<LargeScreenConfig> queryWrapper = QueryGenerator.initQueryWrapper(largeScreenConfig);
LargeScreenConfig config = largeScreenConfigService.getOne(queryWrapper);

View File

@ -85,6 +85,7 @@ public class ProjectController {
@ApiOperation(value = "企业大屏统计项目信息", notes = "企业大屏统计项目信息")
@ApiImplicitParam(name = "companySn", value = "总公司sn", paramType = "body", required = true, dataType = "String")
@PostMapping("/selectProjectListByCompany")
@PreAuthorize("@perm.hasCompanySnAccess(#map['companySn'])")
public Result<CompanyProjectStat> selectProjectListByCompany(@RequestBody Map<String, Object> map) {
return Result.success(projectService.selectProjectListByCompany(map));
}

View File

@ -60,6 +60,8 @@ public class UfaceRecognitionController {
public static final String LINUX = "linux";
@Value("${basePath}")
private String basePath;
@Value("${enableCheckFace}")
private String enableCheckFace;
@Autowired
private IWorkerInfoService workerInfoService;
@Autowired
@ -89,6 +91,11 @@ public class UfaceRecognitionController {
String message = "message";
String projectSn = MapUtils.getString(map, "projectSn");
String fileUrl = MapUtils.getString(map, "fileUrl");
if (Objects.equals(enableCheckFace, "0")) {
data.put(checkType, sucType);
data.put(message, "成功");
return Result.success(data);
}
WorkerManufacturer workerManufacturer = workerManufacturerFactory.getWorkerManufacturer(projectSn);
if (workerManufacturer != null) {
if (StringUtils.isNotEmpty(fileUrl)) {

View File

@ -43,7 +43,7 @@ public class MyUserDetailsImpl implements UserDetailsService {
return "admin";
}
});
return new UserInfo(username, user.getPassword(), true, true, true, true, grantedAuthorityList, user.getUserId(), user.getAccountType(), user.getRealName());
return new UserInfo(username, user.getPassword(), true, true, true, true, grantedAuthorityList, user.getUserId(), user.getAccountType(), user.getRealName(), user.getSn());
}
}

View File

@ -1,16 +1,34 @@
package com.zhgd.xmgl.security;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zhgd.jeecg.common.util.SpringContextUtils;
import com.zhgd.xmgl.constant.Cts;
import com.zhgd.xmgl.modules.basicdata.entity.Company;
import com.zhgd.xmgl.modules.basicdata.entity.SystemUser;
import com.zhgd.xmgl.modules.basicdata.enums.SystemUserAccountTypeEnum;
import com.zhgd.xmgl.modules.basicdata.service.ICompanyService;
import com.zhgd.xmgl.modules.basicdata.service.ISystemUserService;
import com.zhgd.xmgl.modules.project.service.IProjectService;
import com.zhgd.xmgl.modules.worker.entity.UserEnterprise;
import com.zhgd.xmgl.modules.worker.entity.WorkerInfo;
import com.zhgd.xmgl.modules.worker.service.IUserEnterpriseService;
import com.zhgd.xmgl.modules.worker.service.IWorkerInfoService;
import com.zhgd.xmgl.security.entity.UserInfo;
import com.zhgd.xmgl.security.util.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Objects;
@Slf4j
@Component("perm")
public class PermissionEvaluator {
@Lazy
@ -19,6 +37,15 @@ public class PermissionEvaluator {
@Lazy
@Autowired
private IProjectService projectService;
@Lazy
@Autowired
private ISystemUserService systemUserService;
@Lazy
@Autowired
private IUserEnterpriseService userEnterpriseService;
@Lazy
@Autowired
private IWorkerInfoService workerInfoService;
/**
* 有企业sn的权限
@ -62,27 +89,233 @@ public class PermissionEvaluator {
*/
public boolean hasSnAccess(String sn) {
UserInfo user = SecurityUtils.getUser();
if (user == null) {
return false;
}
int c = companyService.count(new LambdaQueryWrapper<Company>()
.eq(Company::getCompanySn, sn));
if (c > 0) {
return hasCompanySnAccess(sn);
} else {
if (user.getAccountType().equals(SystemUserAccountTypeEnum.ENTERPRISE_ADMINISTRATOR_ACCOUNT.getValue())) {
return companyService.hasProjectSnAccessBy1(user.getUserId(), sn);
} else if (user.getAccountType().equals(SystemUserAccountTypeEnum.ENTERPRISE_DISTRICT_ACCOUNT.getValue())) {
return companyService.hasProjectSnAccessBy2(user.getUserId(), sn);
} else if (user.getAccountType().equals(SystemUserAccountTypeEnum.ENTERPRISE_CITY_ACCOUNT.getValue())) {
return companyService.hasProjectSnAccessBy3(user.getUserId(), sn);
} else if (user.getAccountType().equals(SystemUserAccountTypeEnum.ENTERPRISE_SUB_ACCOUNT.getValue())) {
return companyService.hasProjectSnAccessBy4(user.getUserId(), sn);
} else if (user.getAccountType().equals(SystemUserAccountTypeEnum.PROJECT_ACCOUNT.getValue())) {
return projectService.hasProjectSnAccess(user.getUserId(), sn);
} else if (user.getAccountType().equals(SystemUserAccountTypeEnum.PROJECT_SUB_ACCOUNT.getValue())) {
return projectService.hasProjectSnAccess(user.getUserId(), sn);
} else if (user.getAccountType().equals(SystemUserAccountTypeEnum.NEW_USER.getValue())) {
return projectService.hasProjectSnAccessByNewUser(user.getUserId(), sn);
}
return hasProjectSnAccess(sn);
}
return true;
}
/**
* 有项目sn的权限
*
* @param projectSn
* @return
*/
public boolean hasProjectSnAccess(String projectSn) {
UserInfo owner = SecurityUtils.getUser();
if (owner.getAccountType().equals(SystemUserAccountTypeEnum.ENTERPRISE_ADMINISTRATOR_ACCOUNT.getValue())) {
return companyService.hasProjectSnAccessBy1(owner.getUserId(), projectSn);
} else if (owner.getAccountType().equals(SystemUserAccountTypeEnum.ENTERPRISE_DISTRICT_ACCOUNT.getValue())) {
return companyService.hasProjectSnAccessBy2(owner.getUserId(), projectSn);
} else if (owner.getAccountType().equals(SystemUserAccountTypeEnum.ENTERPRISE_CITY_ACCOUNT.getValue())) {
return companyService.hasProjectSnAccessBy3(owner.getUserId(), projectSn);
} else if (owner.getAccountType().equals(SystemUserAccountTypeEnum.ENTERPRISE_SUB_ACCOUNT.getValue())) {
return companyService.hasProjectSnAccessBy4(owner.getUserId(), projectSn);
} else if (owner.getAccountType().equals(SystemUserAccountTypeEnum.PROJECT_ACCOUNT.getValue())) {
return projectService.hasProjectSnAccess(owner.getUserId(), projectSn);
} else if (owner.getAccountType().equals(SystemUserAccountTypeEnum.PROJECT_SUB_ACCOUNT.getValue())) {
return projectService.hasProjectSnAccess(owner.getUserId(), projectSn);
} else if (owner.getAccountType().equals(SystemUserAccountTypeEnum.NEW_USER.getValue())) {
return projectService.hasProjectSnAccessByNewUser(owner.getUserId(), projectSn);
}
return false;
}
/**
* 能访问这个用户id
*
* @param userId
* @return
*/
public boolean hasUserAccess(String userId) {
SystemUser checkUser = systemUserService.getById(userId);
UserInfo owner = SecurityUtils.getUser();
Integer checkAccountType = checkUser.getAccountType();
Integer ownerAccountType = owner.getAccountType();
if (isCompanyType(checkAccountType)) {
if (!isCompanyType(ownerAccountType)) {
return false;
}
if (!hasCompanySnAccess(checkUser.getSn())) {
return false;
}
String ownerSn = getSn(owner.getUserId() + "");
return !Objects.equals(ownerSn, checkUser.getSn());
} else if (checkAccountType.equals(SystemUserAccountTypeEnum.PROJECT_ACCOUNT.getValue())) {
if (!hasSnAccess(checkUser.getSn())) {
return false;
}
if (isCompanyType(ownerAccountType)) {
return true;
}
String ownerSn = getSn(owner.getUserId() + "");
return !Objects.equals(ownerSn, checkUser.getSn());
} else if (checkAccountType.equals(SystemUserAccountTypeEnum.PROJECT_SUB_ACCOUNT.getValue())) {
if (!hasSnAccess(checkUser.getSn())) {
return false;
}
if (isCompanyType(ownerAccountType)) {
return true;
}
if (ownerAccountType.equals(SystemUserAccountTypeEnum.PROJECT_ACCOUNT.getValue())
|| ownerAccountType.equals(SystemUserAccountTypeEnum.NEW_USER.getValue())) {
return true;
} else {
//项目子账号
UserEnterprise userEnterprise = userEnterpriseService.selectUserEnterpriseByUserId(owner.getUserId());
WorkerInfo workerInfo = workerInfoService.getOne(new LambdaQueryWrapper<WorkerInfo>()
.eq(WorkerInfo::getId, checkUser.getWorkerId()).last(Cts.IGNORE_DATA_SCOPE_CONDITION));
return userEnterprise != null && StrUtil.isNotBlank(userEnterprise.getEnterpriseId())
&& workerInfo != null && userEnterprise.getEnterpriseId().contains(Convert.toStr(workerInfo.getEnterpriseId()));
}
} else if (checkAccountType.equals(SystemUserAccountTypeEnum.NEW_USER.getValue())) {
if (isProjectType(ownerAccountType) || ownerAccountType.equals(SystemUserAccountTypeEnum.NEW_USER.getValue())) {
return false;
}
return true;
}
return false;
}
/**
* 获取账号的sn
*
* @param userId
* @return
*/
private String getSn(String userId) {
SystemUser user = systemUserService.getById(userId);
if (isCompanyType(user.getAccountType())
|| user.getAccountType().equals(SystemUserAccountTypeEnum.PROJECT_ACCOUNT.getValue())
|| user.getAccountType().equals(SystemUserAccountTypeEnum.PROJECT_SUB_ACCOUNT.getValue())
) {
return user.getSn();
}
return null;
}
/**
* 是项目级别账号
*
* @param accountType
* @return
*/
private boolean isProjectType(Integer accountType) {
return accountType.equals(SystemUserAccountTypeEnum.PROJECT_ACCOUNT.getValue())
|| accountType.equals(SystemUserAccountTypeEnum.PROJECT_SUB_ACCOUNT.getValue());
}
/**
* 是企业级别账号
*
* @param accountType
* @return
*/
private boolean isCompanyType(Integer accountType) {
return accountType.equals(SystemUserAccountTypeEnum.ENTERPRISE_ADMINISTRATOR_ACCOUNT.getValue())
|| accountType.equals(SystemUserAccountTypeEnum.ENTERPRISE_DISTRICT_ACCOUNT.getValue())
|| accountType.equals(SystemUserAccountTypeEnum.ENTERPRISE_CITY_ACCOUNT.getValue())
|| accountType.equals(SystemUserAccountTypeEnum.ENTERPRISE_SUB_ACCOUNT.getValue());
}
/**
* 通用ID权限验证方法id的entityClassName.fieldName查询出sn通过sn判断是否有权限
*
* @param entityClassName 实体类名
* @param snFieldName sn属性字段名
* @param id 实体ID值
* @return 是否有权限
*/
public boolean hasIdAccess(String entityClassName, String snFieldName, String id) {
if (StringUtils.isBlank(entityClassName) || StringUtils.isBlank(snFieldName) || id == null) {
return false;
}
try {
// 1. 根据实体类名获取对应的实体对象
Object entity = getEntityById(entityClassName, id);
if (entity == null) {
return true;
}
// 2. 通过反射获取指定字段的值
Object fieldValue = getFieldValue(entity, snFieldName);
if (fieldValue == null) {
return false;
}
// 3. 调用hasSnAccess进行权限验证
return hasSnAccess(fieldValue.toString());
} catch (Exception e) {
log.error("权限验证失败 entity: {}, snFieldName: {}, id: {}", entityClassName, snFieldName, id, e);
return false;
}
}
/**
* 根据实体类名和ID获取实体对象
*/
private Object getEntityById(String entityClassName, Serializable id) {
switch (entityClassName) {
case "XXX":
// return organizationJobMapper.selectById(id);
default:
// 通用反射方式获取需要规范命名
return getEntityByReflection(entityClassName, id);
}
}
/**
* 反射方式通用获取实体需要规范Mapper命名
*/
private Object getEntityByReflection(String entityClassName, Serializable id) {
try {
String mapperBeanName = StringUtils.uncapitalize(entityClassName) + "Mapper";
Object mapper = SpringContextUtils.getBean(mapperBeanName);
Method selectByIdMethod = mapper.getClass().getMethod("selectById", Serializable.class);
return selectByIdMethod.invoke(mapper, id);
} catch (Exception e) {
log.warn("通过反射获取实体失败: {}", entityClassName, e);
return null;
}
}
/**
* 通过反射获取字段值
*/
private Object getFieldValue(Object entity, String fieldName) {
try {
Field field = entity.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
return field.get(entity);
} catch (Exception e) {
// 尝试通过getter方法获取
return getFieldValueByGetter(entity, fieldName);
}
}
/**
* 通过getter方法获取字段值
*/
private Object getFieldValueByGetter(Object entity, String fieldName) {
try {
String getterMethodName = "get" + StringUtils.capitalize(fieldName);
Method getterMethod = entity.getClass().getMethod(getterMethodName);
return getterMethod.invoke(entity);
} catch (Exception e) {
log.warn("获取字段值失败: {}", fieldName, e);
return null;
}
}
}

View File

@ -12,6 +12,7 @@ public class UserInfo extends User {
* 账号类型1系统管理员jxjadmin2企业管理员账号175120098943企业区账号4企业市账号5项目账号thhy只能看一个项目6项目子账号aq比一个项目更小7企业子账号qyyszh只能看到很多项目的账号,8参建单位9政务
*/
private java.lang.Integer accountType;
private String sn;
public UserInfo(String username, String password, Collection<? extends GrantedAuthority> authorities, Long userId, String realName) {
super(username, password, authorities);
@ -19,11 +20,12 @@ public class UserInfo extends User {
this.realName = realName;
}
public UserInfo(String username, String password, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities, Long userId, Integer accountType, String realName) {
public UserInfo(String username, String password, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities, Long userId, Integer accountType, String realName, String sn) {
super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
this.userId = userId;
this.accountType = accountType;
this.realName = realName;
this.sn = sn;
}
public Long getUserId() {
@ -49,4 +51,12 @@ public class UserInfo extends User {
public void setRealName(String realName) {
this.realName = realName;
}
public String getSn() {
return sn;
}
public void setSn(String sn) {
this.sn = sn;
}
}