重构社交登录,完善单元测试

This commit is contained in:
YunaiV 2022-04-26 02:17:38 +08:00
parent 89df5b3cf6
commit 878445a238
8 changed files with 110 additions and 187 deletions

View File

@ -23,33 +23,33 @@ public enum SocialTypeEnum implements IntArrayValuable {
* Gitee
* 文档链接https://gitee.com/api/v5/oauth_doc#/
*/
GITEE(10, 1, "GITEE"),
GITEE(10, "GITEE"),
/**
* 钉钉
* 文档链接https://developers.dingtalk.com/document/app/obtain-identity-credentials
*/
DINGTALK(20, 2, "DINGTALK"),
DINGTALK(20, "DINGTALK"),
/**
* 企业微信
* 文档链接https://xkcoding.com/2019/08/06/use-justauth-integration-wechat-enterprise.html
*/
WECHAT_ENTERPRISE(30, 3, "WECHAT_ENTERPRISE"),
WECHAT_ENTERPRISE(30, "WECHAT_ENTERPRISE"),
/**
* 微信公众平台 - 移动端 H5
* 文档链接https://www.cnblogs.com/juewuzhe/p/11905461.html
*/
WECHAT_MP(31, 3, "WECHAT_MP"),
WECHAT_MP(31, "WECHAT_MP"),
/**
* 微信开放平台 - 网站应用 PC 端扫码授权登录
* 文档链接https://justauth.wiki/guide/oauth/wechat_open/#_2-申请开发者资质认证
*/
WECHAT_OPEN(32, 3, "WECHAT_OPEN"),
WECHAT_OPEN(32, "WECHAT_OPEN"),
/**
* 微信小程序
* 文档链接https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/login.html
*/
WECHAT_MINI_PROGRAM(33, 3, "WECHAT_MINI_PROGRAM"),
WECHAT_MINI_PROGRAM(33, "WECHAT_MINI_PROGRAM"),
;
public static final int[] ARRAYS = Arrays.stream(values()).mapToInt(SocialTypeEnum::getType).toArray();
@ -58,12 +58,6 @@ public enum SocialTypeEnum implements IntArrayValuable {
* 类型
*/
private final Integer type;
/**
* 平台
*
* 例如说微信平台下有企业微信公众平台开放平台小程序等
*/
private final Integer platform;
/**
* 类型的标识
*/
@ -78,11 +72,4 @@ public enum SocialTypeEnum implements IntArrayValuable {
return ArrayUtil.firstMatch(o -> o.getType().equals(type), values());
}
public static Set<Integer> getTypes(Collection<Integer> platforms) {
return Arrays.stream(values())
.filter(socialTypeEnum -> platforms.contains(socialTypeEnum.getPlatform()))
.map(SocialTypeEnum::getType)
.collect(Collectors.toSet());
}
}

View File

@ -22,6 +22,8 @@ public class SocialUserBindDO extends BaseDO {
/**
* 关联的用户编号
*
* 关联 UserDO 的编号
*/
private Long userId;
/**
@ -32,14 +34,16 @@ public class SocialUserBindDO extends BaseDO {
private Integer userType;
/**
* 社交平台
* 社交平台的用户编号
*
* 枚举 {@link SocialTypeEnum#getPlatform()}
* 关联 {@link SocialUserDO#getId()}
*/
private Integer platform;
private Long socialUserId;
/**
* 社交的全局编号
* 社交平台的类型
*
* 冗余 {@link SocialUserDO#getType()}
*/
private String unionId;
private Integer socialType;
}

View File

@ -1,7 +1,5 @@
package cn.iocoder.yudao.module.system.dal.dataobject.social;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.framework.common.enums.UserTypeEnum;
import cn.iocoder.yudao.framework.mybatis.core.dataobject.BaseDO;
import cn.iocoder.yudao.module.system.enums.social.SocialTypeEnum;
import com.baomidou.mybatisplus.annotation.TableId;
@ -10,7 +8,6 @@ import lombok.*;
/**
* 社交用户
* 通过 {@link SocialUserDO#getUserId()} 关联到对应的 {@link AdminUserDO}
*
* @author weir
*/

View File

@ -10,26 +10,23 @@ import java.util.List;
@Mapper
public interface SocialUserBindMapper extends BaseMapperX<SocialUserBindDO> {
default void deleteByUserTypeAndUserIdAndUnionId(Integer userType, Long userId, Integer platform) {
default void deleteByUserTypeAndUserIdAndSocialType(Integer userType, Long userId, Integer socialType) {
delete(new LambdaQueryWrapperX<SocialUserBindDO>()
.eq(SocialUserBindDO::getUserType, userType)
.eq(SocialUserBindDO::getUserId, userId)
.eq(SocialUserBindDO::getPlatform, platform));
.eq(SocialUserBindDO::getSocialType, socialType));
}
default void deleteByUserTypeAndPlatformAndUnionId(Integer userType, Integer platform, String unionId) {
default void deleteByUserTypeAndSocialUserId(Integer userType, Long socialUserId) {
delete(new LambdaQueryWrapperX<SocialUserBindDO>()
.eq(SocialUserBindDO::getUserType, userType)
.eq(SocialUserBindDO::getPlatform, platform)
.eq(SocialUserBindDO::getUnionId, unionId));
.eq(SocialUserBindDO::getSocialUserId, socialUserId));
}
default SocialUserBindDO selectByUserTypeAndPlatformAndUnionId(Integer userType,
Integer platform, String unionId) {
default SocialUserBindDO selectByUserTypeAndSocialUserId(Integer userType, Long socialUserId) {
return selectOne(new LambdaQueryWrapperX<SocialUserBindDO>()
.eq(SocialUserBindDO::getUserType, userType)
.eq(SocialUserBindDO::getPlatform, platform)
.eq(SocialUserBindDO::getUnionId, unionId));
.eq(SocialUserBindDO::getSocialUserId, socialUserId));
}
default List<SocialUserBindDO> selectListByUserIdAndUserType(Long userId, Integer userType) {

View File

@ -22,13 +22,7 @@ public interface SocialUserMapper extends BaseMapperX<SocialUserDO> {
default SocialUserDO selectByTypeAndOpenid(Integer type, String openid) {
return selectOne(new LambdaQueryWrapper<SocialUserDO>()
.eq(SocialUserDO::getType, type)
.eq(SocialUserDO::getCode, openid));
}
default List<SocialUserDO> selectListByUnionIdAndType(Collection<String> unionIds, Collection<Integer> types) {
return selectList(new LambdaQueryWrapper<SocialUserDO>()
.in(SocialUserDO::getUnionId, unionIds)
.in(SocialUserDO::getType, types));
.eq(SocialUserDO::getOpenid, openid));
}
}

View File

@ -2,8 +2,6 @@ package cn.iocoder.yudao.module.system.service.social;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils;
import cn.iocoder.yudao.framework.common.util.http.HttpUtils;
import cn.iocoder.yudao.module.system.api.social.dto.SocialUserBindReqDTO;
import cn.iocoder.yudao.module.system.dal.dataobject.social.SocialUserBindDO;
@ -25,9 +23,9 @@ import org.springframework.validation.annotation.Validated;
import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;
import static cn.iocoder.yudao.framework.common.util.json.JsonUtils.toJsonString;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*;
@ -78,7 +76,6 @@ public class SocialUserServiceImpl implements SocialUserService {
}
socialUser.setType(type).setCode(code).setState(state) // 需要保存 code + state 字段保证后续可查询
.setOpenid(authUser.getUuid()).setToken(authUser.getToken().getAccessToken()).setRawTokenInfo((toJsonString(authUser.getToken())))
.setUnionId(StrUtil.blankToDefault(authUser.getToken().getUnionId(), authUser.getUuid())) // unionId 识别多个用户
.setNickname(authUser.getNickname()).setAvatar(authUser.getAvatar()).setRawUserInfo(toJsonString(authUser.getRawUserInfo()));
if (socialUser.getId() == null) {
socialUserMapper.insert(socialUser);
@ -96,9 +93,7 @@ public class SocialUserServiceImpl implements SocialUserService {
return Collections.emptyList();
}
// 获得社交用户
Set<Integer> platforms = CollectionUtils.convertSet(socialUserBinds, SocialUserBindDO::getPlatform);
return socialUserMapper.selectListByUnionIdAndType(CollectionUtils.convertSet(socialUserBinds, SocialUserBindDO::getUnionId),
SocialTypeEnum.getTypes(platforms));
return socialUserMapper.selectBatchIds(convertSet(socialUserBinds, SocialUserBindDO::getSocialUserId));
}
@Override
@ -108,19 +103,17 @@ public class SocialUserServiceImpl implements SocialUserService {
SocialUserDO socialUser = authSocialUser(reqDTO.getType(), reqDTO.getCode(), reqDTO.getState());
Assert.notNull(socialUser, "社交用户不能为空");
// 如果 unionId 之前被绑定过需要进行解绑
Integer platform = SocialTypeEnum.valueOfType(socialUser.getType()).getPlatform();
socialUserBindMapper.deleteByUserTypeAndPlatformAndUnionId(reqDTO.getUserType(), platform,
socialUser.getUnionId());
// 社交用户可能之前绑定过别的用户需要进行解绑
socialUserBindMapper.deleteByUserTypeAndSocialUserId(reqDTO.getUserType(), socialUser.getId());
// 如果 userId 之前绑定过该 type 的其它账号需要进行解绑
socialUserBindMapper.deleteByUserTypeAndUserIdAndUnionId(reqDTO.getUserType(), reqDTO.getUserId(),
socialUser.getUnionId());
// 用户可能之前已经绑定过该社交类型需要进行解绑
socialUserBindMapper.deleteByUserTypeAndUserIdAndSocialType(reqDTO.getUserType(), reqDTO.getUserId(),
socialUser.getType());
// 绑定当前登录的社交用户
SocialUserBindDO socialUserBind = SocialUserBindDO.builder()
.userId(reqDTO.getUserId()).userType(reqDTO.getUserType())
.platform(platform).unionId(socialUser.getUnionId()).build();
.socialUserId(socialUser.getId()).socialType(socialUser.getType()).build();
socialUserBindMapper.insert(socialUserBind);
}
@ -133,8 +126,7 @@ public class SocialUserServiceImpl implements SocialUserService {
}
// 获得对应的社交绑定关系
socialUserBindMapper.deleteByUserTypeAndUserIdAndPlatformAndUnionId(userType, userId,
SocialTypeEnum.valueOfType(socialUser.getType()).getPlatform(), socialUser.getUnionId());
socialUserBindMapper.deleteByUserTypeAndUserIdAndSocialType(userType, userId, socialUser.getType());
}
@Override
@ -144,8 +136,8 @@ public class SocialUserServiceImpl implements SocialUserService {
Assert.notNull(socialUser, "社交用户不能为空");
// 如果未绑定的社交用户则无法自动登录进行报错
SocialUserBindDO socialUserBind = socialUserBindMapper.selectByUserTypeAndPlatformAndUnionId(userType,
SocialTypeEnum.valueOfType(socialUser.getType()).getPlatform(), socialUser.getUnionId());
SocialUserBindDO socialUserBind = socialUserBindMapper.selectByUserTypeAndSocialUserId(userType,
socialUser.getId());
if (socialUserBind == null) {
throw exception(AUTH_THIRD_LOGIN_NOT_BIND);
}

View File

@ -1,16 +1,13 @@
package cn.iocoder.yudao.module.system.service.social;
import cn.iocoder.yudao.framework.common.enums.UserTypeEnum;
import cn.iocoder.yudao.framework.test.core.util.AssertUtils;
import cn.iocoder.yudao.framework.test.core.util.RandomUtils;
import cn.iocoder.yudao.framework.test.core.ut.BaseDbAndRedisUnitTest;
import cn.iocoder.yudao.module.system.api.social.dto.SocialUserBindReqDTO;
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.mysql.social.SocialUserBindMapper;
import cn.iocoder.yudao.module.system.dal.mysql.social.SocialUserMapper;
import cn.iocoder.yudao.framework.test.core.ut.BaseDbAndRedisUnitTest;
import cn.iocoder.yudao.module.system.enums.social.SocialTypeEnum;
import com.baomidou.mybatisplus.core.toolkit.PluginUtils;
import com.xkcoding.justauth.AuthRequestFactory;
import me.zhyd.oauth.enums.AuthResponseStatus;
import me.zhyd.oauth.model.AuthCallback;
@ -19,16 +16,15 @@ import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
import org.mockito.MockedStatic;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Import;
import javax.annotation.Resource;
import java.util.List;
import static cn.hutool.core.util.RandomUtil.*;
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.test.core.util.AssertUtils.assertPojoEquals;
import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException;
@ -157,24 +153,22 @@ public class SocialUserServiceTest extends BaseDbAndRedisUnitTest {
assertEquals(toJsonString(authUser.getRawUserInfo()), socialUser.getRawUserInfo());
assertEquals(type, socialUser.getType());
assertEquals(authUser.getUuid(), socialUser.getOpenid());
assertEquals(authUser.getToken().getUnionId(), socialUser.getUnionId());
}
@Test
public void testGetSocialUserList() {
Long userId = 1L;
Integer userType = UserTypeEnum.ADMIN.getValue();
// mock 获得绑定
socialUserBindMapper.insert(randomPojo(SocialUserBindDO.class) // 可被查询到
.setUserId(userId).setUserType(userType).setPlatform(SocialTypeEnum.GITEE.getPlatform())
.setUnionId("test_unionId"));
socialUserBindMapper.insert(randomPojo(SocialUserBindDO.class) // 不可被查询到
.setUserId(2L).setUserType(userType).setPlatform(SocialTypeEnum.DINGTALK.getPlatform()));
// mock 获得社交用户
SocialUserDO socialUser = randomPojo(SocialUserDO.class).setType(SocialTypeEnum.GITEE.getType())
.setUnionId("test_unionId");
SocialUserDO socialUser = randomPojo(SocialUserDO.class).setType(SocialTypeEnum.GITEE.getType());
socialUserMapper.insert(socialUser); // 可被查到
socialUserMapper.insert(randomPojo(SocialUserDO.class)); // 不可被查到
// mock 获得绑定
socialUserBindMapper.insert(randomPojo(SocialUserBindDO.class) // 可被查询到
.setUserId(userId).setUserType(userType).setSocialType(SocialTypeEnum.GITEE.getType())
.setSocialUserId(socialUser.getId()));
socialUserBindMapper.insert(randomPojo(SocialUserBindDO.class) // 不可被查询到
.setUserId(2L).setUserType(userType).setSocialType(SocialTypeEnum.DINGTALK.getType()));
// 调用
List<SocialUserDO> result = socialUserService.getSocialUserList(userId, userType);
@ -184,120 +178,79 @@ public class SocialUserServiceTest extends BaseDbAndRedisUnitTest {
}
@Test
public void testBindSocialUser_create() {
public void testBindSocialUser() {
// 准备参数
SocialUserBindReqDTO reqDTO = new SocialUserBindReqDTO()
.setUserId(1L).setUserType(UserTypeEnum.ADMIN.getValue())
.setType(SocialTypeEnum.GITEE.getType()).setCode("test_code").setState("test_state");
// mock 数据获得社交用户
SocialUserDO socialUser = randomPojo(SocialUserDO.class).setType(reqDTO.getType())
.setCode(reqDTO.getCode()).setState(reqDTO.getState()).setUnionId("test_unionId");
.setCode(reqDTO.getCode()).setState(reqDTO.getState());
socialUserMapper.insert(socialUser);
// mock 数据解绑其它账号
// mock 数据用户可能之前已经绑定过该社交类型
socialUserBindMapper.insert(randomPojo(SocialUserBindDO.class).setUserId(1L).setUserType(UserTypeEnum.ADMIN.getValue())
.setPlatform(SocialTypeEnum.GITEE.getPlatform()).setUnionId("test_delete_unionId"));
.setSocialType(SocialTypeEnum.GITEE.getType()).setSocialUserId(-1L));
// mock 数据社交用户可能之前绑定过别的用户
socialUserBindMapper.insert(randomPojo(SocialUserBindDO.class).setUserType(UserTypeEnum.ADMIN.getValue())
.setSocialType(SocialTypeEnum.GITEE.getType()).setSocialUserId(socialUser.getId()));
// 调用
socialUserService.bindSocialUser(reqDTO);
// 断言
List<SocialUserBindDO> socialUserBinds = socialUserBindMapper.selectList();
assertEquals(1, socialUserBinds.size());
}
//
// /**
// * 情况二更新 SocialUserDO 的情况
// */
// @Test
// public void testBindSocialUser_update() {
// // mock 数据
// SocialUserDO dbSocialUser = randomPojo(SocialUserDO.class, socialUserDO -> {
// socialUserDO.setUserType(UserTypeEnum.ADMIN.getValue());
// socialUserDO.setType(randomEle(SocialTypeEnum.values()).getType());
// });
// socialUserMapper.insert(dbSocialUser);
// // 准备参数
// Long userId = dbSocialUser.getUserId();
// Integer type = dbSocialUser.getType();
// AuthUser authUser = randomPojo(AuthUser.class);
// // mock 方法
//
// // 调用
// socialService.bindSocialUser(userId, UserTypeEnum.ADMIN.getValue(), type, authUser);
// // 断言
// List<SocialUserDO> socialUsers = socialUserMapper.selectList("user_id", userId);
// assertEquals(1, socialUsers.size());
// assertBindSocialUser(socialUsers.get(0), authUser, userId, type);
// }
//
// /**
// * 情况一和二都存在的逻辑二的场景
// */
// @Test
// public void testBindSocialUser_userId() {
// // mock 数据
// SocialUserDO dbSocialUser = randomPojo(SocialUserDO.class, socialUserDO -> {
// socialUserDO.setUserType(UserTypeEnum.ADMIN.getValue());
// socialUserDO.setType(randomEle(SocialTypeEnum.values()).getType());
// });
// socialUserMapper.insert(dbSocialUser);
// // 准备参数
// Long userId = randomLongId();
// Integer type = dbSocialUser.getType();
// AuthUser authUser = randomPojo(AuthUser.class);
// // mock 方法
//
// // 调用
// socialService.bindSocialUser(userId, UserTypeEnum.ADMIN.getValue(), type, authUser);
// // 断言
// List<SocialUserDO> socialUsers = socialUserMapper.selectList("user_id", userId);
// assertEquals(1, socialUsers.size());
// }
//
// /**
// * 情况一如果新老的 unionId 是一致的无需解绑
// */
// @Test
// public void testUnbindOldSocialUser_no() {
// // mock 数据
// SocialUserDO oldSocialUser = randomPojo(SocialUserDO.class, socialUserDO -> {
// socialUserDO.setUserType(UserTypeEnum.ADMIN.getValue());
// socialUserDO.setType(randomEle(SocialTypeEnum.values()).getType());
// });
// socialUserMapper.insert(oldSocialUser);
// // 准备参数
// Long userId = oldSocialUser.getUserId();
// Integer type = oldSocialUser.getType();
// String newUnionId = oldSocialUser.getUnionId();
//
// // 调用
// socialService.unbindOldSocialUser(userId, UserTypeEnum.ADMIN.getValue(), type, newUnionId);
// // 断言
// assertEquals(1L, socialUserMapper.selectCount(null).longValue());
// }
//
//
// /**
// * 情况二如果新老的 unionId 不一致的需解绑
// */
// @Test
// public void testUnbindOldSocialUser_yes() {
// // mock 数据
// SocialUserDO oldSocialUser = randomPojo(SocialUserDO.class, socialUserDO -> {
// socialUserDO.setUserType(UserTypeEnum.ADMIN.getValue());
// socialUserDO.setType(randomEle(SocialTypeEnum.values()).getType());
// });
// socialUserMapper.insert(oldSocialUser);
// // 准备参数
// Long userId = oldSocialUser.getUserId();
// Integer type = oldSocialUser.getType();
// String newUnionId = randomString(10);
//
// // 调用
// socialService.unbindOldSocialUser(userId, UserTypeEnum.ADMIN.getValue(), type, newUnionId);
// // 断言
// assertEquals(0L, socialUserMapper.selectCount(null).longValue());
// }
}
@Test
public void testUnbindSocialUser_success() {
// 准备参数
Long userId = 1L;
Integer userType = UserTypeEnum.ADMIN.getValue();
Integer type = SocialTypeEnum.GITEE.getType();
String openid = "test_openid";
// mock 数据社交用户
SocialUserDO socialUser = randomPojo(SocialUserDO.class).setType(type).setOpenid(openid);
socialUserMapper.insert(socialUser);
// mock 数据社交绑定关系
SocialUserBindDO socialUserBind = randomPojo(SocialUserBindDO.class).setUserType(userType)
.setUserId(userId).setSocialType(type);
socialUserBindMapper.insert(socialUserBind);
// 调用
socialUserService.unbindSocialUser(userId, userType, type, openid);
// 断言
assertEquals(0, socialUserBindMapper.selectCount(null).intValue());
}
@Test
public void testUnbindSocialUser_notFound() {
// 调用并断言
assertServiceException(
() -> socialUserService.unbindSocialUser(randomLong(), UserTypeEnum.ADMIN.getValue(),
SocialTypeEnum.GITEE.getType(), "test_openid"),
SOCIAL_USER_NOT_FOUND);
}
@Test
public void testGetBindUserId() {
// 准备参数
Integer userType = UserTypeEnum.ADMIN.getValue();
Integer type = SocialTypeEnum.GITEE.getType();
String code = "tudou";
String state = "yuanma";
// mock 社交用户
SocialUserDO socialUser = randomPojo(SocialUserDO.class).setType(type).setCode(code).setState(state);
socialUserMapper.insert(socialUser);
// mock 社交用户的绑定
Long userId = randomLong();
SocialUserBindDO socialUserBind = randomPojo(SocialUserBindDO.class).setUserType(userType).setUserId(userId)
.setSocialType(type).setSocialUserId(socialUser.getId());
socialUserBindMapper.insert(socialUserBind);
// 调用
Long result = socialUserService.getBindUserId(userType, type, code, state);
// 断言
assertEquals(userId, result);
}
}

View File

@ -381,7 +381,6 @@ CREATE TABLE IF NOT EXISTS "system_social_user" (
"type" tinyint NOT NULL,
"openid" varchar(64) NOT NULL,
"token" varchar(256) DEFAULT NULL,
"union_id" varchar(64) NOT NULL,
"raw_token_info" varchar(1024) NOT NULL,
"nickname" varchar(32) NOT NULL,
"avatar" varchar(255) DEFAULT NULL,
@ -399,9 +398,9 @@ CREATE TABLE IF NOT EXISTS "system_social_user" (
CREATE TABLE IF NOT EXISTS "system_social_user_bind" (
"id" number NOT NULL GENERATED BY DEFAULT AS IDENTITY,
"user_id" bigint NOT NULL,
"user_type" tinyint NOT NULL DEFAULT '0',
"platform" tinyint NOT NULL,
"union_id" varchar(64) NOT NULL,
"user_type" tinyint NOT NULL,
"social_type" tinyint NOT NULL,
"social_user_id" number NOT NULL,
"creator" varchar(64) DEFAULT '',
"create_time" timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updater" varchar(64) DEFAULT '',