Commit 02be8110 authored by kang.nie@inzymeits.com's avatar kang.nie@inzymeits.com
Browse files

初始化代码

parent e9f88257
Pipeline #3111 failed with stages
in 0 seconds
package com.cusc.nirvana.user.eiam.service.impl;
import com.cache.CacheFactory;
import com.cache.exception.CacheException;
import com.cusc.nirvana.common.result.Response;
import com.cusc.nirvana.user.auth.identification.service.ICaptchaService;
import com.cusc.nirvana.user.config.SmsPropertyConfig;
import com.cusc.nirvana.user.eiam.constants.RedisConstant;
import com.cusc.nirvana.user.eiam.constants.ResponseCode;
import com.cusc.nirvana.user.eiam.dto.ApplicationDTO;
import com.cusc.nirvana.user.eiam.dto.SmsResponseDTO;
import com.cusc.nirvana.user.eiam.dto.SmsSendConfig;
import com.cusc.nirvana.user.eiam.dto.SmsSendDTO;
import com.cusc.nirvana.user.eiam.service.IEiamSmsService;
import com.cusc.nirvana.user.exception.CuscUserException;
import com.cusc.nirvana.user.util.CuscStringUtils;
import com.cusc.nirvana.user.util.DateUtils;
import com.cusc.nirvana.user.util.RestTemplateUtils;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
/**
* Description: 短信service
* <br />
* CreateDate 2021-11-02 20:25:49
*
* @author yuyi
**/
@Service
@Slf4j
public class EiamSmsServiceImpl implements IEiamSmsService {
private static final Logger LOGGER = LoggerFactory.getLogger(EiamSmsServiceImpl.class);
@Autowired
private RestTemplate restTemplate;
@Autowired
private SmsPropertyConfig smsPropertyConfig;
@Autowired
private CacheFactory cacheFactory;
@Autowired
private ICaptchaService captchaService;
@Override
public SmsResponseDTO sendSms(String phone, List<String> paramterList, SmsSendConfig config) {
SmsSendDTO send = new SmsSendDTO();
send.setAccesskey(config.getSmsPlatformKey());
List<String> phoneList = new ArrayList<>();
phoneList.add(phone);
send.setPhoneNumbers(phoneList);
send.setTemplateParams(paramterList);
send.setSignatureCode(config.getSmsSignatureCode());
send.setStrategyCode(config.getStrategyCode());
send.setTemplateCode(config.getSmsTemplateCode());
Response<SmsResponseDTO> retResp;
try {
retResp = RestTemplateUtils.postForResponse(restTemplate,
smsPropertyConfig.getSmsUrl() + smsPropertyConfig.getSendUrl(),
send,
SmsResponseDTO.class);
} catch (Exception e) {
LOGGER.error("短信发送失败: ", e);
throw new CuscUserException(ResponseCode.SMS_SEND_ERROR.getCode(),
ResponseCode.SMS_SEND_ERROR.getMsg());
}
//记录短信发送次数和间隔
saveSmsSendLimitToRedis(phone, config);
if (retResp != null) {
return retResp.getData();
}
return null;
}
@Override
public SmsResponseDTO sendSms(String phone, String parameter, SmsSendConfig config) {
List<String> list = new ArrayList<>();
list.add(parameter);
return sendSms(phone, list, config);
}
@Override
public boolean checkSmsConfigNotNull(SmsSendConfig bean) {
return bean != null && CuscStringUtils.isNotEmpty(bean.getSmsTemplateCode());
}
/**
* Description: 短信发送限制检查
* <br />
* CreateDate 2022-01-27 14:43:41
*
* @author yuyi
**/
@Override
public void checkSmsSendLimit(String phone, SmsSendConfig bean) {
try {
if (bean.getSmsTotalLimit() != null && bean.getSmsTotalLimit() > 0 && CuscStringUtils.isNotEmpty(
bean.getTotalLimitKey())) {
//记录发送总次数限制
Integer smsTotal =
cacheFactory.getExpireStringService().getValue(
bean.getTotalLimitKey() + phone + "_" + bean.getTenantNo() + "_" + bean.getAppId(),
Integer.class);
if (smsTotal != null && smsTotal >= bean.getSmsTotalLimit()) {
throw new CuscUserException(ResponseCode.SMS_TOTAL_LIMIT_OVERRUN.getCode(),
ResponseCode.SMS_TOTAL_LIMIT_OVERRUN.getMsg());
}
}
if (bean.getSmsIntervalLimit() != null && bean.getSmsIntervalLimit() > 0 && CuscStringUtils.isNotEmpty(
bean.getIntervalLimitKey())) {
//记录发送间隔限制
boolean isExists =
cacheFactory.getExpireStringService()
.containsKey(bean.getIntervalLimitKey() + phone + "_" + bean.getTenantNo() + "_"
+ bean.getAppId());
if (isExists) {
throw new CuscUserException(ResponseCode.SMS_INTERVAL_LIMIT_OVERRUN.getCode(),
ResponseCode.SMS_INTERVAL_LIMIT_OVERRUN.getMsg());
}
}
} catch (Exception e) {
//只记录,不抛出异常,屏蔽对业务的影响
log.error("检查短信发送限制信息时访问redis 异常:", e);
}
}
@Override
public void convertToSmsConfig(ApplicationDTO fromBean, SmsSendConfig toBean) {
//短信配置为空,从应用配置中取
if (!checkSmsConfigNotNull(toBean)) {
throw new CuscUserException(ResponseCode.SMS_CONFIG_NOT_NULL.getCode(),
ResponseCode.SMS_CONFIG_NOT_NULL.getMsg());
}
if (toBean.getSmsPlatformKey() == null) {
if (fromBean.getSmsPlatformKey() == null) {
log.warn("sms config smsPlatformKey is null");
throw new CuscUserException(ResponseCode.SMS_CONFIG_NOT_NULL.getCode() + "",
ResponseCode.SMS_CONFIG_NOT_NULL.getMsg());
}
toBean.setSmsPlatformKey(fromBean.getSmsPlatformKey());
}
if (toBean.getSmsSignatureCode() == null) {
if (fromBean.getSmsSignatureCode() == null) {
log.warn("sms config smsSignatureCode is null");
throw new CuscUserException(ResponseCode.SMS_CONFIG_NOT_NULL.getCode() + "",
ResponseCode.SMS_CONFIG_NOT_NULL.getMsg());
}
toBean.setSmsSignatureCode(fromBean.getSmsSignatureCode());
}
}
@Override
public Response<Boolean> checkSmsCaptcha(String phone, String tenantNo, String appId, String smsCode) {
String smsCaptcha;
try {
String smsCaptchaKey = RedisConstant.SMS_CAPTCHA_KEY + phone + "_" + tenantNo + "_" + appId;
smsCaptcha = cacheFactory.getExpireStringService().getValue(smsCaptchaKey, String.class);
if (CuscStringUtils.isEmpty(smsCaptcha) || !smsCaptcha.equals(smsCode)) {
captchaService.checkSmsCaptchaErrorCount(phone, tenantNo,
appId);
return Response.createError(ResponseCode.SMS_CAPTCHA_INVALID.getMsg(),
ResponseCode.SMS_CAPTCHA_INVALID.getCode() + "");
}
//验证成功之后清理验证码
cacheFactory.getExpireStringService().delete(smsCaptchaKey);
captchaService.delSmsCaptchaErrorCount(phone, tenantNo, appId);
} catch (CacheException e) {
log.error("checkSmsCaptcha 获取reids失败 :", e);
Response.createError(ResponseCode.SMS_GET_CAPTCHA_FAIL.getMsg(),
ResponseCode.SMS_GET_CAPTCHA_FAIL.getCode() + "");
}
return Response.createSuccess(true);
}
//----------------私有方法区域--------------------------
/**
* Description: 保存短信发送限制信息到redis
* <br />
* CreateDate 2022-02-16 09:50:25
*
* @author yuyi
**/
private void saveSmsSendLimitToRedis(String phone, SmsSendConfig bean) {
try {
if (bean.getSmsTotalLimit() != null && bean.getSmsTotalLimit() > 0 && CuscStringUtils.isNotEmpty(
bean.getTotalLimitKey())) {
//记录发送总次数限制
Integer smsTotal =
cacheFactory.getExpireStringService().getValue(
bean.getTotalLimitKey() + phone + "_" + bean.getTenantNo() + "_" + bean.getAppId(),
Integer.class);
Long expireTime;
if (smsTotal == null) {
smsTotal = 1;
LocalDateTime begin = LocalDateTime.now();
expireTime = DateUtils.secondBetween(begin, DateUtils.getDayEnd(begin));
} else {
smsTotal++;
expireTime =
cacheFactory.getExpireStringService()
.getKeyExpireTime(bean.getTotalLimitKey() + phone + "_" + bean.getTenantNo() + "_"
+ bean.getAppId());
}
cacheFactory.getExpireStringService()
.setExpireValue(
bean.getTotalLimitKey() + phone + "_" + bean.getTenantNo() + "_" + bean.getAppId(),
smsTotal,
expireTime.intValue());
}
if (bean.getSmsIntervalLimit() != null && bean.getSmsIntervalLimit() > 0 && CuscStringUtils.isNotEmpty(
bean.getIntervalLimitKey())) {
//记录发送间隔限制
cacheFactory.getExpireStringService()
.setExpireValue(
bean.getIntervalLimitKey() + phone + "_" + bean.getTenantNo() + "_" + bean.getAppId(),
1,
bean.getSmsIntervalLimit());
}
} catch (Exception e) {
//只记录,不抛出异常,屏蔽对业务的影响
log.error("保存短信发送限制信息到redis 异常:", e);
}
}
}
package com.cusc.nirvana.user.eiam.service.impl;
import com.cache.CacheFactory;
import com.cache.exception.CacheException;
import com.cusc.nirvana.common.result.Response;
import com.cusc.nirvana.user.eiam.constants.RedisConstant;
import com.cusc.nirvana.user.eiam.constants.ResponseCode;
import com.cusc.nirvana.user.eiam.dto.UserTokenListDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.util.List;
/**
* Description: 令牌service实现类
* <br />
* CreateDate 2021-11-02 20:25:49
*
* @author yuyi
**/
@Service
@Slf4j
public class EiamTokenService {
@Autowired
private CacheFactory cacheFactory;
/**
* Description: 根据用户id和租户编号踢出
* <br />
* CreateDate 2022-02-17 19:58:58
*
* @author yuyi
**/
public Response kickOutByUserId(String userId, String tenantNo ) {
//通过用户id和应用id找到对应的token信息
try {
String userTokenListKey = RedisConstant.TOKEN_USER_TOKEN_INFO + tenantNo + ":" + userId;
List<UserTokenListDTO> userList =
cacheFactory.getExpireListService().getList(userTokenListKey, UserTokenListDTO.class);
if (CollectionUtils.isEmpty(userList)) {
return Response.createSuccess();
}
for (UserTokenListDTO userToken : userList) {
//删除刷新token
cacheFactory.getExpireHashService()
.delete(RedisConstant.TOKEN_REFRESH_TOKEN_INFO + userToken.getRefresh());
//删除访问token
cacheFactory.getExpireHashService()
.delete(RedisConstant.TOKEN_ACCESS_TOKEN_INFO + userToken.getAccess());
}
//删除用户token的集合
cacheFactory.getExpireListService().delete(userTokenListKey);
} catch (CacheException e) {
log.error("kickOutByUserId 访问reids失败 :{}", e);
return Response.createError(ResponseCode.KICK_OUT_FAIL.getMsg(), ResponseCode.KICK_OUT_FAIL.getCode() + "");
}
return Response.createSuccess();
}
}
package com.cusc.nirvana.user.eiam.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cusc.nirvana.common.result.PageResult;
import com.cusc.nirvana.rds.mybatis.PageHelper;
import com.cusc.nirvana.user.eiam.constants.CommonDeleteEnum;
import com.cusc.nirvana.user.eiam.constants.CommonStatusEnum;
import com.cusc.nirvana.user.eiam.constants.EiamConstant;
import com.cusc.nirvana.user.eiam.constants.ResponseCode;
import com.cusc.nirvana.user.eiam.converter.OrganizationConverter;
import com.cusc.nirvana.user.eiam.dao.OrganizationDao;
import com.cusc.nirvana.user.eiam.dao.entity.OrganizationPO;
import com.cusc.nirvana.user.eiam.dto.OrganizationDTO;
import com.cusc.nirvana.user.eiam.dto.UserDTO;
import com.cusc.nirvana.user.eiam.dto.UserOrganDTO;
import com.cusc.nirvana.user.eiam.service.IOrganizationService;
import com.cusc.nirvana.user.eiam.service.IUserOrganService;
import com.cusc.nirvana.user.eiam.service.IUserService;
import com.cusc.nirvana.user.exception.CuscUserException;
import com.cusc.nirvana.user.util.CuscStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* 组织机构(Organization)表服务实现类
*
* @author yuy336
* @since 2022-01-12 14:59:30
*/
@Service
public class OrganizationServiceImpl extends ServiceImpl<OrganizationDao, OrganizationPO>
implements IOrganizationService {
@Resource
private IUserOrganService userOrganService;
@Resource
private IUserService userService;
/**
* 通过UUID查询单条数据
*
* @param organization
* @return 实例对象
*/
@Override
public OrganizationDTO getByUuid(OrganizationDTO organization) {
OrganizationPO organizationPO = this.getPoByUuid(organization.getUuid(), organization.getTenantNo());
return OrganizationConverter.INSTANCE.poToDto(organizationPO);
}
/**
* 通过查询条件查询集合数据
*
* @param organization
* @return 集合对象
*/
@Override
public List<OrganizationDTO> queryByList(OrganizationDTO organization) {
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.eq("is_delete", CommonDeleteEnum.NORMAL.getCode());
queryWrapper.orderByDesc("create_time");
queryWrapper.eq(CuscStringUtils.isNotEmpty(organization.getTenantNo()),"tenant_no", organization.getTenantNo());
queryWrapper.like(CuscStringUtils.isNotEmpty(organization.getOrganCode()), "organ_code",
organization.getOrganCode());
queryWrapper.like(CuscStringUtils.isNotEmpty(organization.getOrganName()), "organ_name",
organization.getOrganName());
queryWrapper.eq(CuscStringUtils.isNotEmpty(organization.getParentId()), "parent_id",
organization.getParentId());
queryWrapper.eq(organization.getOrganType() != null, "organ_type", organization.getOrganType());
queryWrapper.eq(organization.getStatus() != null, "status", organization.getStatus());
queryWrapper.eq(organization.getBizType() != null, "biz_type", organization.getBizType());
queryWrapper.in(!CollectionUtils.isEmpty(organization.getBizTypeList()),"biz_type",organization.getBizTypeList());
queryWrapper.likeRight(CuscStringUtils.isNotEmpty(organization.getQueryCode()), "query_code",
organization.getQueryCode());
if(!CollectionUtils.isEmpty(organization.getUuidList())){
queryWrapper.in("uuid", organization.getUuidList());
}
List<OrganizationPO> record = this.list(queryWrapper);
return OrganizationConverter.INSTANCE.poListToDtoList(record);
}
/**
* 分页查询
*
* @param organization 筛选条件
* @return 查询结果
*/
@Override
public PageResult<OrganizationDTO> queryByPage(OrganizationDTO organization) {
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.orderByDesc("create_time");
queryWrapper.eq("is_delete", CommonDeleteEnum.NORMAL.getCode());
if (StringUtils.isNotBlank(organization.getTenantNo())) {
queryWrapper.eq("tenant_no", organization.getTenantNo());
}
queryWrapper.like(CuscStringUtils.isNotEmpty(organization.getOrganCode()), "organ_code",
organization.getOrganCode());
queryWrapper.like(CuscStringUtils.isNotEmpty(organization.getOrganName()), "organ_name",
organization.getOrganName());
queryWrapper.like(CuscStringUtils.isNotEmpty(organization.getOrganSimpleName()),"organ_simple_name",organization.getOrganSimpleName());
queryWrapper.eq(CuscStringUtils.isNotEmpty(organization.getParentId()), "parent_id",
organization.getParentId());
queryWrapper.eq(organization.getOrganType() != null, "organ_type", organization.getOrganType());
queryWrapper.eq(organization.getStatus() != null, "status", organization.getStatus());
queryWrapper.eq(organization.getBizType() != null, "biz_type", organization.getBizType());
queryWrapper.eq(CuscStringUtils.isNotEmpty(organization.getUniqueCode()),"unique_code",organization.getUniqueCode());
queryWrapper.likeRight(CuscStringUtils.isNotEmpty(organization.getQueryCode()), "query_code",
organization.getQueryCode());
Page<OrganizationPO> page =
this.page(new Page<>(organization.getCurrPage(), organization.getPageSize()), queryWrapper);
PageResult<OrganizationDTO> result = PageHelper.convert(page, OrganizationDTO.class);
List<OrganizationPO> poList = page.getRecords();
//查询到组织对应的管理员信息
Map<String, UserDTO> adminMap = queryOrganAdmin(poList,null == organization.getParentId() || EiamConstant.DEFAULT_ORGAN_POSTION.equals(organization.getParentId()), organization.getType());
List<OrganizationDTO> dtoList = result.getList();
dtoList.forEach(dto->{
UserDTO userDTO = adminMap.get(dto.getUuid());
if (null != userDTO) {
dto.setAdminUserId(userDTO.getUuid());
dto.setAdminAccount(userDTO.getUserName());
dto.setAdminName(userDTO.getFullName());
dto.setAdminPhone(userDTO.getPhone());
dto.setCreateTime(userDTO.getCreateTime());
}
});
return result;
}
/**
*
* @param poList
* @param tenantAdmin 是否租户管理员
* @return map key--->orgId value-->userInfo
*/
private Map<String, UserDTO> queryOrganAdmin(List<OrganizationPO> poList, boolean tenantAdmin, String type) {
if (CollectionUtils.isEmpty(poList)) {
return Collections.emptyMap();
}
Map<String, OrganizationPO> organMap = poList.stream().collect(Collectors.toMap(OrganizationPO::getUuid, Function.identity(), (k, v) -> v));
List<String> orgUuidList = poList.stream().map(OrganizationPO::getUuid).distinct().collect(Collectors.toList());
UserOrganDTO userOrgDto = new UserOrganDTO();
userOrgDto.setOrganIdList(orgUuidList);
List<UserOrganDTO> userOrganDTOS = userOrganService.queryByList(userOrgDto);
Map<String, String> userOrganMap = userOrganDTOS.stream().collect(Collectors.toMap(UserOrganDTO::getUserId, UserOrganDTO::getOrganId, (k, v) -> v));
//用户id
List<String> userIdList = userOrganDTOS.stream().map(UserOrganDTO::getUserId)
.distinct().collect(Collectors.toList());
//查询用户信息
List<UserDTO> userDTOS;
if(StringUtils.isNotEmpty(type)&&"1".equals(type)){
userDTOS = userService.queryAdminUserListByUserIdListNew(userIdList,tenantAdmin);
}else {
userDTOS = userService.queryAdminUserListByUserIdList(userIdList,tenantAdmin);
}
Map<String, UserDTO> userMap = userDTOS.stream().collect(Collectors.toMap(UserDTO::getUuid, Function.identity(), (k, v) -> v));
Map<String, UserDTO> resultMap = new HashMap<>(poList.size());
userMap.forEach((userId,userDto)->{
String organId = userOrganMap.get(userId);
if (StringUtils.isNotBlank(organId)) {
resultMap.put(organId,userDto);
}
});
return resultMap;
}
/**
* 新增数据
*
* @param organization 实例对象
* @return 实例对象
*/
@Override
@Transactional
public OrganizationDTO insert(OrganizationDTO organization) {
OrganizationPO organizationPO = OrganizationConverter.INSTANCE.dtoToPo(organization);
String orgId = CuscStringUtils.generateUuid();
organizationPO.setUuid(orgId);
//设置查询编码
if (EiamConstant.DEFAULT_ORGAN_POSTION.equals(organization.getParentId())) {
organizationPO.setQueryCode(EiamConstant.DEFAULT_ORGAN_POSTION + EiamConstant.QUERY_CODE_SEPARATOR + orgId);
} else {
//通过父节点查询querycode
OrganizationPO parentPO = getPoByUuid(organization.getParentId(), organization.getTenantNo());
if (parentPO == null) {
throw new CuscUserException(ResponseCode.ORGAN_PARENT_INVALID.getCode(),
ResponseCode.ORGAN_PARENT_INVALID.getMsg());
}
organizationPO.setQueryCode(parentPO.getQueryCode() + EiamConstant.QUERY_CODE_SEPARATOR + orgId);
}
this.save(organizationPO);
organization.setUuid(organizationPO.getUuid());
return organization;
}
/**
* 修改数据
*
* @param organization 实例对象
* @return 实例对象
*/
@Override
@Transactional
public OrganizationDTO update(OrganizationDTO organization) {
OrganizationPO organizationPO = this.getPoByUuid(organization.getUuid(), organization.getTenantNo());
if (null == organizationPO) {
return organization;
}
OrganizationPO updatePo = OrganizationConverter.INSTANCE.dtoToPo(organization);
updatePo.setId(organizationPO.getId());
updatePo.setUuid(null);
updatePo.setOrganCode(null);
updatePo.setTenantNo(null);
//判断父节点是否已修改
if (CuscStringUtils.isNotEmpty(organization.getParentId()) && !organization.getParentId()
.equals(organizationPO.getParentId())) {
//修改当前组织的query code 以及所有下级的query code
//通过父节点查询querycode
OrganizationPO parentPO = getPoByUuid(organization.getParentId(), organization.getTenantNo());
if (parentPO == null) {
throw new CuscUserException(ResponseCode.ORGAN_PARENT_INVALID.getCode(),
ResponseCode.ORGAN_PARENT_INVALID.getMsg());
}
String newQueryCode =
parentPO.getQueryCode() + EiamConstant.QUERY_CODE_SEPARATOR + organizationPO.getUuid();
updateChildQueryCode(organizationPO.getQueryCode(), newQueryCode, organizationPO.getTenantNo());
organizationPO.setQueryCode(newQueryCode);
}
this.updateById(updatePo);
return organization;
}
/**
* 通过主键删除数据
*
* @param organization 实例对象
* @return 是否成功
*/
@Override
@Transactional
public boolean deleteById(OrganizationDTO organization) {
OrganizationPO organizationPO = this.getPoByUuid(organization.getUuid(), organization.getTenantNo());
return this.updateById(organizationPO);
}
@Override
@Transactional
public boolean frozen(OrganizationDTO bean) {
OrganizationPO organPO = this.getPoByUuid(bean.getUuid(), bean.getTenantNo());
if (organPO == null) {
return false;
}
OrganizationPO tmpBean = new OrganizationPO();
tmpBean.setId(organPO.getId());
tmpBean.setStatus(CommonStatusEnum.DISABLE.getCode());
return this.updateById(tmpBean);
}
@Override
@Transactional
public boolean unfreeze(OrganizationDTO bean) {
OrganizationPO organPO = this.getPoByUuid(bean.getUuid(), bean.getTenantNo());
if (organPO == null) {
return false;
}
OrganizationPO tmpBean = new OrganizationPO();
tmpBean.setId(organPO.getId());
tmpBean.setStatus(CommonStatusEnum.ENABLE.getCode());
return this.updateById(tmpBean);
}
@Override
public List<OrganizationDTO> getOrganListByUserId(UserOrganDTO bean) {
return OrganizationConverter.INSTANCE.poListToDtoList(baseMapper.queryOrganListByUserId(bean));
}
//----------私有方法区------------------------
/**
* 通过UUID查询单条数据
*
* @param uuid
* @return 实例对象
*/
private OrganizationPO getPoByUuid(String uuid, String tenantNo) {
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.eq("uuid", uuid);
queryWrapper.eq("is_delete", CommonDeleteEnum.NORMAL.getCode());
queryWrapper.eq(StringUtils.isNotBlank(tenantNo),"tenant_no", tenantNo);
return this.getOne(queryWrapper);
}
/**
* Description: 通过oldQuerycode修改所有下级的queryCode
* <br />
* CreateDate 2022-04-11 15:20:53
*
* @author yuyi
**/
private void updateChildQueryCode(String oldQueryCode, String newQueryCode, String tenantNo) {
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.likeRight("query_code", oldQueryCode);
queryWrapper.eq("is_delete", CommonDeleteEnum.NORMAL.getCode());
queryWrapper.eq("tenant_no", tenantNo);
List<OrganizationPO> orgList = this.list(queryWrapper);
if (!CollectionUtils.isEmpty(orgList)) {
OrganizationPO updatePO;
for (OrganizationPO tempOrg : orgList) {
updatePO = new OrganizationPO();
updatePO.setId(tempOrg.getId());
updatePO.setQueryCode(tempOrg.getQueryCode().replaceAll(oldQueryCode, newQueryCode));
this.updateById(updatePO);
}
}
}
}
package com.cusc.nirvana.user.eiam.service.impl;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cusc.nirvana.common.result.PageResult;
import com.cusc.nirvana.common.result.Response;
import com.cusc.nirvana.rds.mybatis.PageHelper;
import com.cusc.nirvana.user.eiam.constants.CommonDeleteEnum;
import com.cusc.nirvana.user.eiam.constants.CommonStatusEnum;
import com.cusc.nirvana.user.eiam.constants.ResourceAuthTypeEnum;
import com.cusc.nirvana.user.eiam.constants.ResponseCode;
import com.cusc.nirvana.user.eiam.converter.ResourceConverter;
import com.cusc.nirvana.user.eiam.dao.ResourceDao;
import com.cusc.nirvana.user.eiam.dao.entity.ResourcePO;
import com.cusc.nirvana.user.eiam.dto.*;
import com.cusc.nirvana.user.eiam.service.IResourceService;
import com.cusc.nirvana.user.exception.CuscUserException;
import com.cusc.nirvana.user.util.CuscStringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* <p>
* 资源service
* </p>
*
* @author yuy336
* @since 2021-10-20
*/
@Service
@Slf4j
public class ResourceServiceImpl extends ServiceImpl<ResourceDao, ResourcePO> implements IResourceService {
private final static String RESOURCE_SEPARATOR = "-";
@Override
public List<ResourceDTO> queryResourceByRoleId(RoleResourceDTO entity) {
List<ResourcePO> resourceList = baseMapper.queryResourceByRoleId(entity);
List<ResourceDTO> retList = new ArrayList<>();
if (CollectionUtils.isEmpty(resourceList)) {
return retList;
}
ResourceDTO resDTO;
for (ResourcePO resource : resourceList) {
resDTO = new ResourceDTO();
BeanUtils.copyProperties(resource, resDTO);
retList.add(resDTO);
}
return retList;
}
@Override
public Response<List<ResourceSimpleDTO>> query(ResourceDTO entity) {
List<ResourcePO> recordList = queryResourceList(entity);
return Response.createSuccess(getResourceSimple(recordList));
}
private List<ResourcePO> queryResourceList(ResourceDTO entity) {
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.eq("is_delete", CommonDeleteEnum.NORMAL);
queryWrapper.orderByDesc("create_time");
queryWrapper.eq(CuscStringUtils.isNotEmpty(entity.getUuid()), "uuid", entity.getUuid());
queryWrapper.eq(CuscStringUtils.isNotEmpty(entity.getApplicationId()), "application_id", entity.getApplicationId());
queryWrapper.like(CuscStringUtils.isNotEmpty(entity.getResourceName()), "resource_name",
entity.getResourceName());
queryWrapper.eq(CuscStringUtils.isNotEmpty(entity.getParentId()), "parent_id", entity.getParentId());
queryWrapper.eq(entity.getResourceType() != null, "resource_type", entity.getResourceType());
return this.list(queryWrapper);
}
@Override
@Transactional
public Response<Integer> addList(ResourceBatchDTO resourceBatch) {
List<ResourceTreeDTO> resouceList = resourceBatch.getResourceList();
if (CollectionUtils.isEmpty(resouceList)) {
return Response.createSuccess(0);
}
//查询应用下的所有资源code
Set<String> resCodeSetDb = baseMapper.queryResourceCodeSet(resourceBatch.getApplicationId());
Set<String> resCodeSetInput = new HashSet<>();
//树形解析
List<ResourcePO> addList = new ArrayList<>();
getAllResourceNode(resouceList, addList, "0", resourceBatch.getApplicationId(), resourceBatch.getCreator(),
resCodeSetInput, resCodeSetDb);
log.info("ResourceServiceImpl.addList addResourceBatch 的数据:{}", JSON.toJSONString(addList));
baseMapper.addResourceBatch(addList);
//比对出需要删除的资源
List<String> delList = getDelResource(resCodeSetDb, resCodeSetInput);
//删除无效的资源
log.info("ResourceServiceImpl.addList deleteByCode 的数据:{}", JSON.toJSONString(delList));
deleteByCode(delList, resourceBatch.getApplicationId());
return Response.createSuccess(addList.size());
}
@Override
public List<ResourceSimpleDTO> queryResourceByUserId(UserRoleDTO entity) {
List<ResourcePO> resourceList;
if (entity.getAuthType() != null && ResourceAuthTypeEnum.USER.getCode() == entity.getAuthType()) {
resourceList = baseMapper.queryResourceUserByUserId(entity);
} else {
resourceList = baseMapper.queryResourceRoleByUserId(entity);
}
return getResourceSimple(resourceList);
}
@Override
public ResourcePO getResourceDOByCode(ResourceDTO entity) {
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.eq("resource_code", entity.getResourceCode());
queryWrapper.eq("application_id", entity.getApplicationId());
queryWrapper.eq("is_delete", CommonDeleteEnum.NORMAL);
return this.getOne(queryWrapper);
}
/**
* Description:根据资源编码和应用id删除资源信息
* <br />
* CreateDate 2021-10-26 17:40:39
*
* @author yuyi
**/
@Override
@Transactional
public Integer deleteByCode(List<String> codeList, String appId) {
if (CollectionUtils.isEmpty(codeList)) {
return 0;
}
UpdateWrapper updateWrapper = new UpdateWrapper();
updateWrapper.eq("application_id", appId);
updateWrapper.eq("is_delete", CommonDeleteEnum.NORMAL.getCode());
updateWrapper.in("resource_code", codeList);
ResourcePO rrDO = new ResourcePO();
rrDO.setIsDelete(CommonDeleteEnum.DELETED.getCode());
this.update(rrDO, updateWrapper);
return codeList.size();
}
@Override
public void compareResource(List<ResourceTreeDTO> resourceList) {
List<ResourcePO> dbList = queryResourceList(new ResourceDTO());
Set<String> resCodeSetDb = baseMapper.queryResourceCodeSet("1");
Set<String> resCodeSetInput = new HashSet<>();
//树形解析
List<ResourcePO> inputList = new ArrayList<>();
getAllResourceNode(resourceList, inputList, "0", "1", "creater",
resCodeSetInput, resCodeSetDb);
log.info("inputList :" + JSON.toJSONString(inputList));
for (ResourcePO res : inputList) {
boolean isNotExists = true;
for (ResourcePO resTmp : dbList) {
if (res.getResourceCode().equals(resTmp.getResourceCode())) {
isNotExists = false;
}
}
if (isNotExists) {
log.info("compareResource:" + JSON.toJSONString(res));
}
}
}
@Override
public PageResult<ResourceDTO> queryByPage(ResourceDTO bean) {
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.orderByDesc("create_time");
queryWrapper.eq("is_delete", CommonDeleteEnum.NORMAL.getCode());
queryWrapper.like(CuscStringUtils.isNotEmpty(bean.getResourceCode()), "resource_code", bean.getResourceCode());
queryWrapper.like(CuscStringUtils.isNotEmpty(bean.getResourceName()), "resource_name", bean.getResourceName());
queryWrapper.eq(CuscStringUtils.isNotEmpty(bean.getApplicationId()), "application_id", bean.getApplicationId());
queryWrapper.eq(bean.getParentId() != null, "parent_id", bean.getParentId());
queryWrapper.eq(bean.getStatus() != null, "status", bean.getStatus());
Page<ResourcePO> page =
this.page(new Page<>(bean.getCurrPage(), bean.getPageSize()), queryWrapper);
return PageHelper.convert(page, ResourceDTO.class);
}
@Override
public ResourceDTO getByUuid(ResourceDTO bean) {
ResourcePO resourcePO = this.getPoByUuid(bean.getUuid());
return ResourceConverter.INSTANCE.poToDto(resourcePO);
}
@Override
@Transactional
public ResourceDTO add(ResourceDTO resource) {
ResourcePO resourcePO = ResourceConverter.INSTANCE.dtoToPo(resource);
resourcePO.setUuid(CuscStringUtils.generateUuid());
this.save(resourcePO);
resource.setUuid(resourcePO.getUuid());
return resource;
}
@Override
@Transactional
public ResourceDTO update(ResourceDTO bean) {
ResourcePO resourcePO = this.getPoByUuid(bean.getUuid());
if(resourcePO == null){
return null;
}
ResourcePO tmpBean = ResourceConverter.INSTANCE.dtoToPo(bean);
tmpBean.setId(resourcePO.getId());
this.updateById(tmpBean);
return bean;
}
@Override
@Transactional
public boolean deleteById(ResourceDTO resource) {
ResourcePO resourcePO = this.getPoByUuid(resource.getUuid());
if (resourcePO == null) {
throw new CuscUserException(ResponseCode.RESOURCE_INVALID.getCode(),
ResponseCode.RESOURCE_INVALID.getMsg());
}
ResourcePO tmpApp = new ResourcePO();
tmpApp.setId(resourcePO.getId());
tmpApp.setIsDelete(CommonDeleteEnum.DELETED.getCode());
return this.updateById(tmpApp);
}
@Override
@Transactional
public boolean frozen(ResourceDTO resource) {
ResourcePO resourcePO = this.getPoByUuid(resource.getUuid());
if (resourcePO == null) {
throw new CuscUserException(ResponseCode.RESOURCE_INVALID.getCode(),
ResponseCode.RESOURCE_INVALID.getMsg());
}
ResourcePO tmpApp = new ResourcePO();
tmpApp.setId(resourcePO.getId());
tmpApp.setStatus(CommonStatusEnum.DISABLE.getCode());
return this.updateById(tmpApp);
}
@Override
@Transactional
public boolean unfreeze(ResourceDTO resource) {
ResourcePO resourcePO = this.getPoByUuid(resource.getUuid());
if (resourcePO == null) {
throw new CuscUserException(ResponseCode.RESOURCE_INVALID.getCode(),
ResponseCode.RESOURCE_INVALID.getMsg());
}
ResourcePO tmpApp = new ResourcePO();
tmpApp.setId(resourcePO.getId());
tmpApp.setStatus(CommonStatusEnum.ENABLE.getCode());
return this.updateById(tmpApp);
}
/**
* 生成资源sql
*
* @param bean 实体
* @return sql集合
*/
@Override
public Response<List<String>> generateResSql(ResourceDTO bean) {
ResourceDTO paramRes = new ResourceDTO();
List<String> ret = new ArrayList<>();
paramRes.setApplicationId(bean.getApplicationId());
if (bean.isAllChild()) {
ResourcePO tmpRes = this.getPoByUuid(bean.getUuid());
if (tmpRes == null) {
return Response.createSuccess(ret);
}
paramRes.setTreeCode(tmpRes.getTreeCode() + RESOURCE_SEPARATOR);
} else {
paramRes.setUuid(bean.getUuid());
}
ret = baseMapper.generateResSql(paramRes);
return Response.createSuccess(ret);
}
//----------------私有方法区--------------------------------
/**
* Description: 将Resource对象转为Resource简单对象
* <br />
* CreateDate 2021-10-29 15:57:53
*
* @author yuyi
**/
private List<ResourceSimpleDTO> getResourceSimple(List<ResourcePO> recordList) {
List<ResourceSimpleDTO> retList = new ArrayList<>();
ResourceSimpleDTO rsDto;
for (ResourcePO resource : recordList) {
rsDto = new ResourceSimpleDTO();
BeanUtils.copyProperties(resource, rsDto);
retList.add(rsDto);
}
return retList;
}
/**
* 通过UUID查询单条数据
*
* @param uuid
* @return 实例对象
*/
private ResourcePO getPoByUuid(String uuid) {
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.eq("uuid", uuid);
queryWrapper.eq("is_delete", 0);
return this.getOne(queryWrapper);
}
/**
* Description: 获取需要删除的资源
* <br />
* CreateDate 2021-12-02 11:02:13
*
* @author yuyi
**/
private List<String> getDelResource(Set<String> resCodeSetDb, Set<String> resCodeSetInput) {
List<String> ret = new ArrayList<>();
for (String resCode : resCodeSetDb) {
if (!resCodeSetInput.contains(resCode)) {
ret.add(resCode);
}
}
return ret;
}
/**
* Description: 将输入的属性转为List数据
* <br />
* CreateDate 2021-12-02 11:01:18
*
* @author yuyi
**/
private void getAllResourceNode(List<ResourceTreeDTO> children, List<ResourcePO> recordList, String parentUuid,
String appId, String creator, Set<String> resCodeSetInput,
Set<String> resCodeSetDb) {
ResourcePO resource;
ResourcePO temp;
ResourceDTO resDTO;
for (ResourceTreeDTO treeNode : children) {
temp = null;
if (CuscStringUtils.isEmpty(treeNode.getResourceCode())) {
continue;
}
resCodeSetInput.add(treeNode.getResourceCode());
//构建数据库资源
resource = new ResourcePO();
BeanUtils.copyProperties(treeNode, resource);
resource.setParentId(parentUuid);
resource.setApplicationId(appId);
//判断数据库是否存在,存在则查询库中的数据
if (resCodeSetDb.contains(treeNode.getResourceCode())) {
resDTO = new ResourceDTO();
resDTO.setApplicationId(appId);
resDTO.setResourceCode(treeNode.getResourceCode());
//通过code查询资源信息
temp = getResourceDOByCode(resDTO);
}
if (temp != null && CuscStringUtils.isNotEmpty(temp.getUuid())) {
resource.setUuid(temp.getUuid());
resource.setCreator(temp.getCreator());
} else {
resource.setUuid(CuscStringUtils.generateUuid());
resource.setCreator(creator);
}
recordList.add(resource);
if (!CollectionUtils.isEmpty(treeNode.getChildren())) {
getAllResourceNode(treeNode.getChildren(), recordList, resource.getUuid(), appId, creator,
resCodeSetInput,
resCodeSetDb);
}
}
}
}
package com.cusc.nirvana.user.eiam.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cusc.nirvana.common.result.PageResult;
import com.cusc.nirvana.rds.mybatis.PageHelper;
import com.cusc.nirvana.user.eiam.constants.CommonDeleteEnum;
import com.cusc.nirvana.user.eiam.converter.ResourceTempalteConverter;
import com.cusc.nirvana.user.eiam.dao.ResourceTempalteDao;
import com.cusc.nirvana.user.eiam.dao.entity.ResourceTempaltePO;
import com.cusc.nirvana.user.eiam.dto.ResourceTempalteDTO;
import com.cusc.nirvana.user.eiam.service.IResourceTempalteService;
import com.cusc.nirvana.user.util.CuscStringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* (ResourceTempalte)表服务实现类
*
* @author yuy336
* @since 2022-01-11 17:34:45
*/
@Service
public class ResourceTempalteServiceImpl extends ServiceImpl<ResourceTempalteDao, ResourceTempaltePO>
implements IResourceTempalteService {
/**
* 通过UUID查询单条数据
*
* @param resourceTempalte
* @return 实例对象
*/
@Override
public ResourceTempalteDTO getByUuid(ResourceTempalteDTO resourceTempalte) {
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.eq("uuid", resourceTempalte.getUuid());
queryWrapper.eq("is_delete", 0);
ResourceTempaltePO record = this.getOne(queryWrapper);
return ResourceTempalteConverter.INSTANCE.poToDto(record);
}
/**
* 通过查询条件查询集合数据
*
* @param resourceTempalte
* @return 集合对象
*/
@Override
public List<ResourceTempalteDTO> queryByList(ResourceTempalteDTO resourceTempalte) {
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.eq("is_delete", CommonDeleteEnum.NORMAL.getCode());
queryWrapper.orderByDesc("create_time");
queryWrapper.eq(CuscStringUtils.isNotEmpty(resourceTempalte.getApplicationId()), "application_id",
resourceTempalte.getApplicationId());
queryWrapper.eq(CuscStringUtils.isNotEmpty(resourceTempalte.getRoleCode()), "role_code",
resourceTempalte.getRoleCode());
queryWrapper.eq(CuscStringUtils.isNotEmpty(resourceTempalte.getResourceId()), "resource_id",
resourceTempalte.getResourceId());
List<ResourceTempaltePO> record = this.list(queryWrapper);
return ResourceTempalteConverter.INSTANCE.poListToDtoList(record);
}
/**
* 分页查询
*
* @param resourceTempalte 筛选条件
* @return 查询结果
*/
@Override
public PageResult<ResourceTempalteDTO> queryByPage(ResourceTempalteDTO resourceTempalte) {
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.orderByDesc("create_time");
queryWrapper.eq("is_delete", 0);
Page<ResourceTempaltePO> page =
this.page(new Page<>(resourceTempalte.getCurrPage(), resourceTempalte.getPageSize()), queryWrapper);
return PageHelper.convert(page, ResourceTempalteDTO.class);
}
/**
* 新增数据
*
* @param resourceTempalte 实例对象
* @return 实例对象
*/
@Override
@Transactional
public ResourceTempalteDTO insert(ResourceTempalteDTO resourceTempalte) {
ResourceTempaltePO resourceTempaltePO = ResourceTempalteConverter.INSTANCE.dtoToPo(resourceTempalte);
this.save(resourceTempaltePO);
return resourceTempalte;
}
/**
* 修改数据
*
* @param resourceTempalte 实例对象
* @return 实例对象
*/
@Override
@Transactional
public ResourceTempalteDTO update(ResourceTempalteDTO resourceTempalte) {
ResourceTempaltePO resourceTempaltePO = this.getPoByUuid(resourceTempalte.getUuid());
this.updateById(resourceTempaltePO);
return resourceTempalte;
}
/**
* 通过主键删除数据
*
* @param resourceTempalte 实例对象
* @return 是否成功
*/
@Override
@Transactional
public boolean deleteById(ResourceTempalteDTO resourceTempalte) {
ResourceTempaltePO resourceTempaltePO = this.getPoByUuid(resourceTempalte.getUuid());
return this.updateById(resourceTempaltePO);
}
@Override
public List<String> queryResourceIdList(ResourceTempalteDTO bean) {
return baseMapper.queryResourceIdList(bean.getApplicationId(), bean.getRoleCode());
}
/**
* 通过UUID查询单条数据
*
* @param uuid
* @return 实例对象
*/
private ResourceTempaltePO getPoByUuid(String uuid) {
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.eq("uuid", uuid);
queryWrapper.eq("is_delete", 0);
return this.getOne(queryWrapper);
}
}
package com.cusc.nirvana.user.eiam.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cache.CacheFactory;
import com.cusc.nirvana.user.eiam.constants.CommonDeleteEnum;
import com.cusc.nirvana.user.eiam.constants.ResponseCode;
import com.cusc.nirvana.user.eiam.converter.RoleResourceConverter;
import com.cusc.nirvana.user.eiam.dao.RoleResourceDao;
import com.cusc.nirvana.user.eiam.dao.entity.RoleResourcePO;
import com.cusc.nirvana.user.eiam.dto.RoleDTO;
import com.cusc.nirvana.user.eiam.dto.RoleResourceDTO;
import com.cusc.nirvana.user.eiam.service.IRoleResourceService;
import com.cusc.nirvana.user.eiam.service.IRoleService;
import com.cusc.nirvana.user.exception.CuscUserException;
import com.cusc.nirvana.user.util.CuscStringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.List;
/**
* <p>
* 服务实现类
* </p>
*
* @author auto-generator
* @since 2021-10-20
*/
@Service
@Slf4j
public class RoleResourceServiceImpl extends ServiceImpl<RoleResourceDao, RoleResourcePO>
implements IRoleResourceService {
@Autowired
private CacheFactory cacheFactory;
@Autowired
private IRoleService roleService;
@Override
@Transactional
public RoleResourceDTO add(RoleResourceDTO entity) {
//判断是否存在,存在则返回,不存在则新增
List<RoleResourceDTO> rrList = queryByList(entity);
if(!CollectionUtils.isEmpty(rrList)){
return rrList.get(0);
}
entity.setUuid(CuscStringUtils.generateUuid());
RoleResourcePO rrPO = RoleResourceConverter.INSTANCE.dtoToPo(entity);
this.save(rrPO);
return entity;
}
@Override
@Transactional
public Integer addBatchResource(RoleResourceDTO entity) {
//检查是否有租户权限和将关联的中间表删除
deleteByRoleId(entity);
RoleResourcePO rrDO;
List<RoleResourcePO> rrList = new ArrayList<>();
if (!CollectionUtils.isEmpty(entity.getResourceUuidList())) {
//查询角色信息
RoleDTO role = new RoleDTO();
role.setUuid(entity.getRoleId());
role.setTenantNo(entity.getTenantNo());
role = roleService.getByUuid(role);
if (role == null) {
throw new CuscUserException(ResponseCode.ROLE_INVALID.getCode(), ResponseCode.ROLE_INVALID.getMsg());
}
for (String resourceUuid : entity.getResourceUuidList()) {
rrDO = new RoleResourcePO();
rrDO.setRoleId(entity.getRoleId());
rrDO.setResourceId(resourceUuid);
rrDO.setTenantNo(entity.getTenantNo());
rrDO.setApplicationId(role.getApplicationId());
rrDO.setCreator(entity.getCreator());
rrList.add(rrDO);
}
//新增
this.saveBatch(rrList);
}
return rrList.size();
}
@Override
@Transactional
public boolean deleteByRoleId(RoleResourceDTO bean) {
UpdateWrapper updateWrapper = new UpdateWrapper();
updateWrapper.eq("role_id", bean.getRoleId());
updateWrapper.eq("is_delete", CommonDeleteEnum.NORMAL.getCode());
updateWrapper.eq("tenant_no", bean.getTenantNo());
updateWrapper.eq(CuscStringUtils.isNotEmpty(bean.getApplicationId()), "application_id",
bean.getApplicationId());
RoleResourcePO rrDO = new RoleResourcePO();
rrDO.setIsDelete(CommonDeleteEnum.DELETED.getCode());
rrDO.setOperator(bean.getCreator());
this.update(rrDO, updateWrapper);
return true;
}
@Override
@Transactional
public boolean deleteBatchRole(RoleResourceDTO bean) {
UpdateWrapper updateWrapper = new UpdateWrapper();
updateWrapper.eq("resource_id", bean.getResourceId());
updateWrapper.eq("is_delete", CommonDeleteEnum.NORMAL.getCode());
updateWrapper.eq("tenant_no", bean.getTenantNo());
updateWrapper.eq(CuscStringUtils.isNotEmpty(bean.getApplicationId()), "application_id",
bean.getApplicationId());
updateWrapper.in(!CollectionUtils.isEmpty(bean.getRoleIdList()), "role_id", bean.getRoleIdList());
RoleResourcePO rrPO = new RoleResourcePO();
rrPO.setIsDelete(CommonDeleteEnum.DELETED.getCode());
rrPO.setOperator(bean.getOperator());
this.update(rrPO, updateWrapper);
return true;
}
@Override
public List<RoleResourceDTO> queryByList(RoleResourceDTO bean) {
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.eq("is_delete", CommonDeleteEnum.NORMAL.getCode());
queryWrapper.orderByDesc("create_time");
queryWrapper.eq("tenant_no", bean.getTenantNo());
queryWrapper.eq(CuscStringUtils.isNotEmpty(bean.getResourceId()), "resource_id", bean.getResourceId());
queryWrapper.eq(CuscStringUtils.isNotEmpty(bean.getRoleId()), "role_id", bean.getRoleId());
queryWrapper.eq(CuscStringUtils.isNotEmpty(bean.getApplicationId()), "application_id", bean.getApplicationId());
List<RoleResourcePO> record = this.list(queryWrapper);
return RoleResourceConverter.INSTANCE.poListToDtoList(record);
}
}
package com.cusc.nirvana.user.eiam.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cusc.nirvana.common.result.PageResult;
import com.cusc.nirvana.common.result.Response;
import com.cusc.nirvana.rds.mybatis.PageHelper;
import com.cusc.nirvana.user.eiam.constants.CommonDeleteEnum;
import com.cusc.nirvana.user.eiam.constants.CommonStatusEnum;
import com.cusc.nirvana.user.eiam.constants.CommonYesOrNoEnum;
import com.cusc.nirvana.user.eiam.constants.ResponseCode;
import com.cusc.nirvana.user.eiam.converter.RoleConverter;
import com.cusc.nirvana.user.eiam.dao.RoleDao;
import com.cusc.nirvana.user.eiam.dao.entity.RolePO;
import com.cusc.nirvana.user.eiam.dao.entity.UserPO;
import com.cusc.nirvana.user.eiam.dto.RoleDTO;
import com.cusc.nirvana.user.eiam.dto.RoleResourceDTO;
import com.cusc.nirvana.user.eiam.dto.RoleSimpleDTO;
import com.cusc.nirvana.user.eiam.dto.UserRoleDTO;
import com.cusc.nirvana.user.eiam.service.IRoleResourceService;
import com.cusc.nirvana.user.eiam.service.IRoleService;
import com.cusc.nirvana.user.eiam.util.CuscSqlUtils;
import com.cusc.nirvana.user.exception.CuscUserException;
import com.cusc.nirvana.user.util.CuscStringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.List;
/**
* <p>
* 服务实现类
* </p>
*
* @author auto-generator
* @since 2021-10-20
*/
@Service
public class RoleServiceImpl extends ServiceImpl<RoleDao, RolePO> implements IRoleService {
@Autowired
private IRoleResourceService roleResourceService;
@Override
@Transactional
public RoleDTO add(RoleDTO entity) {
RolePO entity0 = new RolePO();
BeanUtils.copyProperties(entity, entity0);
String roleUuid = CuscStringUtils.generateUuid();
entity0.setUuid(roleUuid);
if (CuscStringUtils.isEmpty(entity0.getParentId())) {
entity0.setParentId("0");
}
RoleDTO checkRole = new RoleDTO();
checkRole.setRoleName(entity.getRoleName());
List<RoleSimpleDTO> checkRoleList = queryRoleByParams(checkRole);
if (!CollectionUtils.isEmpty(checkRoleList)) {
throw new CuscUserException(ResponseCode.ROLE_NAME_REPEAT.getCode(),
ResponseCode.ROLE_NAME_REPEAT.getMsg());
}
//新增角色
this.save(entity0);
entity.setUuid(entity0.getUuid());
if (!CollectionUtils.isEmpty(entity.getResourceUuidList())) {
//保存角色与资源的关系
RoleResourceDTO rrDTO = new RoleResourceDTO();
rrDTO.setResourceUuidList(entity.getResourceUuidList());
rrDTO.setRoleId(roleUuid);
rrDTO.setTenantNo(entity.getTenantNo());
rrDTO.setApplicationId(entity.getApplicationId());
rrDTO.setCreator(entity.getCreator());
roleResourceService.addBatchResource(rrDTO);
}
return entity;
}
@Override
@Transactional
public RoleDTO update(RoleDTO entity) {
RolePO entity0 = this.getPoByUuid(entity.getUuid(), entity.getTenantNo());
if (entity0 == null || CommonDeleteEnum.DELETED.getCode() == entity0.getIsDelete()) {
throw new CuscUserException(ResponseCode.ROLE_INVALID.getCode(),
ResponseCode.ROLE_INVALID.getMsg());
}
entity.setId(entity0.getId());
entity.setRoleScene(entity0.getRoleScene());
//检查角色名称是否重复
if(CuscStringUtils.isNotEmpty(entity.getRoleName())){
RoleDTO checkRole = new RoleDTO();
checkRole.setRoleName(entity.getRoleName());
checkRole.setId(entity0.getId());
checkRole.setTenantNo(entity.getTenantNo());
checkRole.setApplicationId(entity.getApplicationId());
List<RoleSimpleDTO> checkRoleList = queryRoleByParams(checkRole);
if (!CollectionUtils.isEmpty(checkRoleList)) {
throw new CuscUserException(ResponseCode.ROLE_NAME_REPEAT.getCode(),
ResponseCode.ROLE_NAME_REPEAT.getMsg());
}
}
//编辑角色与资源的关系
if(!CollectionUtils.isEmpty(entity.getResourceUuidList())){
RoleResourceDTO rrDTO = new RoleResourceDTO();
rrDTO.setResourceUuidList(entity.getResourceUuidList());
rrDTO.setRoleId(entity.getUuid());
rrDTO.setTenantNo(entity.getTenantNo());
rrDTO.setCreator(entity.getOperator());
roleResourceService.addBatchResource(rrDTO);
}
//设置不允许修改
BeanUtils.copyProperties(entity, entity0);
entity0.setUuid(null);
this.updateById(entity0);
return entity;
}
@Override
@Transactional
public RoleDTO delete(RoleDTO entity) {
RolePO entity0 = this.getPoByUuid(entity.getUuid(), entity.getTenantNo());
if (entity0 == null) {
throw new CuscUserException(ResponseCode.ROLE_INVALID.getCode(),
ResponseCode.ROLE_INVALID.getMsg());
}
if (CommonDeleteEnum.DELETED.getCode() == entity0.getIsDelete()) {
return RoleConverter.INSTANCE.poToDto(entity0);
}
//删除角色与资源的关系
RoleResourceDTO rrDTO = new RoleResourceDTO();
rrDTO.setRoleId(entity0.getUuid());
rrDTO.setTenantNo(entity.getTenantNo());
roleResourceService.addBatchResource(rrDTO);
RolePO tmpRole = new RolePO();
tmpRole.setId(entity0.getId());
tmpRole.setIsDelete(CommonDeleteEnum.DELETED.getCode());
tmpRole.setOperator(entity.getOperator());
this.updateById(tmpRole);
return RoleConverter.INSTANCE.poToDto(entity0);
}
@Override
public RoleDTO get(RoleDTO entity) {
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.eq(null != entity.getId() ,"id", entity.getId());
queryWrapper.eq(CuscStringUtils.isNotEmpty(entity.getRoleCode()),"role_code",entity.getRoleCode());
queryWrapper.eq("is_delete", 0);
queryWrapper.eq("tenant_no", entity.getTenantNo());
queryWrapper.eq("application_id",entity.getApplicationId());
RolePO record = this.getOne(queryWrapper);
RoleDTO resp = new RoleDTO();
if (record != null) {
BeanUtils.copyProperties(record, resp);
}
return resp;
}
@Override
public PageResult<RoleDTO> page(RoleDTO entity) {
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.orderByDesc("create_time");
queryWrapper.eq("is_delete", CommonDeleteEnum.NORMAL.getCode());
queryWrapper.eq("tenant_no", entity.getTenantNo());
queryWrapper.eq(CuscStringUtils.isNotEmpty(entity.getApplicationId()), "application_id",
entity.getApplicationId());
queryWrapper.eq(entity.getRoleType() != null, "role_type", entity.getRoleType());
queryWrapper.eq(entity.getStatus() != null, "status", entity.getStatus());
queryWrapper.eq(CuscStringUtils.isNotEmpty(entity.getParentId()), "parent_id", entity.getParentId());
queryWrapper.like(CuscStringUtils.isNotEmpty(entity.getRoleCode()), "role_code", entity.getRoleCode());
queryWrapper.like(CuscStringUtils.isNotEmpty(entity.getRoleName()), "role_name", entity.getRoleName());
queryWrapper.eq(entity.getId() != null, "id", entity.getId());
if (!CollectionUtils.isEmpty(entity.getResourceUuidList())) {
//查询条件如果传了资源id,则增加资源id的校验
StringBuilder existsSql = new StringBuilder();
for (String resUuid : entity.getResourceUuidList()) {
existsSql.append("'");
existsSql.append(CuscSqlUtils.transactSQLInjection(resUuid));
existsSql.append("',");
}
existsSql.deleteCharAt(existsSql.length() - 1);
queryWrapper.exists(
"select 1 from eiam_role_resource where is_delete = 0 and role_id = eiam_role.uuid and tenant_no "
+ "= '"
+ CuscSqlUtils.transactSQLInjection(entity.getTenantNo()) + "' and resource_id in (" + existsSql + ")");
}
if (CuscStringUtils.isNotEmpty(entity.getPositionId())) {
//查询岗位对应的角色信息
queryWrapper.exists(
"select 1 from eiam_position_role where is_delete = 0 and role_id = eiam_role.uuid and tenant_no "
+ "= '"
+ CuscSqlUtils.transactSQLInjection(entity.getTenantNo()) + "' and position_id = '" + CuscSqlUtils.transactSQLInjection(entity.getPositionId()) + "'");
}
if (CuscStringUtils.isNotEmpty(entity.getUserId())) {
//查询岗位对应的角色信息
queryWrapper.exists(
"select 1 from eiam_user_role where is_delete = 0 and role_id = eiam_role.uuid and tenant_no = '"
+ CuscSqlUtils.transactSQLInjection(entity.getTenantNo()) + "' and user_id = '" + CuscSqlUtils.transactSQLInjection(entity.getPositionId()) + "'");
}
Page<UserPO> page =
this.page(new Page<>(entity.getCurrPage(), entity.getPageSize()), queryWrapper);
return PageHelper.convert(page, RoleDTO.class);
}
@Override
public List<RoleSimpleDTO> query(RoleDTO entity) {
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.eq("is_delete", 0);
queryWrapper.eq("tenant_no", entity.getTenantNo());
queryWrapper.orderByDesc("create_time");
queryWrapper.like(CuscStringUtils.isNotEmpty(entity.getRoleName()), "role_name", entity.getRoleName());
queryWrapper.eq(CuscStringUtils.isNotEmpty(entity.getRoleCode()), "role_code",
entity.getRoleCode());
queryWrapper.eq(CuscStringUtils.isNotEmpty(entity.getUuid()), "uuid", entity.getUuid());
queryWrapper.eq(CuscStringUtils.isNotEmpty(entity.getApplicationId()), "application_id",
entity.getApplicationId());
queryWrapper.eq(entity.getRoleType() != null, "role_type", entity.getRoleType());
queryWrapper.eq(entity.getRoleScene() != null, "role_scene", entity.getRoleScene());
queryWrapper.eq(entity.getStatus() != null, "status", entity.getStatus());
queryWrapper.eq(CuscStringUtils.isNotEmpty(entity.getParentId()), "parent_id", entity.getParentId());
List<RolePO> recordList = this.list(queryWrapper);
return getRoleSimple(recordList);
}
@Override
public RoleDTO getByUuid(RoleDTO bean) {
RolePO rolePO = this.getPoByUuid(bean.getUuid(), bean.getTenantNo());
return RoleConverter.INSTANCE.poToDto(rolePO);
}
@Override
public List<RoleSimpleDTO> getByUuids(RoleDTO entity) {
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.in("uuid", entity.getUuidList());
queryWrapper.eq("is_delete", 0);
queryWrapper.eq("tenant_no", entity.getTenantNo());
List<RolePO> recordList = this.list(queryWrapper);
return getRoleSimple(recordList);
}
/**
* Description: 通过用户id查询角色信息
* <br />
* CreateDate 2021-10-29 22:24:25
*
* @author yuyi
**/
@Override
public List<RoleDTO> queryRoleByUserId(UserRoleDTO entity) {
return RoleConverter.INSTANCE.poListToDtoList(baseMapper.queryRoleByUserId(entity));
}
@Override
public List<RoleSimpleDTO> queryRoleByName(RoleDTO entity) {
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.eq("is_delete", 0);
queryWrapper.eq("tenant_no", entity.getTenantNo());
queryWrapper.eq("role_name", entity.getRoleName());
queryWrapper.ne(entity.getId() != null, "id", entity.getId());
queryWrapper.ne("uuid", entity.getUuid());
List<RolePO> recordList = this.list(queryWrapper);
return getRoleSimple(recordList);
}
@Override
public RoleDTO frozen(RoleDTO bean) {
RolePO rolePO = this.getPoByUuid(bean.getUuid(), bean.getTenantNo());
if (rolePO == null) {
throw new CuscUserException(ResponseCode.ROLE_INVALID.getCode(),
ResponseCode.ROLE_INVALID.getMsg());
}
RolePO tmpBean = new RolePO();
tmpBean.setId(rolePO.getId());
tmpBean.setStatus(CommonStatusEnum.DISABLE.getCode());
this.updateById(tmpBean);
return RoleConverter.INSTANCE.poToDto(rolePO);
}
@Override
public RoleDTO unfreeze(RoleDTO bean) {
RolePO rolePO = this.getPoByUuid(bean.getUuid(), bean.getTenantNo());
if (rolePO == null) {
throw new CuscUserException(ResponseCode.ROLE_INVALID.getCode(),
ResponseCode.ROLE_INVALID.getMsg());
}
RolePO tmpBean = new RolePO();
tmpBean.setId(rolePO.getId());
tmpBean.setStatus(CommonStatusEnum.ENABLE.getCode());
this.updateById(tmpBean);
return RoleConverter.INSTANCE.poToDto(rolePO);
}
@Override
public Response<Boolean> queryHideSensitiveByUserId(UserRoleDTO bean) {
List<RoleDTO> roleList = queryRoleByUserId(bean);
if(CollectionUtils.isEmpty(roleList)){
return Response.createSuccess(false);
}
for(RoleDTO role : roleList){
if(role.getHideSensitiveInfo() != null && CommonYesOrNoEnum.YES.getCode() == role.getHideSensitiveInfo()){
return Response.createSuccess(true);
}
}
return Response.createSuccess(false);
}
//----------------私有方法区--------------------------------
/**
* Description:查询角色所有信息
* <br />
* CreateDate 2021-10-26 17:42:09
*
* @author yuyi
**/
private List<RoleSimpleDTO> queryRoleByParams(RoleDTO entity) {
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.eq("is_delete", 0);
queryWrapper.orderByDesc("create_time");
queryWrapper.eq("tenant_no", entity.getTenantNo());
queryWrapper.eq(CuscStringUtils.isNotEmpty(entity.getRoleName()), "role_name", entity.getRoleName());
queryWrapper.eq(CuscStringUtils.isNotEmpty(entity.getRoleCode()), "role_code",
entity.getRoleCode());
queryWrapper.eq(CuscStringUtils.isNotEmpty(entity.getUuid()), "uuid",
entity.getUuid());
queryWrapper.eq(CuscStringUtils.isNotEmpty(entity.getApplicationId()), "application_id", entity.getApplicationId());
queryWrapper.ne(entity.getId() != null, "id", entity.getId());
return getRoleSimple(this.list(queryWrapper));
}
/**
* 通过UUID查询单条数据
*
* @param uuid
* @return 实例对象
*/
private RolePO getPoByUuid(String uuid, String tenantNo) {
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.eq("uuid", uuid);
queryWrapper.eq("is_delete", 0);
queryWrapper.eq("tenant_no", tenantNo);
return this.getOne(queryWrapper);
}
/**
* Description:将role对象转为role简单对象
* <br />
* CreateDate 2021-10-29 16:22:44
*
* @author yuyi
**/
private List<RoleSimpleDTO> getRoleSimple(List<RolePO> recordList) {
List<RoleSimpleDTO> retList = new ArrayList<>();
RoleSimpleDTO rsDto;
for (RolePO role : recordList) {
rsDto = new RoleSimpleDTO();
BeanUtils.copyProperties(role, rsDto);
retList.add(rsDto);
}
return retList;
}
}
package com.cusc.nirvana.user.eiam.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cache.CacheFactory;
import com.cache.exception.CacheException;
import com.cusc.nirvana.common.result.Response;
import com.cusc.nirvana.user.eiam.constants.CommonDeleteEnum;
import com.cusc.nirvana.user.eiam.constants.CommonYesOrNoEnum;
import com.cusc.nirvana.user.eiam.constants.EiamConstant;
import com.cusc.nirvana.user.eiam.constants.RedisConstant;
import com.cusc.nirvana.user.eiam.constants.ResponseCode;
import com.cusc.nirvana.user.eiam.constants.RoleSceneEnum;
import com.cusc.nirvana.user.eiam.dao.UrlDao;
import com.cusc.nirvana.user.eiam.dao.entity.UrlPO;
import com.cusc.nirvana.user.eiam.dto.ApplicationDTO;
import com.cusc.nirvana.user.eiam.dto.EiamUrlDTO;
import com.cusc.nirvana.user.eiam.dto.ResourceUrlSimpleDTO;
import com.cusc.nirvana.user.eiam.dto.UserDTO;
import com.cusc.nirvana.user.eiam.dto.UserRoleDTO;
import com.cusc.nirvana.user.eiam.service.IApplicationService;
import com.cusc.nirvana.user.eiam.service.IUrlService;
import com.cusc.nirvana.user.eiam.service.IUserService;
import com.cusc.nirvana.user.exception.CuscUserException;
import com.cusc.nirvana.user.util.CuscStringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* <p>
* 服务实现类
* </p>
*
* @author auto-generator
* @since 2021-10-20
*/
@Service
@Slf4j
public class UrlServiceImpl extends ServiceImpl<UrlDao, UrlPO> implements IUrlService {
@Autowired
private CacheFactory cacheFactory;
@Autowired
@Lazy
private IUserService userService;
@Autowired
@Lazy
private IApplicationService applicationService;
@Override
public Response<List<ResourceUrlSimpleDTO>> queryAll(Integer isAuth) {
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.eq("is_delete", 0);
queryWrapper.eq("is_auth", isAuth);
List<UrlPO> recordList = this.list(queryWrapper);
return Response.createSuccess(getResourceUrlSimple(recordList));
}
@Override
@Transactional
public Response addList(List<EiamUrlDTO> resourceUrlList) {
return Response.createSuccess(baseMapper.addResourceUrlBatch(resourceUrlList));
}
@Override
public Long queryByUrl(EiamUrlDTO bean) {
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.eq("is_delete", 0);
queryWrapper.eq("url", bean.getUrl());
queryWrapper.eq("application_id", bean.getApplicationId());
UrlPO resourceUrl = this.getOne(queryWrapper);
if (resourceUrl != null) {
return resourceUrl.getId();
}
return null;
}
@Override
public Integer whiteListToRedis() {
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.eq("is_delete", CommonDeleteEnum.NORMAL);
queryWrapper.eq("is_auth", EiamConstant.URL_IS_AUTH_NO);
List<UrlPO> urlList = this.list(queryWrapper);
Set<String> whiteList = new HashSet<>();
if (CollectionUtils.isEmpty(urlList)) {
urlList = new ArrayList<>();
}
for (UrlPO url : urlList) {
whiteList.add(url.getServerName() + url.getUrl());
}
try {
cacheFactory.getSetService().addSet(RedisConstant.URL_WHITE_LIST, whiteList, true);
} catch (CacheException e) {
throw new CuscUserException(ResponseCode.SYS_BUSY.getCode() + "", ResponseCode.SYS_BUSY.getMsg());
}
return urlList.size();
}
@Override
@Transactional
public Long add(EiamUrlDTO bean) {
//检查url是否重复
Long urlId = queryByUrl(bean);
if (urlId != null && urlId > 0) {
return urlId;
}
UrlPO urlDO = new UrlPO();
BeanUtils.copyProperties(bean, urlDO);
this.save(urlDO);
return urlDO.getId();
}
/**
* Description: 将ResourceUrl对象转为ResourceUrl简单对象
* <br />
* CreateDate 2021-10-29 15:57:53
*
* @author yuyi
**/
private List<ResourceUrlSimpleDTO> getResourceUrlSimple(List<UrlPO> recordList) {
List<ResourceUrlSimpleDTO> retList = new ArrayList<>();
ResourceUrlSimpleDTO rusDto;
for (UrlPO resource : recordList) {
rusDto = new ResourceUrlSimpleDTO();
BeanUtils.copyProperties(resource, rusDto);
retList.add(rusDto);
}
return retList;
}
/**
* Description: 将用户授权的url写入redis
* <br />
* CreateDate 2022-01-20 17:13:48
*
* @author yuyi
**/
@Override
@Async("dataToRedisExecutor")
public void userRelUrlToRedis(String userId, String tenantNo, String appId) {
userRoleResUrlToRedis(userId, tenantNo, appId);
}
@Override
@Async("dataToRedisExecutor")
public void userRelRolUrlToRedis(String userId, String tenantNo, String appId) {
userRoleResUrlToRedis(userId, tenantNo, appId);
}
@Override
@Async("dataToRedisExecutor")
public void userRoleResUrlToRedis(String userId, String tenantNo, String appId) {
Set<String> urlSet = baseMapper.queryRoleUrlByUserId(userId, tenantNo, appId);
putUrlRedis(userId, tenantNo, appId, urlSet);
}
/**
* Description: 将用户授权应用的所有url写入redis
* <br />
* CreateDate 2022-01-20 17:13:48
*
* @author yuyi
**/
@Override
@Async("dataToRedisExecutor")
public void userRelAppUrlToRedis(String userId, String tenantNo) {
//查询用户授权的应用,可以使用租户授权的应用查询
ApplicationDTO applicationDTO = new ApplicationDTO();
List<ApplicationDTO> taList = applicationService.queryByList(applicationDTO);
if (CollectionUtils.isEmpty(taList)) {
log.warn("userRelAppUrlToRedis 未找到租户对应的应用。tenantNo:{},userId:{}", tenantNo, userId);
}
for (ApplicationDTO tmpBean : taList) {
userRelUrlToRedis(userId, tenantNo, tmpBean.getApplicationCode());
}
}
/**
* Description: 删除用户对应的
* <br />
* CreateDate 2022-01-20 17:13:48
*
* @author yuyi
**/
@Override
public void delUserRelUrlRedis(String userId, String tenantNo, String appId) {
Set<String> appIdSet = new HashSet<>();
if (CuscStringUtils.isEmpty(appId)) {
//查询用户授权的应用,可以使用租户授权的应用查询
ApplicationDTO applicationDTO = new ApplicationDTO();
List<ApplicationDTO> taList = applicationService.queryByList(applicationDTO);
if (CollectionUtils.isEmpty(taList)) {
log.warn("userRelUrlToRedis 未找到租户对应的应用。tenantNo:{},userId:{}", tenantNo, userId);
}
for (ApplicationDTO tmpBean : taList) {
appIdSet.add(tmpBean.getApplicationCode());
}
} else {
appIdSet.add(appId);
}
for (String appIdStr : appIdSet) {
delUrlRedis(userId, tenantNo, appIdStr);
}
}
/**
* Description: 将角色对应的所有用户url写入redis
* <br />
* CreateDate 2022-01-20 17:13:48
*
* @author yuyi
**/
@Override
@Async("dataToRedisExecutor")
public void roleRelUrlToRedis(String roleId, Integer roleScene, String tenantNo, String appId) {
//判断角色类型
if (RoleSceneEnum.USER.getCode() == roleScene) {
//用户角色:查询角色对应的所有用户
UserRoleDTO userRole = new UserRoleDTO();
userRole.setRoleId(roleId);
userRole.setTenantNo(tenantNo);
userRole.setIsDelete(CommonDeleteEnum.NORMAL.getCode());
List<UserDTO> userList = userService.queryUserByRoleId(userRole);
if (!CollectionUtils.isEmpty(userList)) {
for (UserDTO user : userList) {
userRelUrlToRedis(user.getUuid(), tenantNo, appId);
}
}
}
}
/**
* Description: 将用户集合授权的url写入redis
* <br />
* CreateDate 2022-01-20 17:13:48
*
* @author yuyi
**/
@Override
@Async("dataToRedisExecutor")
public void userListRelUrlToRedis(List<String> userIdList, String tenantNo, String appId) {
if (CollectionUtils.isEmpty(userIdList)) {
log.warn("userListRelUrlToRedis userIdList is empty. ");
}
for (String userId : userIdList) {
userRelUrlToRedis(userId, tenantNo, appId);
}
}
@Override
@Async("dataToRedisExecutor")
public void tenantRelUrlToRedis(String tenantNo, String appId) {
//通过租户查询出租户管理员
UserDTO user = new UserDTO();
user.setTenantNo(tenantNo);
user.setIsTenantAdmin(CommonYesOrNoEnum.YES.getCode());
user = userService.getUser(user);
if (user == null) {
log.warn("tenantRelUrlToRedis:未找到有效的租户管理员账号。tenantNo:{}, appId:{}", tenantNo, appId);
return;
}
Set<String> urlSet = baseMapper.queryUrlByTenantNo(tenantNo, appId);
putUrlRedis(user.getUuid(), tenantNo, appId, urlSet);
}
//------------私有方法区----------------------
private void putUrlRedis(String userId, String tenantNo, String appId, Set<String> urlSet) {
String redisKey = RedisConstant.USER_URL_LIST + tenantNo + ":" + userId + "_" + appId;
if (CollectionUtils.isEmpty(urlSet)) {
log.warn("putUrlRedis urlSet is empty. key:" + redisKey);
return;
}
try {
//将角色对应的url集合放到redis
cacheFactory.getSetService()
.addSet(redisKey, urlSet,
true);
} catch (CacheException e) {
log.warn("putUrlRedis fail key: " + redisKey + " ", e);
}
}
private void delUrlRedis(String userId, String tenantNo, String appId) {
String redisKey = RedisConstant.USER_URL_LIST + tenantNo + ":" + userId + "_" + appId;
try {
//删除redis中角色对应的url集合
cacheFactory.getSetService().delete(redisKey);
} catch (CacheException e) {
log.warn("delUrlRedis fail key: " + redisKey + " ", e);
}
}
}
package com.cusc.nirvana.user.eiam.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cusc.nirvana.common.result.PageResult;
import com.cusc.nirvana.rds.mybatis.PageHelper;
import com.cusc.nirvana.user.eiam.constants.CommonDeleteEnum;
import com.cusc.nirvana.user.eiam.converter.UserOrganConverter;
import com.cusc.nirvana.user.eiam.dao.UserOrganDao;
import com.cusc.nirvana.user.eiam.dao.entity.UserOrganPO;
import com.cusc.nirvana.user.eiam.dto.UserOrganDTO;
import com.cusc.nirvana.user.eiam.service.IUserOrganService;
import com.cusc.nirvana.user.util.CuscStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import java.util.List;
/**
* 用户组织信息(UserOrgan)表服务实现类
*
* @author yuy336
* @since 2022-01-12 15:00:02
*/
@Service
public class UserOrganServiceImpl extends ServiceImpl<UserOrganDao, UserOrganPO> implements IUserOrganService {
/**
* 通过UUID查询单条数据
*
* @param userOrgan
* @return 实例对象
*/
@Override
public UserOrganDTO getByUuid(UserOrganDTO userOrgan) {
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.eq("uuid", userOrgan.getUuid());
queryWrapper.eq("is_delete", 0);
UserOrganPO record = this.getOne(queryWrapper);
return UserOrganConverter.INSTANCE.poToDto(record);
}
/**
* 通过查询条件查询集合数据
*
* @param userOrgan
* @return 集合对象
*/
@Override
public List<UserOrganDTO> queryByList(UserOrganDTO userOrgan) {
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.eq("is_delete", CommonDeleteEnum.NORMAL.getCode());
queryWrapper.orderByDesc("create_time");
queryWrapper.eq(StringUtils.isNotBlank(userOrgan.getTenantNo()),"tenant_no", userOrgan.getTenantNo());
if (!CollectionUtils.isEmpty(userOrgan.getOrganIdList())) {
queryWrapper.in("organ_id",userOrgan.getOrganIdList());
}
queryWrapper.eq(CuscStringUtils.isNotEmpty(userOrgan.getUserId()),"user_id",userOrgan.getUserId());
queryWrapper.eq(CuscStringUtils.isNotEmpty(userOrgan.getOrganId()),"organ_id",userOrgan.getOrganId());
List<UserOrganPO> record = this.list(queryWrapper);
return UserOrganConverter.INSTANCE.poListToDtoList(record);
}
/**
* 分页查询
*
* @param userOrgan 筛选条件
* @return 查询结果
*/
@Override
public PageResult<UserOrganDTO> queryByPage(UserOrganDTO userOrgan) {
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.orderByDesc("create_time");
queryWrapper.eq("is_delete", 0);
Page<UserOrganPO> page =
this.page(new Page<>(userOrgan.getCurrPage(), userOrgan.getPageSize()), queryWrapper);
return PageHelper.convert(page, UserOrganDTO.class);
}
/**
* 新增数据
*
* @param userOrgan 实例对象
* @return 实例对象
*/
@Override
@Transactional
public UserOrganDTO insert(UserOrganDTO userOrgan) {
UserOrganPO userOrganPO = UserOrganConverter.INSTANCE.dtoToPo(userOrgan);
this.save(userOrganPO);
return userOrgan;
}
/**
* 修改数据
*
* @param userOrgan 实例对象
* @return 实例对象
*/
@Override
@Transactional
public UserOrganDTO update(UserOrganDTO userOrgan) {
UserOrganPO userOrganPO = this.getPoByUuid(userOrgan.getUuid());
this.updateById(userOrganPO);
return userOrgan;
}
/**
* 通过主键删除数据
* @param userOrgan 实例对象
* @return 是否成功
*/
@Override
@Transactional
public boolean deleteById(UserOrganDTO userOrgan) {
UserOrganPO userOrganPO = this.getPoByUuid(userOrgan.getUuid());
return this.updateById(userOrganPO);
}
/**
* 通过UUID查询单条数据
*
* @param uuid
* @return 实例对象
*/
private UserOrganPO getPoByUuid(String uuid) {
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.eq("uuid", uuid);
queryWrapper.eq("is_delete", 0);
return this.getOne(queryWrapper);
}
}
package com.cusc.nirvana.user.eiam.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cusc.nirvana.user.eiam.constants.CommonDeleteEnum;
import com.cusc.nirvana.user.eiam.converter.UserResourceConverter;
import com.cusc.nirvana.user.eiam.dao.UserResourceDao;
import com.cusc.nirvana.user.eiam.dao.entity.UserResourcePO;
import com.cusc.nirvana.user.eiam.dto.UserResourceDTO;
import com.cusc.nirvana.user.eiam.service.IUserResourceService;
import com.cusc.nirvana.user.util.CuscStringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.List;
/**
* 用户资源关系(UserResource)表服务实现类
*
* @author yuy336
* @since 2022-01-19 13:41:03
*/
@Service
public class UserResourceServiceImpl extends ServiceImpl<UserResourceDao, UserResourcePO>
implements IUserResourceService {
/**
* 通过查询条件查询集合数据
*
* @param bean
* @return 集合对象
*/
@Override
public List<UserResourceDTO> queryByList(UserResourceDTO bean) {
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.eq("is_delete", CommonDeleteEnum.NORMAL.getCode());
queryWrapper.orderByDesc("create_time");
List<UserResourcePO> record = this.list(queryWrapper);
return UserResourceConverter.INSTANCE.poListToDtoList(record);
}
/**
* 新增数据
*
* @param bean 实例对象
* @return 实例对象
*/
@Override
@Transactional
public UserResourceDTO insert(UserResourceDTO bean) {
UserResourcePO userResourcePO = UserResourceConverter.INSTANCE.dtoToPo(bean);
this.save(userResourcePO);
return bean;
}
@Override
@Transactional
public Integer insertBatchResource(UserResourceDTO bean) {
//先删除
bean.setOperator(bean.getCreator());
deleteByUserId(bean);
List<UserResourcePO> urList = new ArrayList<>();
if(!CollectionUtils.isEmpty(bean.getResourceIdList())){
UserResourcePO urDO;
for (String resourceId : bean.getResourceIdList()) {
urDO = new UserResourcePO();
urDO.setUserId(bean.getUserId());
urDO.setResourceId(resourceId);
urDO.setTenantNo(bean.getTenantNo());
urDO.setApplicationId(bean.getApplicationId());
urList.add(urDO);
}
//新增
this.saveBatch(urList);
}
return urList.size();
}
@Override
@Transactional
public boolean deleteByUserId(UserResourceDTO bean) {
UpdateWrapper updateWrapper = new UpdateWrapper();
updateWrapper.eq("user_id", bean.getUserId());
updateWrapper.eq("is_delete", CommonDeleteEnum.NORMAL.getCode());
updateWrapper.eq("tenant_no", bean.getTenantNo());
updateWrapper.eq(CuscStringUtils.isNotEmpty(bean.getApplicationId()), "application_id",
bean.getApplicationId());
UserResourcePO urDO = new UserResourcePO();
urDO.setIsDelete(CommonDeleteEnum.DELETED.getCode());
urDO.setOperator(bean.getOperator());
this.update(urDO, updateWrapper);
return false;
}
}
package com.cusc.nirvana.user.eiam.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cache.CacheFactory;
import com.cusc.nirvana.common.result.Response;
import com.cusc.nirvana.user.eiam.constants.CommonDeleteEnum;
import com.cusc.nirvana.user.eiam.constants.RoleSceneEnum;
import com.cusc.nirvana.user.eiam.converter.UserRoleConverter;
import com.cusc.nirvana.user.eiam.dao.UserRoleDao;
import com.cusc.nirvana.user.eiam.dao.entity.UserRolePO;
import com.cusc.nirvana.user.eiam.dto.UserRoleDTO;
import com.cusc.nirvana.user.eiam.service.IUrlService;
import com.cusc.nirvana.user.eiam.service.IUserRoleService;
import com.cusc.nirvana.user.util.CuscStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import java.util.*;
/**
* <p>
* 用户角色服务实现类
* </p>
*
* @author auto-generator
* @since 2021-10-20
*/
@Service
public class UserRoleServiceImpl extends ServiceImpl<UserRoleDao, UserRolePO> implements IUserRoleService {
@Autowired
private CacheFactory cacheFactory;
@Autowired
@Lazy
private IUrlService urlService;
@Override
@Transactional
public UserRoleDTO add(UserRoleDTO bean) {
//新增
UserRolePO userRolePO = UserRoleConverter.INSTANCE.dtoToPo(bean);
this.save(userRolePO);
//将用户对应的url放到redis
urlService.userRelRolUrlToRedis(bean.getUserId(), userRolePO.getTenantNo(), userRolePO.getApplicationId());
return bean;
}
@Override
@Transactional
public Response addBatchRole(UserRoleDTO entity) {
//先删除
deleteByUser(entity);
List<UserRolePO> urList = new ArrayList<>();
if (!CollectionUtils.isEmpty(entity.getRoleUuidList())) {
UserRolePO urDO;
for (String roleUuid : entity.getRoleUuidList()) {
urDO = new UserRolePO();
urDO.setUserId(entity.getUserId());
urDO.setRoleId(roleUuid);
urDO.setTenantNo(entity.getTenantNo());
urDO.setApplicationId(entity.getApplicationId());
urList.add(urDO);
}
//新增
this.saveBatch(urList);
}
//将用户对应的url放到redis
urlService.userRelRolUrlToRedis(entity.getUserId(), entity.getTenantNo(), entity.getApplicationId());
return Response.createSuccess(entity.getRoleUuidList().size());
}
@Override
@Transactional
public Response deleteByUser(UserRoleDTO entity) {
UpdateWrapper updateWrapper = new UpdateWrapper();
updateWrapper.eq("user_id", entity.getUserId());
updateWrapper.eq("is_delete", CommonDeleteEnum.NORMAL.getCode());
updateWrapper.eq("tenant_no", entity.getTenantNo());
updateWrapper.eq(CuscStringUtils.isNotEmpty(entity.getApplicationId()), "application_id",
entity.getApplicationId());
UserRolePO urDO = new UserRolePO();
urDO.setIsDelete(CommonDeleteEnum.DELETED.getCode());
urDO.setOperator(entity.getOperator());
this.update(urDO, updateWrapper);
//将用户对应的url放到redis
urlService.userRelRolUrlToRedis(entity.getUserId(), entity.getTenantNo(), entity.getApplicationId());
return Response.createSuccess(true);
}
@Override
@Transactional
public Response deleteByRole(UserRoleDTO entity) {
UpdateWrapper updateWrapper = new UpdateWrapper();
updateWrapper.eq("role_id", entity.getRoleId());
updateWrapper.eq("is_delete", CommonDeleteEnum.NORMAL.getCode());
updateWrapper.eq("tenant_no", entity.getTenantNo());
updateWrapper.eq(CuscStringUtils.isNotEmpty(entity.getApplicationId()), "application_id",
entity.getApplicationId());
UserRolePO urDO = new UserRolePO();
urDO.setIsDelete(CommonDeleteEnum.DELETED.getCode());
urDO.setOperator(entity.getOperator());
this.update(urDO, updateWrapper);
//通过角色将角色对应的url放到redis
urlService.roleRelUrlToRedis(entity.getRoleId(), RoleSceneEnum.USER.getCode(), entity.getTenantNo(),
entity.getApplicationId());
return Response.createSuccess(true);
}
@Override
public Map<String, Set<String>> queryRoleListByUserId(String userId, String tenantNo, String appId) {
List<UserRolePO> urList = baseMapper.queryRoleListByUserId(userId, tenantNo, appId);
if (CollectionUtils.isEmpty(urList)) {
return null;
}
Map<String, Set<String>> retMap = new HashMap<>();
Set<String> roleSet;
for (UserRolePO tmpBean : urList) {
//获取当前应用对应的角色
roleSet = retMap.get(tmpBean.getApplicationId());
if (roleSet == null) {
roleSet = new HashSet<>();
retMap.put(tmpBean.getApplicationId(), roleSet);
}
roleSet.add(tmpBean.getRoleId());
}
return retMap;
}
@Override
@Transactional
public boolean delBatchUser(UserRoleDTO entity) {
UpdateWrapper updateWrapper = new UpdateWrapper();
updateWrapper.eq("user_id", entity.getUserId());
updateWrapper.eq("is_delete", CommonDeleteEnum.NORMAL.getCode());
updateWrapper.eq("tenant_no", entity.getTenantNo());
updateWrapper.eq(CuscStringUtils.isNotEmpty(entity.getApplicationId()), "application_id",
entity.getApplicationId());
updateWrapper.in(!CollectionUtils.isEmpty(entity.getUserIdList()), "user_id", entity.getUserIdList());
UserRolePO urDO = new UserRolePO();
urDO.setIsDelete(CommonDeleteEnum.DELETED.getCode());
urDO.setOperator(entity.getOperator());
this.update(urDO, updateWrapper);
//通过角色将角色对应的url放到redis
urlService.roleRelUrlToRedis(entity.getUserId(), RoleSceneEnum.USER.getCode(), entity.getTenantNo(),
entity.getApplicationId());
return true;
}
@Override
public void updateByUserId(UserRoleDTO dto) {
UserRolePO updatePo = new UserRolePO();
updatePo.setRoleId(dto.getRoleId());
updatePo.setIsDelete(0);
LambdaQueryWrapper<UserRolePO> query = new LambdaQueryWrapper<>();
query.eq(UserRolePO::getUserId, dto.getUserId());
this.update(updatePo, query);
}
@Override
public List<UserRoleDTO> queryListByUserIdList(UserRoleDTO dto) {
LambdaQueryWrapper<UserRolePO> query = new LambdaQueryWrapper<>();
query.in(UserRolePO::getUserId, dto.getUserId());
List<UserRolePO> list = this.list(query);
return UserRoleConverter.INSTANCE.poListToDtoList(list);
}
/**
* 通过查询条件查询集合数据
*
* @param userRole
* @return 集合对象
*/
@Override
public List<UserRoleDTO> queryByList(UserRoleDTO userRole) {
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.eq("is_delete", CommonDeleteEnum.NORMAL.getCode());
queryWrapper.orderByDesc("create_time");
queryWrapper.eq("tenant_no", userRole.getTenantNo());
queryWrapper.eq(CuscStringUtils.isNotEmpty(userRole.getUserId()), "user_id", userRole.getUserId());
queryWrapper.eq(CuscStringUtils.isNotEmpty(userRole.getRoleId()), "role_id", userRole.getRoleId());
queryWrapper.eq(CuscStringUtils.isNotEmpty(userRole.getApplicationId()), "application_id", userRole.getApplicationId());
List<UserRolePO> record = this.list(queryWrapper);
return UserRoleConverter.INSTANCE.poListToDtoList(record);
}
}
package com.cusc.nirvana.user.eiam.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cache.CacheFactory;
import com.cache.exception.CacheException;
import com.cusc.nirvana.common.result.PageResult;
import com.cusc.nirvana.common.result.Response;
import com.cusc.nirvana.rds.mybatis.PageHelper;
import com.cusc.nirvana.user.eiam.constants.CommonDeleteEnum;
import com.cusc.nirvana.user.eiam.constants.CommonStatusEnum;
import com.cusc.nirvana.user.eiam.constants.CommonYesOrNoEnum;
import com.cusc.nirvana.user.eiam.constants.RedisConstant;
import com.cusc.nirvana.user.eiam.constants.ResponseCode;
import com.cusc.nirvana.user.eiam.converter.UserConverter;
import com.cusc.nirvana.user.eiam.dao.UserDao;
import com.cusc.nirvana.user.eiam.dao.entity.UserPO;
import com.cusc.nirvana.user.eiam.dto.ApplicationDTO;
import com.cusc.nirvana.user.eiam.dto.SmsSendConfig;
import com.cusc.nirvana.user.eiam.dto.UserDTO;
import com.cusc.nirvana.user.eiam.dto.UserPasswordDTO;
import com.cusc.nirvana.user.eiam.dto.UserRoleDTO;
import com.cusc.nirvana.user.eiam.dto.UserSimpleDTO;
import com.cusc.nirvana.user.eiam.dto.UserTokenListDTO;
import com.cusc.nirvana.user.eiam.service.*;
import com.cusc.nirvana.user.eiam.util.CuscSqlUtils;
import com.cusc.nirvana.user.eiam.util.PasswordChecker;
import com.cusc.nirvana.user.exception.CuscUserException;
import com.cusc.nirvana.user.util.CuscStringUtils;
import com.cusc.nirvana.user.util.crypt.Sm4Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
/**
* <p>
* 针对内部员工、生态合作伙伴、分级线下店铺等企业内部用户 服务实现类
* </p>
*
* @author yuy336
* @since 2021-10-20
*/
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserDao, UserPO> implements IUserService {
@Autowired
private IUserRoleService userRoleService;
@Autowired
private IEiamSmsService smsService;
@Autowired
@Lazy
private IUrlService urlService;
@Autowired
private IApplicationService applicationService;
@Autowired
private EiamTokenService tokenService;
@Autowired
private CacheFactory cacheFactory;
@Override
@Transactional
public UserDTO addUser(UserDTO entity) {
UserPO entity0 = new UserPO();
BeanUtils.copyProperties(entity, entity0);
entity0.setUuid(CuscStringUtils.generateUuid());
entity0.setStatus(CommonStatusEnum.ENABLE.getCode());
if (CuscStringUtils.isNotEmpty(entity.getPassword())) {
//密码复杂度检查
PasswordChecker.checkPasswordRule(entity.getPassword(), entity.getUserName(), entity.getPhone(),
entity.getEmail());
entity0.setPassword(Sm4Util.encryptEcbPadding(entity0.getUuid().substring(16), entity.getPassword()));
}
UserDTO checkUserRepeat;
List<UserPO> checkUserList;
//检查用户名是否重复
if (CuscStringUtils.isNotEmpty(entity.getUserName())) {
checkUserRepeat = new UserDTO();
checkUserRepeat.setUserName(entity.getUserName());
checkUserRepeat.setTenantNo(entity.getTenantNo());
checkUserList = queryUserByParams(checkUserRepeat);
if (!CollectionUtils.isEmpty(checkUserList)) {
throw new CuscUserException(ResponseCode.USER_NAME_REPEAT.getCode(),
ResponseCode.USER_NAME_REPEAT.getMsg());
}
}
//检查手机号是否重复
if (CuscStringUtils.isNotEmpty(entity.getPhone())) {
checkUserRepeat = new UserDTO();
checkUserRepeat.setPhone(entity.getPhone());
checkUserRepeat.setTenantNo(entity.getTenantNo());
checkUserList = queryUserByParams(checkUserRepeat);
if (!CollectionUtils.isEmpty(checkUserList)) {
throw new CuscUserException(ResponseCode.USER_PHONE_REPEAT.getCode(),
ResponseCode.USER_PHONE_REPEAT.getMsg());
}
}
//检查邮箱是否重复
if (CuscStringUtils.isNotEmpty(entity.getEmail())) {
checkUserRepeat = new UserDTO();
checkUserRepeat.setEmail(entity.getEmail());
checkUserRepeat.setTenantNo(entity.getTenantNo());
checkUserList = queryUserByParams(checkUserRepeat);
if (!CollectionUtils.isEmpty(checkUserList)) {
throw new CuscUserException(ResponseCode.USER_EMAIL_REPEAT.getCode(),
ResponseCode.USER_EMAIL_REPEAT.getMsg());
}
}
this.save(entity0);
entity.setUuid(entity0.getUuid());
return entity;
}
@Override
@Transactional
public UserDTO updateUser(UserDTO entity) {
UserPO entity0 = this.getPoByUuid(entity.getUuid(), entity.getTenantNo());
if (entity0 == null || CommonDeleteEnum.DELETED.getCode() == entity0.getIsDelete()) {
throw new CuscUserException(ResponseCode.USER_INVALID.getCode(),
ResponseCode.USER_INVALID.getMsg());
}
entity.setId(entity0.getId());
BeanUtils.copyProperties(entity, entity0);
UserDTO checkUserRepeat;
List<UserPO> checkUserList;
//检查用户名是否重复
if (CuscStringUtils.isNotEmpty(entity.getUserName())) {
checkUserRepeat = new UserDTO();
checkUserRepeat.setUserName(entity.getUserName());
checkUserRepeat.setId(entity.getId());
checkUserRepeat.setTenantNo(entity.getTenantNo());
checkUserList = queryUserByParams(checkUserRepeat);
if (!CollectionUtils.isEmpty(checkUserList)) {
throw new CuscUserException(ResponseCode.USER_NAME_REPEAT.getCode(),
ResponseCode.USER_NAME_REPEAT.getMsg());
}
}
//检查手机号是否重复
if (CuscStringUtils.isNotEmpty(entity.getPhone())) {
checkUserRepeat = new UserDTO();
checkUserRepeat.setPhone(entity.getPhone());
checkUserRepeat.setId(entity.getId());
checkUserRepeat.setTenantNo(entity.getTenantNo());
checkUserList = queryUserByParams(checkUserRepeat);
if (!CollectionUtils.isEmpty(checkUserList)) {
throw new CuscUserException(ResponseCode.USER_PHONE_REPEAT.getCode(),
ResponseCode.USER_PHONE_REPEAT.getMsg());
}
}
//检查邮箱是否重复
if (CuscStringUtils.isNotEmpty(entity.getEmail())) {
checkUserRepeat = new UserDTO();
checkUserRepeat.setEmail(entity.getEmail());
checkUserRepeat.setId(entity.getId());
checkUserRepeat.setTenantNo(entity.getTenantNo());
checkUserList = queryUserByParams(checkUserRepeat);
if (!CollectionUtils.isEmpty(checkUserList)) {
throw new CuscUserException(ResponseCode.USER_EMAIL_REPEAT.getCode(),
ResponseCode.USER_EMAIL_REPEAT.getMsg());
}
}
//登录名不允许修改
entity0.setUuid(null);
entity0.setPassword(null);
entity0.setTenantNo(null);
this.updateById(entity0);
return entity;
}
@Override
@Transactional
public boolean deleteUser(UserDTO entity) {
UserPO entity0 = this.getPoByUuid(entity.getUuid(), entity.getTenantNo());
if (entity0 == null) {
throw new CuscUserException(ResponseCode.USER_INVALID.getCode(),
ResponseCode.USER_INVALID.getMsg());
}
entity.setId(entity0.getId());
String userId = entity0.getUuid();
//检查是否有租户权限
if (CommonDeleteEnum.DELETED.getCode() == entity0.getIsDelete()) {
return true;
}
//删除用户与角色的关系
UserRoleDTO userRole = new UserRoleDTO();
userRole.setUserId(entity0.getUuid());
userRoleService.deleteByUser(userRole);
entity0 = new UserPO();
entity0.setId(entity.getId());
entity0.setIsDelete(CommonDeleteEnum.DELETED.getCode());
//删除的同时冻结用户
entity0.setStatus(CommonStatusEnum.DISABLE.getCode());
boolean ret = this.updateById(entity0);
//删除redis中用户对应的url
urlService.delUserRelUrlRedis(userId, entity0.getTenantNo(), null);
//执行踢出
tokenService.kickOutByUserId(userId, entity.getTenantNo());
return ret;
}
@Override
public UserDTO getUser(UserDTO entity) {
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.eq(entity.getId() != null, "id", entity.getId());
queryWrapper.eq("is_delete", CommonDeleteEnum.NORMAL.getCode());
queryWrapper.eq("tenant_no", entity.getTenantNo());
queryWrapper.in(!CollectionUtils.isEmpty(entity.getTenantNoList()), "tenant_no", entity.getTenantNoList());
queryWrapper.eq(CuscStringUtils.isNotEmpty(entity.getPhone()), "phone", entity.getPhone());
queryWrapper.eq(CuscStringUtils.isNotEmpty(entity.getEmail()), "email", entity.getEmail());
queryWrapper.eq(CuscStringUtils.isNotEmpty(entity.getUserName()), "user_name", entity.getUserName());
queryWrapper.eq(entity.getIsTenantAdmin() != null, "is_tenant_admin", entity.getIsTenantAdmin());
queryWrapper.eq(entity.getStatus() != null, "status", entity.getStatus());
queryWrapper.eq(CuscStringUtils.isNotEmpty(entity.getUuid()), "uuid", entity.getUuid());
UserPO record = this.getOne(queryWrapper);
return UserConverter.INSTANCE.poToDto(record);
}
@Override
public PageResult<UserDTO> pageListUser(UserDTO entity) {
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.orderByDesc("create_time");
queryWrapper.eq("is_delete", 0);
queryWrapper.eq("tenant_no", entity.getTenantNo());
queryWrapper.like(CuscStringUtils.isNotEmpty(entity.getUserName()), "user_name", entity.getUserName());
queryWrapper.like(CuscStringUtils.isNotEmpty(entity.getPhone()), "phone", entity.getPhone());
queryWrapper.like(CuscStringUtils.isNotEmpty(entity.getFullName()), "full_name", entity.getFullName());
queryWrapper.eq(entity.getStatus() != null, "status", entity.getStatus());
queryWrapper.eq(CuscStringUtils.isNotEmpty(entity.getUuid()), "uuid", entity.getUuid());
queryWrapper.eq(entity.getId() != null, "id", entity.getId());
//关联组织查询
if (CuscStringUtils.isNotEmpty(entity.getQueryOrganId())) {
String userOrganStr =
"select user_id from eiam_user_organ where eiam_user.uuid = eiam_user_organ.user_id and "
+ "eiam_user_organ.organ_id = '"
+ CuscSqlUtils.transactSQLInjection(entity.getQueryOrganId()) + "'";
queryWrapper.exists(userOrganStr);
}
Page<UserDTO> page =
this.page(new Page<>(entity.getCurrPage(), entity.getPageSize()), queryWrapper);
return PageHelper.convert(page, UserDTO.class);
}
@Override
public List<UserSimpleDTO> queryListUser(UserDTO entity) {
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.eq("is_delete", 0);
// queryWrapper.orderByDesc("create_time");
queryWrapper.eq(CuscStringUtils.isNotEmpty(entity.getTenantNo()), "tenant_no", entity.getTenantNo());
queryWrapper.eq(CuscStringUtils.isNotEmpty(entity.getUserName()), "user_name", entity.getUserName());
queryWrapper.eq(CuscStringUtils.isNotEmpty(entity.getPhone()), "phone",
entity.getPhone());
queryWrapper.like(CuscStringUtils.isNotEmpty(entity.getFullName()), "full_name", entity.getFullName());
queryWrapper.eq(CuscStringUtils.isNotEmpty(entity.getUuid()), "uuid", entity.getUuid());
queryWrapper.in(!CollectionUtils.isEmpty(entity.getUuidList()), "uuid", entity.getUuidList());
queryWrapper.eq(entity.getIsTenantAdmin() != null, "is_tenant_admin", entity.getIsTenantAdmin());
queryWrapper.orderByAsc("update_time");
List<UserPO> recordList = this.list(queryWrapper);
return getUserSimple(recordList);
}
@Override
@Transactional
public boolean frozen(UserDTO entity) {
UserPO entity0 = this.getPoByUuid(entity.getUuid(), entity.getTenantNo());
if (entity0 == null || CommonDeleteEnum.DELETED.getCode() == entity0.getIsDelete()) {
throw new CuscUserException(ResponseCode.USER_INVALID.getCode(),
ResponseCode.USER_INVALID.getMsg());
}
String userId = entity0.getUuid();
UserPO bean = new UserPO();
bean.setId(entity0.getId());
bean.setStatus(CommonStatusEnum.DISABLE.getCode());
boolean ret = this.updateById(bean);
//删除redis中用户对应的url
urlService.delUserRelUrlRedis(userId, entity0.getTenantNo(), null);
//执行踢出
tokenService.kickOutByUserId(userId, entity.getTenantNo());
return ret;
}
@Override
@Transactional
public boolean unfreeze(UserDTO entity) {
UserPO entity0 = this.getPoByUuid(entity.getUuid(), entity.getTenantNo());
if (entity0 == null || CommonDeleteEnum.DELETED.getCode() == entity0.getIsDelete()) {
throw new CuscUserException(ResponseCode.USER_INVALID.getCode(),
ResponseCode.USER_INVALID.getMsg());
}
String userId = entity0.getUuid();
//检查是否有租户权限
UserPO bean = new UserPO();
bean.setId(entity0.getId());
bean.setStatus(CommonStatusEnum.ENABLE.getCode());
boolean ret = this.updateById(bean);
//将用户授权的应用的url放到redis中
urlService.userRelAppUrlToRedis(userId, entity0.getTenantNo());
return ret;
}
@Override
public UserDTO getByUuid(UserDTO entity) {
UserPO record = this.getPoByUuid(entity.getUuid(), entity.getTenantNo());
return UserConverter.INSTANCE.poToDto(record);
}
@Override
public List<UserSimpleDTO> getByUuids(UserDTO entity) {
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.in("uuid", entity.getUuidList());
queryWrapper.eq("is_delete", CommonDeleteEnum.NORMAL.getCode());
queryWrapper.eq("tenant_no", entity.getTenantNo());
List<UserPO> recordList = this.list(queryWrapper);
return getUserSimple(recordList);
}
/**
* Description: 将user对象转为user简单对象
* <br />
* CreateDate 2021-10-29 15:57:53
*
* @author yuyi
**/
private List<UserSimpleDTO> getUserSimple(List<UserPO> recordList) {
List<UserSimpleDTO> retList = new ArrayList<>();
UserSimpleDTO usDto;
for (UserPO user : recordList) {
usDto = new UserSimpleDTO();
BeanUtils.copyProperties(user, usDto);
retList.add(usDto);
}
return retList;
}
/**
* Description: 通过角色id查询用户信息
* <br />
* CreateDate 2021-10-29 22:25:38
*
* @author yuyi
**/
@Override
public List<UserDTO> queryUserByRoleId(UserRoleDTO entity) {
return baseMapper.queryUserByRoleId(entity);
}
/**
* Description: 更换租户管理员账号
* <br />
* CreateDate 2022-01-20 11:48:36
*
* @author yuyi
**/
@Override
@Transactional
public boolean changeTenantAdmin(UserDTO bean) {
//检查参数是否正确
if (bean == null || CuscStringUtils.isEmpty(bean.getTenantNo()) || CuscStringUtils.isEmpty(bean.getUuid())
|| CuscStringUtils.isEmpty(bean.getNewUserId())) {
throw new CuscUserException(ResponseCode.PARAMETER_NULL.getCode(),
ResponseCode.PARAMETER_NULL.getMsg());
}
//老用户
UserDTO oldUser = getByUuid(bean);
if (oldUser == null || CommonYesOrNoEnum.YES.getCode() != oldUser.getIsTenantAdmin().intValue()) {
throw new CuscUserException(ResponseCode.USER_INVALID.getCode(),
ResponseCode.USER_INVALID.getMsg());
}
//将老用户的管理员标记去掉
UserDTO oldUserUpdate = new UserDTO();
oldUserUpdate.setId(oldUser.getId());
oldUserUpdate.setIsTenantAdmin(CommonYesOrNoEnum.NO.getCode());
updateUser(oldUserUpdate);
//新用户
UserDTO newUser = new UserDTO();
newUser.setUuid(bean.getNewUserId());
newUser.setTenantNo(bean.getTenantNo());
newUser = getByUuid(newUser);
if (newUser == null) {
throw new CuscUserException(ResponseCode.USER_INVALID.getCode(),
ResponseCode.USER_INVALID.getMsg());
}
//将新用户的标记为租户管理员
UserDTO newUserUpdate = new UserDTO();
newUserUpdate.setId(oldUser.getId());
newUserUpdate.setIsTenantAdmin(CommonYesOrNoEnum.YES.getCode());
updateUser(newUserUpdate);
return true;
}
@Override
public void allUserRelUrlToRedis(UserDTO bean) {
if (bean == null || CuscStringUtils.isEmpty(bean.getTenantNo()) || CuscStringUtils.isEmpty(
bean.getApplicationId())) {
throw new CuscUserException(ResponseCode.PARAMETER_NULL.getCode(),
ResponseCode.PARAMETER_NULL.getMsg());
}
List<UserPO> userList = queryUserByParams(bean);
if (CollectionUtils.isEmpty(userList)) {
log.info("allUserRelUrlToRedis user list is empty!");
return;
}
List<String> userIdList = new ArrayList<>();
for (UserPO user : userList) {
userIdList.add(user.getUuid());
}
urlService.userListRelUrlToRedis(userIdList, bean.getTenantNo(), bean.getApplicationId());
}
/**
* Description: 修改密码
* <br />
* CreateDate 2022-01-21 15:36:34
*
* @author yuyi
**/
@Override
@Transactional
public boolean changePassword(UserDTO bean) {
UserPO entity0 = this.getPoByUuid(bean.getUuid(), bean.getTenantNo());
if (entity0 == null || CommonDeleteEnum.DELETED.getCode() == entity0.getIsDelete()) {
throw new CuscUserException(ResponseCode.USER_INVALID.getCode(),
ResponseCode.USER_INVALID.getMsg());
}
//验证原密码是否正确
if (!Sm4Util.encryptEcbPadding(entity0.getUuid().substring(16), bean.getPassword())
.equals(entity0.getPassword())) {
throw new CuscUserException(ResponseCode.USER_OLD_PASSWORD_ERROR.getCode(),
ResponseCode.USER_OLD_PASSWORD_ERROR.getMsg());
}
//密码复杂度检查
PasswordChecker.checkPasswordRule(bean.getNewPassword(), entity0.getUserName(), entity0.getPhone(),
entity0.getEmail());
//修改密码
UserPO userPO = new UserPO();
userPO.setId(entity0.getId());
userPO.setPassword(Sm4Util.encryptEcbPadding(entity0.getUuid().substring(16), bean.getNewPassword()));
return this.updateById(userPO);
}
/**
* Description: 重置密码
* <br />
* CreateDate 2022-01-21 15:36:34
*
* @author yuyi
**/
@Override
@Transactional
public boolean resetPassword(UserPasswordDTO bean) {
UserPO entity0 = this.getPoByUuid(bean.getUuid(), bean.getTenantNo());
if (entity0 == null || CommonDeleteEnum.DELETED.getCode() == entity0.getIsDelete()) {
throw new CuscUserException(ResponseCode.USER_INVALID.getCode(),
ResponseCode.USER_INVALID.getMsg());
}
if (CuscStringUtils.isEmpty(entity0.getPhone())) {
throw new CuscUserException(ResponseCode.RESET_PASSWORDPHONE_NOT_NULL.getCode(),
ResponseCode.RESET_PASSWORDPHONE_NOT_NULL.getMsg());
}
//是否验证短信验证
if (CuscStringUtils.isNotEmpty(bean.getSmsCode())) {
Response<Boolean> smsResp = smsService.checkSmsCaptcha(entity0.getPhone(), bean.getTenantNo(),
bean.getApplicationId(),
bean.getSmsCode());
if(!smsResp.isSuccess()){
throw new CuscUserException(smsResp.getCode(), smsResp.getMsg());
}
}
//生成新密码
String newPassword;
boolean ret;
//密码为空时,需要生成新密码
if(CuscStringUtils.isEmpty(bean.getPassword())){
SmsSendConfig smsConfig = bean.getSmsSendConfig();
//查询应用配置
ApplicationDTO appConfig = applicationService.getCacheByCode(bean.getApplicationId());
//短信配置检查和读取应用的配置
smsService.convertToSmsConfig(appConfig, smsConfig);
//生成新密码
newPassword = createNewPassword();
//短信发送限制检查
smsConfig.setIntervalLimitKey(RedisConstant.SMS_SEND_RESET_PASSWORD_INTERVAL_LIMIT);
smsConfig.setTotalLimitKey(RedisConstant.SMS_SEND_RESET_PASSWORD_DAY_LIMIT);
smsConfig.setTenantNo(bean.getTenantNo());
smsConfig.setAppId(bean.getApplicationId());
smsService.checkSmsSendLimit(entity0.getPhone(), smsConfig);
//修改密码
UserPO userPO = new UserPO();
userPO.setId(entity0.getId());
userPO.setPassword(Sm4Util.encryptEcbPadding(entity0.getUuid().substring(16), newPassword));
ret = this.updateById(userPO);
//将密码以短信的方式发送给用户
smsService.sendSms(entity0.getPhone(), newPassword, smsConfig);
}else{
newPassword = bean.getPassword();
//密码复杂度检查
PasswordChecker.checkPasswordRule(newPassword, entity0.getUserName(), entity0.getPhone(),
entity0.getEmail());
//修改密码
UserPO userPO = new UserPO();
userPO.setId(entity0.getId());
userPO.setPassword(Sm4Util.encryptEcbPadding(entity0.getUuid().substring(16), newPassword));
ret = this.updateById(userPO);
}
return ret;
}
/**
* Description: 查询用户是否在线
* <br />
* CreateDate 2022-01-21 15:36:34
*
* @author yuyi
**/
@Override
public boolean getUserOnline(UserDTO bean) {
//通过用户id和应用id找到对应的token信息
try {
String userTokenListKey = RedisConstant.TOKEN_USER_TOKEN_INFO + bean.getTenantNo() + ":" + bean.getUuid();
List<UserTokenListDTO> userList =
cacheFactory.getExpireListService().getList(userTokenListKey, UserTokenListDTO.class);
if (CollectionUtils.isEmpty(userList)) {
return false;
}
for (UserTokenListDTO userToken : userList) {
if (userToken.getAppId().equals(bean.getApplicationId())) {
return true;
}
}
} catch (CacheException e) {
log.error("getUserOnline 访问reids失败 :{}", e);
return false;
}
return false;
}
@Override
public List<UserDTO> queryAdminUserListByUserIdList(List<String> userIdList, boolean tenantAdmin) {
if (CollectionUtils.isEmpty(userIdList)) {
return Collections.emptyList();
}
//租户管理员
List<UserPO> list;
if (tenantAdmin) {
list = this.lambdaQuery().in(UserPO::getUuid, userIdList).eq(UserPO::getIsTenantAdmin, 1).list();
} else {
list = this.lambdaQuery().in(UserPO::getUuid, userIdList).ne(UserPO::getOrdinaryAdmin, 0).list();
}
return UserConverter.INSTANCE.poListToDtoList(list);
}
@Override
public List<UserDTO> queryAdminUserListByUserIdListNew(List<String> userIdList, boolean tenantAdmin) {
if (CollectionUtils.isEmpty(userIdList)) {
return Collections.emptyList();
}
//租户管理员
List<UserPO> list = this.lambdaQuery().in(UserPO::getUuid, userIdList).ne(UserPO::getOrdinaryAdmin, 0).list();
return UserConverter.INSTANCE.poListToDtoList(list);
}
//-----------------私有方法区-----------------------
/**
* Description:查询用户信息
* <br />
* CreateDate 2021-10-26 17:42:09
*
* @author yuyi
**/
private List<UserPO> queryUserByParams(UserDTO entity) {
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.eq("is_delete", 0);
queryWrapper.eq("tenant_no", entity.getTenantNo());
queryWrapper.in(!CollectionUtils.isEmpty(entity.getTenantNoList()), "tenant_no", entity.getTenantNoList());
queryWrapper.eq(CuscStringUtils.isNotEmpty(entity.getUserName()), "user_name", entity.getUserName());
queryWrapper.eq(CuscStringUtils.isNotEmpty(entity.getPhone()), "phone",
entity.getPhone());
queryWrapper.eq(CuscStringUtils.isNotEmpty(entity.getEmail()), "email",
entity.getEmail());
queryWrapper.ne(entity.getId() != null, "id", entity.getId());
return this.list(queryWrapper);
}
/**
* 通过UUID查询单条数据
*
* @param uuid
* @return 实例对象
*/
private UserPO getPoByUuid(String uuid, String tenantNo) {
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.eq("uuid", uuid);
queryWrapper.eq("is_delete", CommonDeleteEnum.NORMAL.getCode());
queryWrapper.eq(CuscStringUtils.isNotEmpty(tenantNo), "tenant_no", tenantNo);
return this.getOne(queryWrapper);
}
/**
* 创建新密码
*/
private String createNewPassword() {
char[] chars = new char[9];
Random rnd = new Random();
int specialPosition = rnd.nextInt(7) + 1;
for (int i = 0; i < 9; i++) {
if (specialPosition == i) {
chars[i] = '@';
} else {
chars[i] = nextChar(rnd);
}
}
return new String(chars);
}
/**
* 创建随机字符,包含数字、大小写字母
*/
private static char nextChar(Random rnd) {
switch (rnd.nextInt(3)) {
case 0:
return (char) ('a' + rnd.nextInt(26));
case 1:
return (char) ('A' + rnd.nextInt(26));
default:
return (char) ('0' + rnd.nextInt(10));
}
}
}
package com.cusc.nirvana.user.eiam.util;
import com.cusc.nirvana.user.eiam.constants.ResponseCode;
import com.cusc.nirvana.user.exception.CuscUserException;
import com.cusc.nirvana.user.util.CuscStringUtils;
/**
* Description: 参数校验
* <br />
* CreateDate 2022-02-17 10:52
*
* @author yuy336
**/
public class CommonParamterCheck {
/**
* Description: 检查应用和租户是否为空
* <br />
* CreateDate 2022-02-17 10:55:16
*
* @author yuyi
**/
public static void appIdAndTenantNoRequired(String applicationId, String tenantNo) {
if (CuscStringUtils.isEmpty(applicationId) || CuscStringUtils.isEmpty(tenantNo)) {
throw new CuscUserException(ResponseCode.APPLICATION_TENANT_REQUIRED.getCode(),
ResponseCode.APPLICATION_TENANT_REQUIRED.getMsg());
}
}
/**
* Description: 检查uuid、应用和租户是否为空
* <br />
* CreateDate 2022-02-17 10:55:16
*
* @author yuyi
**/
public static void uuidAppTenantRequired(String uuid, String applicationId, String tenantNo) {
if (CuscStringUtils.isEmpty(applicationId) || CuscStringUtils.isEmpty(tenantNo)) {
throw new CuscUserException(ResponseCode.APPLICATION_TENANT_REQUIRED.getCode(),
ResponseCode.APPLICATION_TENANT_REQUIRED.getMsg());
}
if (CuscStringUtils.isEmpty(uuid)) {
throw new CuscUserException(ResponseCode.PARAMETER_NULL.getCode(),
ResponseCode.PARAMETER_NULL.getMsg());
}
}
}
package com.cusc.nirvana.user.eiam.util;
import org.apache.commons.lang3.StringUtils;
/**
* Description: 智网sql工具类
* <br />
* CreateDate 2022-07-08 20:31:36
*
* @author yuyi
**/
public class CuscSqlUtils {
private final static String[] keywords =
{"'", "\"", ";", "\\", "*", "-", "+", "%", "master", "truncate", "insert", "select", "delete", "update",
"declare",
"alert", "drop", "and", "exec", "execute", "count", "xp_cmdshell", "declare", "sitename", "mid", "union", "from"};
/**
* Description: 转换sql注入
* <br />
* CreateDate 2022-07-08 20:32:05
*
* @author yuyi
**/
public static String transactSQLInjection(String str) {
if (StringUtils.isEmpty(str)) {
return null;
}
//判断是否包含非法字符
for (String keyword : keywords) {
if (str.indexOf(keyword) != -1) {
str = StringUtils.replace(str, keyword, "");
}
}
return str;
}
}
package com.cusc.nirvana.user.eiam.util;
import com.cusc.nirvana.user.eiam.constants.PasswordCheckCode;
import com.cusc.nirvana.user.exception.CuscUserException;
import com.cusc.nirvana.user.util.CuscStringUtils;
import java.util.ArrayList;
import java.util.List;
/**
* Description: 密码检查工具类
* <br />
* 规则:
* 1、长度大于8,且小于20
* 2、不能包含用户名
* 3、不能包含连续3位及以上相同字母或数字
* 4、不能包含3个及以上字典连续字符
* 4、不能包含3个及以上键盘连续字符
* 4、数字、小写字母、大写字母、特殊字符,至少包含三种
* CreateDate 2021-11-08 17:38
*
* @author yuyi
**/
public class PasswordChecker {
/**
* 数字
*/
private static final String REG_NUMBER = ".*\\d+.*";
/**
* 小写字母
*/
private static final String REG_UPPERCASE = ".*[A-Z]+.*";
/**
* 大写字母
*/
private static final String REG_LOWERCASE = ".*[a-z]+.*";
/**
* 特殊符号(~!@#$%^&*()_+|<>,.?/:;'[]{}\)
*/
private static final String REG_SYMBOL = ".*[~!@#$%^&*()_+|<>,.?/:;'\\[\\]{}\"]+.*";
/**
* 键盘字符表(小写)
* 非shift键盘字符表
*/
private static final char[][] CHAR_TABLE1 = new char[][] {
{'1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-', '=', '\0'},
{'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', '[', ']', '\\'},
{'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', ';', '\'', '\0', '\0'},
{'z', 'x', 'c', 'v', 'b', 'n', 'm', ',', '.', '/', '\0', '\0', '\0'}};
/**
* shift键盘的字符表
*/
private static final char[][] CHAR_TABLE2 = new char[][] {
{'!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_', '+', '\0'},
{'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', '{', '}', '|'},
{'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', ':', '"', '\0', '\0'},
{'z', 'x', 'c', 'v', 'b', 'n', 'm', '<', '>', '?', '\0', '\0', '\0'}};
private static List<String> SYSTEM_PASSWORD = initSystemPassword();
/**
* 校验密码
*
* @param password 密码
* @param username 用户名
*/
public static boolean checkPasswordRule(String password, String username, String phone, String email) {
if (CuscStringUtils.isEmpty(password) || password.length() < 8 || password.length() > 20) {
throw new CuscUserException(PasswordCheckCode.PASSWORD_LENGTH.getCode() + "",
PasswordCheckCode.PASSWORD_LENGTH.getMsg());
}
if (CuscStringUtils.isNotEmpty(username) && password.toLowerCase().contains(username.toLowerCase())) {
throw new CuscUserException(PasswordCheckCode.CONTAINS_USER_NAME.getCode() + "",
PasswordCheckCode.CONTAINS_USER_NAME.getMsg());
}
if (CuscStringUtils.isNotEmpty(phone) && password.contains(phone)) {
throw new CuscUserException(PasswordCheckCode.CONTAINS_USER_NAME.getCode() + "",
PasswordCheckCode.CONTAINS_USER_NAME.getMsg());
}
if (CuscStringUtils.isNotEmpty(email) && password.toLowerCase().contains(email.toLowerCase())) {
throw new CuscUserException(PasswordCheckCode.CONTAINS_USER_NAME.getCode() + "",
PasswordCheckCode.CONTAINS_USER_NAME.getMsg());
}
if (isContinuousChar(password)) {
throw new CuscUserException(PasswordCheckCode.CONTINUOUS_CHARACTER.getCode() + "",
PasswordCheckCode.CONTINUOUS_CHARACTER.getMsg());
}
if (isKeyBoardContinuousChar(password)) {
throw new CuscUserException(PasswordCheckCode.KEYBOARD_CONTINUOUS_CHARACTERS.getCode() + "",
PasswordCheckCode.KEYBOARD_CONTINUOUS_CHARACTERS.getMsg());
}
if (SYSTEM_PASSWORD.contains(password)) {
throw new CuscUserException(PasswordCheckCode.CONTAINS_SYSTEM_PASSWORD.getCode() + "",
PasswordCheckCode.CONTAINS_SYSTEM_PASSWORD.getMsg());
}
int i = 0;
if (password.matches(REG_NUMBER)) {
i++;
}
if (password.matches(REG_LOWERCASE)) {
i++;
}
if (password.matches(REG_UPPERCASE)) {
i++;
}
if (password.matches(REG_SYMBOL)) {
i++;
}
if (i < 3) {
throw new CuscUserException(PasswordCheckCode.TOO_LOW_COMPLEXITY.getCode() + "",
PasswordCheckCode.TOO_LOW_COMPLEXITY.getMsg());
}
return true;
}
/**
* 是否包含3个及以上相同或字典连续字符
*/
private static boolean isContinuousChar(String password) {
char[] chars = password.toCharArray();
for (int i = 0; i < chars.length - 2; i++) {
int n1 = chars[i];
int n2 = chars[i + 1];
int n3 = chars[i + 2];
// 判断重复字符
if (n1 == n2 && n1 == n3) {
return true;
}
// 判断连续字符: 正序 + 倒序
if ((n1 + 1 == n2 && n1 + 2 == n3) || (n1 - 1 == n2 && n1 - 2 == n3)) {
return true;
}
}
return false;
}
/**
* 是否包含3个及以上键盘连续字符
*
* @param password 待匹配的字符串
*/
private static boolean isKeyBoardContinuousChar(String password) {
if (CuscStringUtils.isEmpty(password)) {
return false;
}
//考虑大小写,都转换成小写字母
char[] lpStrChars = password.toLowerCase().toCharArray();
// 获取字符串长度
int nStrLen = lpStrChars.length;
// 定义位置数组:row - 行,col - column 列
int[] pRowCharPos = new int[nStrLen];
int[] pColCharPos = new int[nStrLen];
for (int i = 0; i < nStrLen; i++) {
char chLower = lpStrChars[i];
pColCharPos[i] = -1;
// 检索在表1中的位置,构建位置数组
for (int nRowTable1Idx = 0; nRowTable1Idx < 4; nRowTable1Idx++) {
for (int nColTable1Idx = 0; nColTable1Idx < 13; nColTable1Idx++) {
if (chLower == CHAR_TABLE1[nRowTable1Idx][nColTable1Idx]) {
pRowCharPos[i] = nRowTable1Idx;
pColCharPos[i] = nColTable1Idx;
}
}
}
// 在表1中没找到,到表二中去找,找到则continue
if (pColCharPos[i] >= 0) {
continue;
}
// 检索在表2中的位置,构建位置数组
for (int nRowTable2Idx = 0; nRowTable2Idx < 4; nRowTable2Idx++) {
for (int nColTable2Idx = 0; nColTable2Idx < 13; nColTable2Idx++) {
if (chLower == CHAR_TABLE2[nRowTable2Idx][nColTable2Idx]) {
pRowCharPos[i] = nRowTable2Idx;
pColCharPos[i] = nColTable2Idx;
}
}
}
}
// 匹配坐标连线
for (int j = 1; j <= nStrLen - 2; j++) {
//同一行
if (pRowCharPos[j - 1] == pRowCharPos[j] && pRowCharPos[j] == pRowCharPos[j + 1]) {
// 键盘行正向连续(asd)或者键盘行反向连续(dsa)
if ((pColCharPos[j - 1] + 1 == pColCharPos[j] && pColCharPos[j] + 1 == pColCharPos[j + 1]) ||
(pColCharPos[j + 1] + 1 == pColCharPos[j] && pColCharPos[j] + 1 == pColCharPos[j - 1])) {
return true;
}
}
//同一列
if (pColCharPos[j - 1] == pColCharPos[j] && pColCharPos[j] == pColCharPos[j + 1]) {
//键盘列连续(qaz)或者键盘列反向连续(zaq)
if ((pRowCharPos[j - 1] + 1 == pRowCharPos[j] && pRowCharPos[j] + 1 == pRowCharPos[j + 1]) ||
(pRowCharPos[j - 1] - 1 == pRowCharPos[j] && pRowCharPos[j] - 1 == pRowCharPos[j + 1])) {
return true;
}
}
}
return false;
}
/**
* Description: 初始化系统、数据库相关字
* <br />
* CreateDate 2021-11-09 09:07:17
*
* @author yuyi
**/
private static List<String> initSystemPassword() {
List<String> ret = new ArrayList<>();
ret.add("root");
ret.add("admin");
ret.add("mysql");
ret.add("oracle");
ret.add("system");
return ret;
}
}
spring:
cloud:
nacos:
config:
server-addr: 10.179.71.33:8848,10.179.71.81:8848,10.179.71.221:8848
username: nacos
password: Hy@OneNacos2022
namespace: 92bf8770-8770-4326-a20e-2ed8b17a559e
group: DEFAULT_GROUP
file-extension: yml
discovery:
server-addr: 10.179.71.33:8848,10.179.71.81:8848,10.179.71.221:8848
namespace: 92bf8770-8770-4326-a20e-2ed8b17a559e
username: nacos
password: Hy@OneNacos2022
group: DEFAULT_GROUP
spring:
application:
name: local-rnr-user
//import com.alibaba.fastjson.JSONObject;
//import com.cache.CacheFactory;
//import com.cache.exception.CacheException;
//import com.cusc.nirvana.common.result.Response;
//import com.cusc.nirvana.user.LocalRnrUserApplication;
//import com.cusc.nirvana.user.auth.common.constants.RedisConstant;
//import com.cusc.nirvana.user.auth.common.constants.UserTypeEnum;
//import com.cusc.nirvana.user.auth.identification.dto.MobileLoginReq;
//import com.cusc.nirvana.user.auth.identification.dto.Oauth2Token;
//import com.cusc.nirvana.user.auth.identification.service.ILoginService;
//import com.cusc.nirvana.user.eiam.dto.UserTokenListDTO;
//import com.cusc.nirvana.user.eiam.service.impl.UrlServiceImpl;
//import org.junit.Test;
//import org.junit.runner.RunWith;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.boot.test.context.SpringBootTest;
//import org.springframework.test.context.junit4.SpringRunner;
//
//import java.util.List;
//import java.util.UUID;
//
//@RunWith(SpringRunner.class)
//@SpringBootTest(classes = LocalRnrUserApplication.class)
//public class XiaminTest {
//
// @Autowired
// private UrlServiceImpl urlService;
// @Autowired
// private CacheFactory cacheFactory;
// @Autowired
// ILoginService loginService;
//
// @Test
// public void test1() {
// System.out.println("测试");
// Integer returnInt = urlService.whiteListToRedis();
// System.out.println(returnInt);
// }
//
// @Test
// public void test2() {
// String serverName = "local-rnr-customer";
// String url = "/login/ciamXP";
// String allURL = serverName + url;
//// "local-rnr-customer/login/caimXP"
// System.out.println(serverName + url);
// System.out.println(allURL);
// System.out.println("local-rnr-customer/login/ciamXP");
// try {
// boolean bool = cacheFactory.getSetService().containsValue(RedisConstant.URL_WHITE_LIST, serverName + url);
// boolean bool1 = cacheFactory.getSetService().containsValue(RedisConstant.URL_WHITE_LIST, allURL);
// boolean bool2 = cacheFactory.getSetService().containsValue(RedisConstant.URL_WHITE_LIST, "local-rnr-customer/login/ciamXP");
// System.out.println(bool);
// System.out.println(bool1);
// System.out.println(bool2);
// } catch (CacheException e) {
// e.printStackTrace();
// }
//
// String superSecretId = "18701506636";
// System.out.println(UUID.fromString(superSecretId).toString());
// String superSecretId2 = "18701506636";
// System.out.println(UUID.fromString(superSecretId2).toString());
// }
//
// @Test
// public void test3() {
// MobileLoginReq mobileLogin = new MobileLoginReq();
// mobileLogin.setApplicationId("5");
// mobileLogin.setPhone("15803307104");
// mobileLogin.setTenantNo("testRnr2");
// mobileLogin.setUserType(UserTypeEnum.CIAM.getCode());
// Response<Oauth2Token> response = loginService.ciamMobileLoginXP(mobileLogin);
// System.out.println(JSONObject.toJSONString(response.getData()));
// }
//
// @Test
// public void test4() {
// try {
// String userTokenListKey = RedisConstant.TOKEN_USER_TOKEN_INFO + "testRnr2:null";
// List<UserTokenListDTO> userList = cacheFactory.getExpireListService().getList(userTokenListKey, UserTokenListDTO.class);
// for (UserTokenListDTO uu : userList) {
// boolean accessBool = cacheFactory.getExpireListService().delete(RedisConstant.TOKEN_ACCESS_TOKEN_INFO + uu.getAccess());
// boolean refreshBool = cacheFactory.getExpireListService().delete(RedisConstant.TOKEN_REFRESH_TOKEN_INFO + uu.getRefresh());
// System.out.println(JSONObject.toJSONString(uu));
// System.out.println(accessBool);
// System.out.println(refreshBool);
// }
// System.out.println(userList.size());
// cacheFactory.getExpireListService().delete(userTokenListKey);
// userList = cacheFactory.getExpireListService().getList(userTokenListKey, UserTokenListDTO.class);
// System.out.println(userList.size());
// } catch (CacheException e) {
// e.printStackTrace();
// }
// }
//}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.cusc.nirvana</groupId>
<artifactId>cusc-parent</artifactId>
<version>1.2.1-SNAPSHOT</version>
<relativePath/>
</parent>
<groupId>com.cusc.nirvana</groupId>
<artifactId>local-rnr-user</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<module>local-rnr-user-dto</module>
<module>local-rnr-user-remote</module>
<module>local-rnr-user-server</module>
<module>local-rnr-user-plug</module>
</modules>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
</project>
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment