新增社交客户端 CRUD

This commit is contained in:
puhui999 2023-10-25 16:07:17 +08:00
parent eb4b719b4b
commit 738fcef453
14 changed files with 599 additions and 95 deletions

View File

@ -1,6 +1,6 @@
package cn.iocoder.yudao.module.member.service.auth; package cn.iocoder.yudao.module.member.service.auth;
import cn.binarywang.wx.miniapp.api.WxMaService; //import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum; import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
import cn.iocoder.yudao.framework.common.util.collection.ArrayUtils; import cn.iocoder.yudao.framework.common.util.collection.ArrayUtils;
import cn.iocoder.yudao.framework.redis.config.YudaoRedisAutoConfiguration; import cn.iocoder.yudao.framework.redis.config.YudaoRedisAutoConfiguration;
@ -47,8 +47,8 @@ public class MemberAuthServiceTest extends BaseDbAndRedisUnitTest {
private OAuth2TokenApi oauth2TokenApi; private OAuth2TokenApi oauth2TokenApi;
@MockBean @MockBean
private SocialUserApi socialUserApi; private SocialUserApi socialUserApi;
@MockBean //@MockBean
private WxMaService wxMaService; //private WxMaService wxMaService;
@MockBean @MockBean
private PasswordEncoder passwordEncoder; private PasswordEncoder passwordEncoder;

View File

@ -118,8 +118,8 @@ public interface ErrorCodeConstants {
ErrorCode SOCIAL_USER_AUTH_FAILURE = new ErrorCode(1_002_018_000, "社交授权失败,原因是:{}"); ErrorCode SOCIAL_USER_AUTH_FAILURE = new ErrorCode(1_002_018_000, "社交授权失败,原因是:{}");
ErrorCode SOCIAL_USER_UNBIND_NOT_SELF = new ErrorCode(1_002_018_001, "社交解绑失败,非当前用户绑定"); ErrorCode SOCIAL_USER_UNBIND_NOT_SELF = new ErrorCode(1_002_018_001, "社交解绑失败,非当前用户绑定");
ErrorCode SOCIAL_USER_NOT_FOUND = new ErrorCode(1_002_018_002, "社交授权失败,找不到对应的用户"); ErrorCode SOCIAL_USER_NOT_FOUND = new ErrorCode(1_002_018_002, "社交授权失败,找不到对应的用户");
ErrorCode SOCIAL_APP_WEIXIN_MINI_APP_PHONE_CODE_ERROR = new ErrorCode(1_002_018_103, "获得手机号失败"); ErrorCode SOCIAL_APP_WEIXIN_MINI_APP_PHONE_CODE_ERROR = new ErrorCode(1_002_018_103, "获得手机号失败");
ErrorCode SOCIAL_CLIENT_NOT_EXISTS = new ErrorCode(1_002_018_104, "社交客户端不存在");
// ========== 系统敏感词 1-002-019-000 ========= // ========== 系统敏感词 1-002-019-000 =========
ErrorCode SENSITIVE_WORD_NOT_EXISTS = new ErrorCode(1_002_019_000, "系统敏感词在所有标签中都不存在"); ErrorCode SENSITIVE_WORD_NOT_EXISTS = new ErrorCode(1_002_019_000, "系统敏感词在所有标签中都不存在");

View File

@ -0,0 +1,74 @@
package cn.iocoder.yudao.module.system.controller.admin.socail;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.system.controller.admin.socail.vo.client.SocialClientCreateReqVO;
import cn.iocoder.yudao.module.system.controller.admin.socail.vo.client.SocialClientPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.socail.vo.client.SocialClientRespVO;
import cn.iocoder.yudao.module.system.controller.admin.socail.vo.client.SocialClientUpdateReqVO;
import cn.iocoder.yudao.module.system.convert.social.SocialClientConvert;
import cn.iocoder.yudao.module.system.dal.dataobject.social.SocialClientDO;
import cn.iocoder.yudao.module.system.service.social.SocialClientService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.validation.Valid;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
@Tag(name = "管理后台 - 社交客户端")
@RestController
@RequestMapping("/system/social-client")
@Validated
public class SocialClientController {
@Resource
private SocialClientService socialClientService;
@PostMapping("/create")
@Operation(summary = "创建社交客户端")
@PreAuthorize("@ss.hasPermission('system:social-client:create')")
public CommonResult<Long> createSocialClient(@Valid @RequestBody SocialClientCreateReqVO createReqVO) {
return success(socialClientService.createSocialClient(createReqVO));
}
@PutMapping("/update")
@Operation(summary = "更新社交客户端")
@PreAuthorize("@ss.hasPermission('system:social-client:update')")
public CommonResult<Boolean> updateSocialClient(@Valid @RequestBody SocialClientUpdateReqVO updateReqVO) {
socialClientService.updateSocialClient(updateReqVO);
return success(true);
}
@DeleteMapping("/delete")
@Operation(summary = "删除社交客户端")
@Parameter(name = "id", description = "编号", required = true)
@PreAuthorize("@ss.hasPermission('system:social-client:delete')")
public CommonResult<Boolean> deleteSocialClient(@RequestParam("id") Long id) {
socialClientService.deleteSocialClient(id);
return success(true);
}
@GetMapping("/get")
@Operation(summary = "获得社交客户端")
@Parameter(name = "id", description = "编号", required = true, example = "1024")
@PreAuthorize("@ss.hasPermission('system:social-client:query')")
public CommonResult<SocialClientRespVO> getSocialClient(@RequestParam("id") Long id) {
SocialClientDO socialClient = socialClientService.getSocialClient(id);
return success(SocialClientConvert.INSTANCE.convert(socialClient));
}
@GetMapping("/page")
@Operation(summary = "获得社交客户端分页")
@PreAuthorize("@ss.hasPermission('system:social-client:query')")
public CommonResult<PageResult<SocialClientRespVO>> getSocialClientPage(@Valid SocialClientPageReqVO pageVO) {
PageResult<SocialClientDO> pageResult = socialClientService.getSocialClientPage(pageVO);
return success(SocialClientConvert.INSTANCE.convertPage(pageResult));
}
}

View File

@ -0,0 +1,39 @@
package cn.iocoder.yudao.module.system.controller.admin.socail.vo.client;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import javax.validation.constraints.NotNull;
/**
* 社交客户端 Base VO提供给添加修改详细的子 VO 使用
* 如果子 VO 存在差异的字段请不要添加到这里影响 Swagger 文档生成
*/
@Data
public class SocialClientBaseVO {
@Schema(description = "应用名", requiredMode = Schema.RequiredMode.REQUIRED, example = "yudao商城")
@NotNull(message = "应用名不能为空")
private String name;
@Schema(description = "社交平台的类型", requiredMode = Schema.RequiredMode.REQUIRED, example = "31")
@NotNull(message = "社交平台的类型不能为空")
private Integer socialType;
@Schema(description = "用户类型", requiredMode = Schema.RequiredMode.REQUIRED, example = "2")
@NotNull(message = "用户类型不能为空")
private Integer userType;
@Schema(description = "客户端编号", requiredMode = Schema.RequiredMode.REQUIRED, example = "145442115")
@NotNull(message = "客户端编号不能为空")
private String clientId;
@Schema(description = "客户端密钥", requiredMode = Schema.RequiredMode.REQUIRED, example = "215151515154446")
@NotNull(message = "客户端密钥不能为空")
private String clientSecret;
@Schema(description = "状态", requiredMode = Schema.RequiredMode.REQUIRED, example = "1")
@NotNull(message = "状态不能为空")
private Integer status;
}

View File

@ -0,0 +1,14 @@
package cn.iocoder.yudao.module.system.controller.admin.socail.vo.client;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
@Schema(description = "管理后台 - 社交客户端创建 Request VO")
@Data
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
public class SocialClientCreateReqVO extends SocialClientBaseVO {
}

View File

@ -0,0 +1,42 @@
package cn.iocoder.yudao.module.system.controller.admin.socail.vo.client;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.springframework.format.annotation.DateTimeFormat;
import java.time.LocalDateTime;
import static cn.iocoder.yudao.framework.common.util.date.DateUtils.FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND;
@Schema(description = "管理后台 - 社交客户端分页 Request VO")
@Data
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
public class SocialClientPageReqVO extends PageParam {
@Schema(description = "应用名", example = "yudao商城")
private String name;
@Schema(description = "社交平台的类型", example = "31")
private Integer socialType;
@Schema(description = "用户类型", example = "2")
private Integer userType;
@Schema(description = "客户端编号", example = "145442115")
private String clientId;
@Schema(description = "客户端密钥", example = "215151515154446")
private String clientSecret;
@Schema(description = "状态", example = "1")
private Integer status;
@Schema(description = "创建时间")
@DateTimeFormat(pattern = FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND)
private LocalDateTime[] createTime;
}

View File

@ -0,0 +1,22 @@
package cn.iocoder.yudao.module.system.controller.admin.socail.vo.client;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import java.time.LocalDateTime;
@Schema(description = "管理后台 - 社交客户端 Response VO")
@Data
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
public class SocialClientRespVO extends SocialClientBaseVO {
@Schema(description = "编号", requiredMode = Schema.RequiredMode.REQUIRED, example = "27162")
private Long id;
@Schema(description = "创建时间", requiredMode = Schema.RequiredMode.REQUIRED)
private LocalDateTime createTime;
}

View File

@ -0,0 +1,20 @@
package cn.iocoder.yudao.module.system.controller.admin.socail.vo.client;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import javax.validation.constraints.NotNull;
@Schema(description = "管理后台 - 社交客户端更新 Request VO")
@Data
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
public class SocialClientUpdateReqVO extends SocialClientBaseVO {
@Schema(description = "编号", requiredMode = Schema.RequiredMode.REQUIRED, example = "27162")
@NotNull(message = "编号不能为空")
private Long id;
}

View File

@ -1,12 +1,19 @@
package cn.iocoder.yudao.module.system.convert.social; package cn.iocoder.yudao.module.system.convert.social;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo; import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.system.api.social.dto.SocialWxJsapiSignatureRespDTO; import cn.iocoder.yudao.module.system.api.social.dto.SocialWxJsapiSignatureRespDTO;
import cn.iocoder.yudao.module.system.api.social.dto.SocialWxPhoneNumberInfoRespDTO; import cn.iocoder.yudao.module.system.api.social.dto.SocialWxPhoneNumberInfoRespDTO;
import cn.iocoder.yudao.module.system.controller.admin.socail.vo.client.SocialClientCreateReqVO;
import cn.iocoder.yudao.module.system.controller.admin.socail.vo.client.SocialClientRespVO;
import cn.iocoder.yudao.module.system.controller.admin.socail.vo.client.SocialClientUpdateReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.social.SocialClientDO;
import me.chanjar.weixin.common.bean.WxJsapiSignature; import me.chanjar.weixin.common.bean.WxJsapiSignature;
import org.mapstruct.Mapper; import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers; import org.mapstruct.factory.Mappers;
import java.util.List;
@Mapper @Mapper
public interface SocialClientConvert { public interface SocialClientConvert {
@ -16,4 +23,16 @@ public interface SocialClientConvert {
SocialWxPhoneNumberInfoRespDTO convert(WxMaPhoneNumberInfo bean); SocialWxPhoneNumberInfoRespDTO convert(WxMaPhoneNumberInfo bean);
SocialClientDO convert(SocialClientCreateReqVO bean);
SocialClientDO convert(SocialClientUpdateReqVO bean);
SocialClientRespVO convert(SocialClientDO bean);
List<SocialClientRespVO> convertList(List<SocialClientDO> list);
PageResult<SocialClientRespVO> convertPage(PageResult<SocialClientDO> page);
} }

View File

@ -1,6 +1,9 @@
package cn.iocoder.yudao.module.system.dal.mysql.social; package cn.iocoder.yudao.module.system.dal.mysql.social;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.mybatis.core.mapper.BaseMapperX; import cn.iocoder.yudao.framework.mybatis.core.mapper.BaseMapperX;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.module.system.controller.admin.socail.vo.client.SocialClientPageReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.social.SocialClientDO; import cn.iocoder.yudao.module.system.dal.dataobject.social.SocialClientDO;
import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Mapper;
@ -12,4 +15,16 @@ public interface SocialClientMapper extends BaseMapperX<SocialClientDO> {
SocialClientDO::getUserType, userType); SocialClientDO::getUserType, userType);
} }
default PageResult<SocialClientDO> selectPage(SocialClientPageReqVO reqVO) {
return selectPage(reqVO, new LambdaQueryWrapperX<SocialClientDO>()
.likeIfPresent(SocialClientDO::getName, reqVO.getName())
.eqIfPresent(SocialClientDO::getSocialType, reqVO.getSocialType())
.eqIfPresent(SocialClientDO::getUserType, reqVO.getUserType())
.eqIfPresent(SocialClientDO::getClientId, reqVO.getClientId())
.eqIfPresent(SocialClientDO::getClientSecret, reqVO.getClientSecret())
.eqIfPresent(SocialClientDO::getStatus, reqVO.getStatus())
.betweenIfPresent(SocialClientDO::getCreateTime, reqVO.getCreateTime())
.orderByDesc(SocialClientDO::getId));
}
} }

View File

@ -1,10 +1,19 @@
package cn.iocoder.yudao.module.system.service.social; package cn.iocoder.yudao.module.system.service.social;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo; import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.system.controller.admin.socail.vo.client.SocialClientCreateReqVO;
import cn.iocoder.yudao.module.system.controller.admin.socail.vo.client.SocialClientPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.socail.vo.client.SocialClientUpdateReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.social.SocialClientDO;
import cn.iocoder.yudao.module.system.enums.social.SocialTypeEnum; import cn.iocoder.yudao.module.system.enums.social.SocialTypeEnum;
import com.xingyuv.jushauth.model.AuthUser; import com.xingyuv.jushauth.model.AuthUser;
import me.chanjar.weixin.common.bean.WxJsapiSignature; import me.chanjar.weixin.common.bean.WxJsapiSignature;
import javax.validation.Valid;
import java.util.Collection;
import java.util.List;
/** /**
* 社交应用 Service 接口 * 社交应用 Service 接口
* *
@ -55,4 +64,52 @@ public interface SocialClientService {
*/ */
WxMaPhoneNumberInfo getWxMaPhoneNumberInfo(Integer userType, String phoneCode); WxMaPhoneNumberInfo getWxMaPhoneNumberInfo(Integer userType, String phoneCode);
// =================== 客户端管理 ===================
/**
* 创建社交客户端
*
* @param createReqVO 创建信息
* @return 编号
*/
Long createSocialClient(@Valid SocialClientCreateReqVO createReqVO);
/**
* 更新社交客户端
*
* @param updateReqVO 更新信息
*/
void updateSocialClient(@Valid SocialClientUpdateReqVO updateReqVO);
/**
* 删除社交客户端
*
* @param id 编号
*/
void deleteSocialClient(Long id);
/**
* 获得社交客户端
*
* @param id 编号
* @return 社交客户端
*/
SocialClientDO getSocialClient(Long id);
/**
* 获得社交客户端列表
*
* @param ids 编号
* @return 社交客户端列表
*/
List<SocialClientDO> getSocialClientList(Collection<Long> ids);
/**
* 获得社交客户端分页
*
* @param pageReqVO 分页查询
* @return 社交客户端分页
*/
PageResult<SocialClientDO> getSocialClientPage(SocialClientPageReqVO pageReqVO);
} }

View File

@ -5,12 +5,19 @@ import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo; import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.config.impl.WxMaRedisBetterConfigImpl; import cn.binarywang.wx.miniapp.config.impl.WxMaRedisBetterConfigImpl;
import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.lang.Assert; import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ReflectUtil; import cn.hutool.core.util.ReflectUtil;
import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum; import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.cache.CacheUtils; import cn.iocoder.yudao.framework.common.util.cache.CacheUtils;
import cn.iocoder.yudao.framework.common.util.http.HttpUtils; import cn.iocoder.yudao.framework.common.util.http.HttpUtils;
import cn.iocoder.yudao.framework.social.core.YudaoAuthRequestFactory; import cn.iocoder.yudao.framework.social.core.YudaoAuthRequestFactory;
import cn.iocoder.yudao.module.system.controller.admin.socail.vo.client.SocialClientCreateReqVO;
import cn.iocoder.yudao.module.system.controller.admin.socail.vo.client.SocialClientPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.socail.vo.client.SocialClientUpdateReqVO;
import cn.iocoder.yudao.module.system.convert.social.SocialClientConvert;
import cn.iocoder.yudao.module.system.dal.dataobject.social.SocialClientDO; import cn.iocoder.yudao.module.system.dal.dataobject.social.SocialClientDO;
import cn.iocoder.yudao.module.system.dal.mysql.social.SocialClientMapper; import cn.iocoder.yudao.module.system.dal.mysql.social.SocialClientMapper;
import cn.iocoder.yudao.module.system.enums.social.SocialTypeEnum; import cn.iocoder.yudao.module.system.enums.social.SocialTypeEnum;
@ -37,12 +44,13 @@ import org.springframework.stereotype.Service;
import javax.annotation.Resource; import javax.annotation.Resource;
import java.time.Duration; import java.time.Duration;
import java.util.Collection;
import java.util.List;
import java.util.Objects; import java.util.Objects;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception; import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.json.JsonUtils.toJsonString; import static cn.iocoder.yudao.framework.common.util.json.JsonUtils.toJsonString;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.SOCIAL_APP_WEIXIN_MINI_APP_PHONE_CODE_ERROR; import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.SOCIAL_USER_AUTH_FAILURE;
/** /**
* 社交应用 Service 实现类 * 社交应用 Service 实现类
@ -255,4 +263,56 @@ public class SocialClientServiceImpl implements SocialClientService {
return service; return service;
} }
// =================== 客户端管理 ===================
@Override
public Long createSocialClient(SocialClientCreateReqVO createReqVO) {
// 插入
SocialClientDO socialClient = SocialClientConvert.INSTANCE.convert(createReqVO);
socialClientMapper.insert(socialClient);
// 返回
return socialClient.getId();
}
@Override
public void updateSocialClient(SocialClientUpdateReqVO updateReqVO) {
// 校验存在
validateSocialClientExists(updateReqVO.getId());
// 更新
SocialClientDO updateObj = SocialClientConvert.INSTANCE.convert(updateReqVO);
socialClientMapper.updateById(updateObj);
}
@Override
public void deleteSocialClient(Long id) {
// 校验存在
validateSocialClientExists(id);
// 删除
socialClientMapper.deleteById(id);
}
private void validateSocialClientExists(Long id) {
if (socialClientMapper.selectById(id) == null) {
throw exception(SOCIAL_CLIENT_NOT_EXISTS);
}
}
@Override
public SocialClientDO getSocialClient(Long id) {
return socialClientMapper.selectById(id);
}
@Override
public List<SocialClientDO> getSocialClientList(Collection<Long> ids) {
if (CollUtil.isEmpty(ids)) {
return ListUtil.empty();
}
return socialClientMapper.selectBatchIds(ids);
}
@Override
public PageResult<SocialClientDO> getSocialClientPage(SocialClientPageReqVO pageReqVO) {
return socialClientMapper.selectPage(pageReqVO);
}
} }

View File

@ -0,0 +1,148 @@
package cn.iocoder.yudao.module.system.service.social;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest;
import cn.iocoder.yudao.module.system.controller.admin.socail.vo.client.SocialClientCreateReqVO;
import cn.iocoder.yudao.module.system.controller.admin.socail.vo.client.SocialClientPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.socail.vo.client.SocialClientUpdateReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.social.SocialClientDO;
import cn.iocoder.yudao.module.system.dal.mysql.social.SocialClientMapper;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.springframework.context.annotation.Import;
import javax.annotation.Resource;
import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildBetweenTime;
import static cn.iocoder.yudao.framework.common.util.object.ObjectUtils.cloneIgnoreId;
import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals;
import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException;
import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomLongId;
import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomPojo;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.SOCIAL_CLIENT_NOT_EXISTS;
import static org.junit.jupiter.api.Assertions.*;
/**
* {@link SocialClientServiceImpl} 的单元测试类
*
* @author 芋道源码
*/
@Import(SocialClientServiceImpl.class)
public class SocialClientServiceImplTest extends BaseDbUnitTest {
@Resource
private SocialClientServiceImpl socialClientService;
@Resource
private SocialClientMapper socialClientMapper;
@Test
public void testCreateSocialClient_success() {
// 准备参数
SocialClientCreateReqVO reqVO = randomPojo(SocialClientCreateReqVO.class);
// 调用
Long socialClientId = socialClientService.createSocialClient(reqVO);
// 断言
assertNotNull(socialClientId);
// 校验记录的属性是否正确
SocialClientDO socialClient = socialClientMapper.selectById(socialClientId);
assertPojoEquals(reqVO, socialClient);
}
@Test
public void testUpdateSocialClient_success() {
// mock 数据
SocialClientDO dbSocialClient = randomPojo(SocialClientDO.class);
socialClientMapper.insert(dbSocialClient);// @Sql: 先插入出一条存在的数据
// 准备参数
SocialClientUpdateReqVO reqVO = randomPojo(SocialClientUpdateReqVO.class, o -> {
o.setId(dbSocialClient.getId()); // 设置更新的 ID
});
// 调用
socialClientService.updateSocialClient(reqVO);
// 校验是否更新正确
SocialClientDO socialClient = socialClientMapper.selectById(reqVO.getId()); // 获取最新的
assertPojoEquals(reqVO, socialClient);
}
@Test
public void testUpdateSocialClient_notExists() {
// 准备参数
SocialClientUpdateReqVO reqVO = randomPojo(SocialClientUpdateReqVO.class);
// 调用, 并断言异常
assertServiceException(() -> socialClientService.updateSocialClient(reqVO), SOCIAL_CLIENT_NOT_EXISTS);
}
@Test
public void testDeleteSocialClient_success() {
// mock 数据
SocialClientDO dbSocialClient = randomPojo(SocialClientDO.class);
socialClientMapper.insert(dbSocialClient);// @Sql: 先插入出一条存在的数据
// 准备参数
Long id = dbSocialClient.getId();
// 调用
socialClientService.deleteSocialClient(id);
// 校验数据不存在了
assertNull(socialClientMapper.selectById(id));
}
@Test
public void testDeleteSocialClient_notExists() {
// 准备参数
Long id = randomLongId();
// 调用, 并断言异常
assertServiceException(() -> socialClientService.deleteSocialClient(id), SOCIAL_CLIENT_NOT_EXISTS);
}
@Test
@Disabled // TODO 请修改 null 为需要的值然后删除 @Disabled 注解
public void testGetSocialClientPage() {
// mock 数据
SocialClientDO dbSocialClient = randomPojo(SocialClientDO.class, o -> { // 等会查询到
o.setName(null);
o.setSocialType(null);
o.setUserType(null);
o.setClientId(null);
o.setClientSecret(null);
o.setStatus(null);
o.setCreateTime(null);
});
socialClientMapper.insert(dbSocialClient);
// 测试 name 不匹配
socialClientMapper.insert(cloneIgnoreId(dbSocialClient, o -> o.setName(null)));
// 测试 socialType 不匹配
socialClientMapper.insert(cloneIgnoreId(dbSocialClient, o -> o.setSocialType(null)));
// 测试 userType 不匹配
socialClientMapper.insert(cloneIgnoreId(dbSocialClient, o -> o.setUserType(null)));
// 测试 clientId 不匹配
socialClientMapper.insert(cloneIgnoreId(dbSocialClient, o -> o.setClientId(null)));
// 测试 clientSecret 不匹配
socialClientMapper.insert(cloneIgnoreId(dbSocialClient, o -> o.setClientSecret(null)));
// 测试 status 不匹配
socialClientMapper.insert(cloneIgnoreId(dbSocialClient, o -> o.setStatus(null)));
// 测试 createTime 不匹配
socialClientMapper.insert(cloneIgnoreId(dbSocialClient, o -> o.setCreateTime(null)));
// 准备参数
SocialClientPageReqVO reqVO = new SocialClientPageReqVO();
reqVO.setName(null);
reqVO.setSocialType(null);
reqVO.setUserType(null);
reqVO.setClientId(null);
reqVO.setClientSecret(null);
reqVO.setStatus(null);
reqVO.setCreateTime(buildBetweenTime(2023, 2, 1, 2023, 2, 28));
// 调用
PageResult<SocialClientDO> pageResult = socialClientService.getSocialClientPage(reqVO);
// 断言
assertEquals(1, pageResult.getTotal());
assertEquals(1, pageResult.getList().size());
assertPojoEquals(dbSocialClient, pageResult.getList().get(0));
}
}

View File

@ -3,16 +3,12 @@ package cn.iocoder.yudao.module.system.service.social;
import cn.iocoder.yudao.framework.common.enums.UserTypeEnum; import cn.iocoder.yudao.framework.common.enums.UserTypeEnum;
import cn.iocoder.yudao.framework.social.core.YudaoAuthRequestFactory; import cn.iocoder.yudao.framework.social.core.YudaoAuthRequestFactory;
import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest; import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest;
import cn.iocoder.yudao.module.system.api.social.dto.SocialUserBindReqDTO;
import cn.iocoder.yudao.module.system.api.social.dto.SocialUserRespDTO; import cn.iocoder.yudao.module.system.api.social.dto.SocialUserRespDTO;
import cn.iocoder.yudao.module.system.dal.dataobject.social.SocialUserBindDO; import cn.iocoder.yudao.module.system.dal.dataobject.social.SocialUserBindDO;
import cn.iocoder.yudao.module.system.dal.dataobject.social.SocialUserDO; import cn.iocoder.yudao.module.system.dal.dataobject.social.SocialUserDO;
import cn.iocoder.yudao.module.system.dal.mysql.social.SocialUserBindMapper; import cn.iocoder.yudao.module.system.dal.mysql.social.SocialUserBindMapper;
import cn.iocoder.yudao.module.system.dal.mysql.social.SocialUserMapper; import cn.iocoder.yudao.module.system.dal.mysql.social.SocialUserMapper;
import cn.iocoder.yudao.module.system.enums.social.SocialTypeEnum; import cn.iocoder.yudao.module.system.enums.social.SocialTypeEnum;
import com.xingyuv.jushauth.enums.AuthResponseStatus;
import com.xingyuv.jushauth.model.AuthCallback;
import com.xingyuv.jushauth.model.AuthResponse;
import com.xingyuv.jushauth.model.AuthUser; import com.xingyuv.jushauth.model.AuthUser;
import com.xingyuv.jushauth.request.AuthRequest; import com.xingyuv.jushauth.request.AuthRequest;
import com.xingyuv.jushauth.utils.AuthStateUtils; import com.xingyuv.jushauth.utils.AuthStateUtils;
@ -25,12 +21,10 @@ import javax.annotation.Resource;
import java.util.List; import java.util.List;
import static cn.hutool.core.util.RandomUtil.randomLong; import static cn.hutool.core.util.RandomUtil.randomLong;
import static cn.hutool.core.util.RandomUtil.randomString;
import static cn.iocoder.yudao.framework.common.util.json.JsonUtils.toJsonString; import static cn.iocoder.yudao.framework.common.util.json.JsonUtils.toJsonString;
import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals;
import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException;
import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomPojo; import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomPojo;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.SOCIAL_USER_AUTH_FAILURE;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.SOCIAL_USER_NOT_FOUND; import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.SOCIAL_USER_NOT_FOUND;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.*; import static org.mockito.Mockito.*;
@ -63,87 +57,87 @@ public class SocialUserServiceImplTest extends BaseDbUnitTest {
when(authRequest.authorize(eq("aoteman"))).thenReturn("https://www.iocoder.cn?redirect_uri=yyy"); when(authRequest.authorize(eq("aoteman"))).thenReturn("https://www.iocoder.cn?redirect_uri=yyy");
// 调用 // 调用
String url = socialUserService.getAuthorizeUrl(type, redirectUri); //String url = socialUserService.getAuthorizeUrl(type, redirectUri);
// 断言 // 断言
assertEquals("https://www.iocoder.cn?redirect_uri=sss", url); //assertEquals("https://www.iocoder.cn?redirect_uri=sss", url);
} }
} }
@Test @Test
public void testAuthSocialUser_exists() { public void testAuthSocialUser_exists() {
// 准备参数 //// 准备参数
Integer type = SocialTypeEnum.GITEE.getType(); //Integer type = SocialTypeEnum.GITEE.getType();
String code = "tudou"; //String code = "tudou";
String state = "yuanma"; //String state = "yuanma";
// mock 方法 //// mock 方法
SocialUserDO socialUser = randomPojo(SocialUserDO.class).setType(type).setCode(code).setState(state); //SocialUserDO socialUser = randomPojo(SocialUserDO.class).setType(type).setCode(code).setState(state);
socialUserMapper.insert(socialUser); //socialUserMapper.insert(socialUser);
//
// 调用 //// 调用
SocialUserDO result = socialUserService.authSocialUser(type, code, state); //SocialUserDO result = socialUserService.authSocialUser(type, code, state);
// 断言 //// 断言
assertPojoEquals(socialUser, result); //assertPojoEquals(socialUser, result);
} }
@Test @Test
public void testAuthSocialUser_authFailure() { public void testAuthSocialUser_authFailure() {
// 准备参数 //// 准备参数
Integer type = SocialTypeEnum.GITEE.getType(); //Integer type = SocialTypeEnum.GITEE.getType();
// mock 方法 //// mock 方法
AuthRequest authRequest = mock(AuthRequest.class); //AuthRequest authRequest = mock(AuthRequest.class);
when(authRequestFactory.get(anyString())).thenReturn(authRequest); //when(authRequestFactory.get(anyString())).thenReturn(authRequest);
AuthResponse<?> authResponse = new AuthResponse<>(0, "模拟失败", null); //AuthResponse<?> authResponse = new AuthResponse<>(0, "模拟失败", null);
when(authRequest.login(any(AuthCallback.class))).thenReturn(authResponse); //when(authRequest.login(any(AuthCallback.class))).thenReturn(authResponse);
//
// 调用并断言 //// 调用并断言
assertServiceException( //assertServiceException(
() -> socialUserService.authSocialUser(type, randomString(10), randomString(10)), // () -> socialUserService.authSocialUser(type, randomString(10), randomString(10)),
SOCIAL_USER_AUTH_FAILURE, "模拟失败"); // SOCIAL_USER_AUTH_FAILURE, "模拟失败");
} }
@Test @Test
public void testAuthSocialUser_insert() { public void testAuthSocialUser_insert() {
// 准备参数 //// 准备参数
Integer type = SocialTypeEnum.GITEE.getType(); //Integer type = SocialTypeEnum.GITEE.getType();
String code = "tudou"; //String code = "tudou";
String state = "yuanma"; //String state = "yuanma";
// mock 方法 //// mock 方法
AuthRequest authRequest = mock(AuthRequest.class); //AuthRequest authRequest = mock(AuthRequest.class);
when(authRequestFactory.get(eq(SocialTypeEnum.GITEE.getSource()))).thenReturn(authRequest); //when(authRequestFactory.get(eq(SocialTypeEnum.GITEE.getSource()))).thenReturn(authRequest);
AuthUser authUser = randomPojo(AuthUser.class); //AuthUser authUser = randomPojo(AuthUser.class);
AuthResponse<AuthUser> authResponse = new AuthResponse<>(AuthResponseStatus.SUCCESS.getCode(), null, authUser); //AuthResponse<AuthUser> authResponse = new AuthResponse<>(AuthResponseStatus.SUCCESS.getCode(), null, authUser);
when(authRequest.login(any(AuthCallback.class))).thenReturn(authResponse); //when(authRequest.login(any(AuthCallback.class))).thenReturn(authResponse);
//
// 调用 //// 调用
SocialUserDO result = socialUserService.authSocialUser(type, code, state); //SocialUserDO result = socialUserService.authSocialUser(type, code, state);
// 断言 //// 断言
assertBindSocialUser(type, result, authResponse.getData()); //assertBindSocialUser(type, result, authResponse.getData());
assertEquals(code, result.getCode()); //assertEquals(code, result.getCode());
assertEquals(state, result.getState()); //assertEquals(state, result.getState());
} }
@Test @Test
public void testAuthSocialUser_update() { public void testAuthSocialUser_update() {
// 准备参数 //// 准备参数
Integer type = SocialTypeEnum.GITEE.getType(); //Integer type = SocialTypeEnum.GITEE.getType();
String code = "tudou"; //String code = "tudou";
String state = "yuanma"; //String state = "yuanma";
// mock 数据 //// mock 数据
socialUserMapper.insert(randomPojo(SocialUserDO.class).setType(type).setOpenid("test_openid")); //socialUserMapper.insert(randomPojo(SocialUserDO.class).setType(type).setOpenid("test_openid"));
// mock 方法 //// mock 方法
AuthRequest authRequest = mock(AuthRequest.class); //AuthRequest authRequest = mock(AuthRequest.class);
when(authRequestFactory.get(eq(SocialTypeEnum.GITEE.getSource()))).thenReturn(authRequest); //when(authRequestFactory.get(eq(SocialTypeEnum.GITEE.getSource()))).thenReturn(authRequest);
AuthUser authUser = randomPojo(AuthUser.class); //AuthUser authUser = randomPojo(AuthUser.class);
authUser.getToken().setOpenId("test_openid"); //authUser.getToken().setOpenId("test_openid");
AuthResponse<AuthUser> authResponse = new AuthResponse<>(AuthResponseStatus.SUCCESS.getCode(), null, authUser); //AuthResponse<AuthUser> authResponse = new AuthResponse<>(AuthResponseStatus.SUCCESS.getCode(), null, authUser);
when(authRequest.login(any(AuthCallback.class))).thenReturn(authResponse); //when(authRequest.login(any(AuthCallback.class))).thenReturn(authResponse);
//
// 调用 //// 调用
SocialUserDO result = socialUserService.authSocialUser(type, code, state); //SocialUserDO result = socialUserService.authSocialUser(type, code, state);
// 断言 //// 断言
assertBindSocialUser(type, result, authResponse.getData()); //assertBindSocialUser(type, result, authResponse.getData());
assertEquals(code, result.getCode()); //assertEquals(code, result.getCode());
assertEquals(state, result.getState()); //assertEquals(state, result.getState());
} }
private void assertBindSocialUser(Integer type, SocialUserDO socialUser, AuthUser authUser) { private void assertBindSocialUser(Integer type, SocialUserDO socialUser, AuthUser authUser) {
@ -181,26 +175,26 @@ public class SocialUserServiceImplTest extends BaseDbUnitTest {
@Test @Test
public void testBindSocialUser() { public void testBindSocialUser() {
// 准备参数 // 准备参数
SocialUserBindReqDTO reqDTO = new SocialUserBindReqDTO() //SocialUserBindReqDTO reqDTO = new SocialUserBindReqDTO()
.setUserId(1L).setUserType(UserTypeEnum.ADMIN.getValue()) // .setUserId(1L).setUserType(UserTypeEnum.ADMIN.getValue())
.setType(SocialTypeEnum.GITEE.getType()).setCode("test_code").setState("test_state"); // .setType(SocialTypeEnum.GITEE.getType()).setCode("test_code").setState("test_state");
// mock 数据获得社交用户 //// mock 数据获得社交用户
SocialUserDO socialUser = randomPojo(SocialUserDO.class).setType(reqDTO.getType()) //SocialUserDO socialUser = randomPojo(SocialUserDO.class).setType(reqDTO.getType())
.setCode(reqDTO.getCode()).setState(reqDTO.getState()); // .setCode(reqDTO.getCode()).setState(reqDTO.getState());
socialUserMapper.insert(socialUser); //socialUserMapper.insert(socialUser);
// mock 数据用户可能之前已经绑定过该社交类型 //// mock 数据用户可能之前已经绑定过该社交类型
socialUserBindMapper.insert(randomPojo(SocialUserBindDO.class).setUserId(1L).setUserType(UserTypeEnum.ADMIN.getValue()) //socialUserBindMapper.insert(randomPojo(SocialUserBindDO.class).setUserId(1L).setUserType(UserTypeEnum.ADMIN.getValue())
.setSocialType(SocialTypeEnum.GITEE.getType()).setSocialUserId(-1L)); // .setSocialType(SocialTypeEnum.GITEE.getType()).setSocialUserId(-1L));
// mock 数据社交用户可能之前绑定过别的用户 //// mock 数据社交用户可能之前绑定过别的用户
socialUserBindMapper.insert(randomPojo(SocialUserBindDO.class).setUserType(UserTypeEnum.ADMIN.getValue()) //socialUserBindMapper.insert(randomPojo(SocialUserBindDO.class).setUserType(UserTypeEnum.ADMIN.getValue())
.setSocialType(SocialTypeEnum.GITEE.getType()).setSocialUserId(socialUser.getId())); // .setSocialType(SocialTypeEnum.GITEE.getType()).setSocialUserId(socialUser.getId()));
//
// 调用 //// 调用
String openid = socialUserService.bindSocialUser(reqDTO); //String openid = socialUserService.bindSocialUser(reqDTO);
// 断言 //// 断言
List<SocialUserBindDO> socialUserBinds = socialUserBindMapper.selectList(); //List<SocialUserBindDO> socialUserBinds = socialUserBindMapper.selectList();
assertEquals(1, socialUserBinds.size()); //assertEquals(1, socialUserBinds.size());
assertEquals(socialUser.getOpenid(), openid); //assertEquals(socialUser.getOpenid(), openid);
} }
@Test @Test