Member:社交登录逻辑调整,如果登录时无用户,则自动创建用户,保持和各 App 统一逻辑

This commit is contained in:
YunaiV 2023-12-23 09:59:58 +08:00
parent 106c1ecf4c
commit d65c28d7f7
16 changed files with 80 additions and 38 deletions

View File

@ -15,6 +15,7 @@ import java.util.Arrays;
@Getter @Getter
public enum TerminalEnum implements IntArrayValuable { public enum TerminalEnum implements IntArrayValuable {
UNKNOWN(0, "未知"), // 目的在无法解析到 terminal 使用它
WECHAT_MINI_PROGRAM(10, "微信小程序"), WECHAT_MINI_PROGRAM(10, "微信小程序"),
WECHAT_WAP(11, "微信公众号"), WECHAT_WAP(11, "微信公众号"),
H5(20, "H5 网页"), H5(20, "H5 网页"),

View File

@ -88,8 +88,6 @@ public class ServletUtils {
return JakartaServletUtil.getClientIP(request); return JakartaServletUtil.getClientIP(request);
} }
// TODO @疯狂terminal 还是从 ServletUtils 里拿更容易全局治理
public static boolean isJsonRequest(ServletRequest request) { public static boolean isJsonRequest(ServletRequest request) {
return StrUtil.startWithIgnoreCase(request.getContentType(), MediaType.APPLICATION_JSON_VALUE); return StrUtil.startWithIgnoreCase(request.getContentType(), MediaType.APPLICATION_JSON_VALUE);
} }

View File

@ -1,8 +1,11 @@
package cn.iocoder.yudao.framework.web.core.util; package cn.iocoder.yudao.framework.web.core.util;
import cn.hutool.core.util.NumberUtil; import cn.hutool.core.util.NumberUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.iocoder.yudao.framework.common.enums.TerminalEnum;
import cn.iocoder.yudao.framework.common.enums.UserTypeEnum; import cn.iocoder.yudao.framework.common.enums.UserTypeEnum;
import cn.iocoder.yudao.framework.common.pojo.CommonResult; import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.servlet.ServletUtils;
import cn.iocoder.yudao.framework.web.config.WebProperties; import cn.iocoder.yudao.framework.web.config.WebProperties;
import org.springframework.web.context.request.RequestAttributes; import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.RequestContextHolder;
@ -25,6 +28,13 @@ public class WebFrameworkUtils {
public static final String HEADER_TENANT_ID = "tenant-id"; public static final String HEADER_TENANT_ID = "tenant-id";
/**
* 终端的 Header
*
* @see cn.iocoder.yudao.framework.common.enums.TerminalEnum
*/
public static final String HEADER_TERMINAL = "terminal";
private static WebProperties properties; private static WebProperties properties;
public WebFrameworkUtils(WebProperties webProperties) { public WebFrameworkUtils(WebProperties webProperties) {
@ -107,6 +117,15 @@ public class WebFrameworkUtils {
return getLoginUserId(request); return getLoginUserId(request);
} }
public static Integer getTerminal() {
HttpServletRequest request = getRequest();
if (request == null) {
return TerminalEnum.UNKNOWN.getTerminal();
}
String terminalValue = request.getHeader(HEADER_TERMINAL);
return NumberUtil.parseInt(terminalValue, TerminalEnum.UNKNOWN.getTerminal());
}
public static void setCommonResult(ServletRequest request, CommonResult<?> result) { public static void setCommonResult(ServletRequest request, CommonResult<?> result) {
request.setAttribute(REQUEST_ATTRIBUTE_COMMON_RESULT, result); request.setAttribute(REQUEST_ATTRIBUTE_COMMON_RESULT, result);
} }

View File

@ -61,9 +61,8 @@ public class AppTradeOrderController {
@PostMapping("/create") @PostMapping("/create")
@Operation(summary = "创建订单") @Operation(summary = "创建订单")
@PreAuthenticated @PreAuthenticated
public CommonResult<AppTradeOrderCreateRespVO> createOrder(@Valid @RequestBody AppTradeOrderCreateReqVO createReqVO, public CommonResult<AppTradeOrderCreateRespVO> createOrder(@Valid @RequestBody AppTradeOrderCreateReqVO createReqVO) {
@RequestHeader Integer terminal) { TradeOrderDO order = tradeOrderUpdateService.createOrder(getLoginUserId(), createReqVO);
TradeOrderDO order = tradeOrderUpdateService.createOrder(getLoginUserId(), getClientIP(), createReqVO, terminal);
return success(new AppTradeOrderCreateRespVO().setId(order.getId()).setPayOrderId(order.getPayOrderId())); return success(new AppTradeOrderCreateRespVO().setId(order.getId()).setPayOrderId(order.getPayOrderId()));
} }

View File

@ -69,8 +69,7 @@ public interface TradeOrderConvert {
@Mapping(source = "calculateRespBO.price.vipPrice", target = "vipPrice"), @Mapping(source = "calculateRespBO.price.vipPrice", target = "vipPrice"),
@Mapping(source = "calculateRespBO.price.payPrice", target = "payPrice") @Mapping(source = "calculateRespBO.price.payPrice", target = "payPrice")
}) })
TradeOrderDO convert(Long userId, String userIp, AppTradeOrderCreateReqVO createReqVO, TradeOrderDO convert(Long userId, AppTradeOrderCreateReqVO createReqVO, TradePriceCalculateRespBO calculateRespBO);
TradePriceCalculateRespBO calculateRespBO);
TradeOrderRespDTO convert(TradeOrderDO orderDO); TradeOrderRespDTO convert(TradeOrderDO orderDO);

View File

@ -36,12 +36,10 @@ public interface TradeOrderUpdateService {
* 会员创建交易订单 * 会员创建交易订单
* *
* @param userId 登录用户 * @param userId 登录用户
* @param userIp 用户 IP 地址
* @param createReqVO 创建交易订单请求模型 * @param createReqVO 创建交易订单请求模型
* @param terminal 终端 {@link TerminalEnum}
* @return 交易订单的 * @return 交易订单的
*/ */
TradeOrderDO createOrder(Long userId, String userIp, AppTradeOrderCreateReqVO createReqVO, Integer terminal); TradeOrderDO createOrder(Long userId, AppTradeOrderCreateReqVO createReqVO);
/** /**
* 更新交易订单已支付 * 更新交易订单已支付

View File

@ -64,6 +64,8 @@ import java.util.Set;
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.collection.CollectionUtils.*; import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.*;
import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.minusTime; import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.minusTime;
import static cn.iocoder.yudao.framework.common.util.servlet.ServletUtils.getClientIP;
import static cn.iocoder.yudao.framework.web.core.util.WebFrameworkUtils.getTerminal;
import static cn.iocoder.yudao.module.trade.enums.ErrorCodeConstants.*; import static cn.iocoder.yudao.module.trade.enums.ErrorCodeConstants.*;
/** /**
@ -158,11 +160,11 @@ public class TradeOrderUpdateServiceImpl implements TradeOrderUpdateService {
@Override @Override
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
@TradeOrderLog(operateType = TradeOrderOperateTypeEnum.MEMBER_CREATE) @TradeOrderLog(operateType = TradeOrderOperateTypeEnum.MEMBER_CREATE)
public TradeOrderDO createOrder(Long userId, String userIp, AppTradeOrderCreateReqVO createReqVO, Integer terminal) { public TradeOrderDO createOrder(Long userId, AppTradeOrderCreateReqVO createReqVO) {
// 1.1 价格计算 // 1.1 价格计算
TradePriceCalculateRespBO calculateRespBO = calculatePrice(userId, createReqVO); TradePriceCalculateRespBO calculateRespBO = calculatePrice(userId, createReqVO);
// 1.2 构建订单 // 1.2 构建订单
TradeOrderDO order = buildTradeOrder(userId, userIp, createReqVO, calculateRespBO, terminal); TradeOrderDO order = buildTradeOrder(userId, createReqVO, calculateRespBO);
List<TradeOrderItemDO> orderItems = buildTradeOrderItems(order, calculateRespBO); List<TradeOrderItemDO> orderItems = buildTradeOrderItems(order, calculateRespBO);
// 2. 订单创建前的逻辑 // 2. 订单创建前的逻辑
@ -178,15 +180,15 @@ public class TradeOrderUpdateServiceImpl implements TradeOrderUpdateService {
return order; return order;
} }
private TradeOrderDO buildTradeOrder(Long userId, String clientIp, AppTradeOrderCreateReqVO createReqVO, private TradeOrderDO buildTradeOrder(Long userId, AppTradeOrderCreateReqVO createReqVO,
TradePriceCalculateRespBO calculateRespBO, Integer terminal) { TradePriceCalculateRespBO calculateRespBO) {
TradeOrderDO order = TradeOrderConvert.INSTANCE.convert(userId, clientIp, createReqVO, calculateRespBO); TradeOrderDO order = TradeOrderConvert.INSTANCE.convert(userId, createReqVO, calculateRespBO);
order.setType(calculateRespBO.getType()); order.setType(calculateRespBO.getType());
order.setNo(tradeNoRedisDAO.generate(TradeNoRedisDAO.TRADE_ORDER_NO_PREFIX)); order.setNo(tradeNoRedisDAO.generate(TradeNoRedisDAO.TRADE_ORDER_NO_PREFIX));
order.setStatus(TradeOrderStatusEnum.UNPAID.getStatus()); order.setStatus(TradeOrderStatusEnum.UNPAID.getStatus());
order.setRefundStatus(TradeOrderRefundStatusEnum.NONE.getStatus()); order.setRefundStatus(TradeOrderRefundStatusEnum.NONE.getStatus());
order.setProductCount(getSumValue(calculateRespBO.getItems(), TradePriceCalculateRespBO.OrderItem::getCount, Integer::sum)); order.setProductCount(getSumValue(calculateRespBO.getItems(), TradePriceCalculateRespBO.OrderItem::getCount, Integer::sum));
order.setTerminal(terminal); order.setUserIp(getClientIP()).setTerminal(getTerminal());
// 支付 + 退款信息 // 支付 + 退款信息
order.setAdjustPrice(0).setPayStatus(false); order.setAdjustPrice(0).setPayStatus(false);
order.setRefundStatus(TradeOrderRefundStatusEnum.NONE.getStatus()).setRefundPrice(0); order.setRefundStatus(TradeOrderRefundStatusEnum.NONE.getStatus()).setRefundPrice(0);

View File

@ -73,9 +73,8 @@ public class AppAuthController {
@PostMapping("/sms-login") @PostMapping("/sms-login")
@Operation(summary = "使用手机 + 验证码登录") @Operation(summary = "使用手机 + 验证码登录")
public CommonResult<AppAuthLoginRespVO> smsLogin(@RequestBody @Valid AppAuthSmsLoginReqVO reqVO, public CommonResult<AppAuthLoginRespVO> smsLogin(@RequestBody @Valid AppAuthSmsLoginReqVO reqVO) {
@RequestHeader Integer terminal) { return success(authService.smsLogin(reqVO));
return success(authService.smsLogin(reqVO, terminal));
} }
@PostMapping("/send-sms-code") @PostMapping("/send-sms-code")

View File

@ -1,6 +1,5 @@
package cn.iocoder.yudao.module.member.service.auth; package cn.iocoder.yudao.module.member.service.auth;
import cn.iocoder.yudao.framework.common.enums.TerminalEnum;
import cn.iocoder.yudao.module.member.controller.app.auth.vo.*; import cn.iocoder.yudao.module.member.controller.app.auth.vo.*;
import jakarta.validation.Valid; import jakarta.validation.Valid;
@ -33,10 +32,9 @@ public interface MemberAuthService {
* 手机 + 验证码登陆 * 手机 + 验证码登陆
* *
* @param reqVO 登陆信息 * @param reqVO 登陆信息
* @param terminal 终端 {@link TerminalEnum}
* @return 登录结果 * @return 登录结果
*/ */
AppAuthLoginRespVO smsLogin(@Valid AppAuthSmsLoginReqVO reqVO, Integer terminal); AppAuthLoginRespVO smsLogin(@Valid AppAuthSmsLoginReqVO reqVO);
/** /**
* 社交登录使用 code 授权码 * 社交登录使用 code 授权码

View File

@ -36,6 +36,7 @@ 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.servlet.ServletUtils.getClientIP; import static cn.iocoder.yudao.framework.common.util.servlet.ServletUtils.getClientIP;
import static cn.iocoder.yudao.framework.web.core.util.WebFrameworkUtils.getTerminal;
import static cn.iocoder.yudao.module.member.enums.ErrorCodeConstants.*; import static cn.iocoder.yudao.module.member.enums.ErrorCodeConstants.*;
/** /**
@ -78,13 +79,13 @@ public class MemberAuthServiceImpl implements MemberAuthService {
@Override @Override
@Transactional @Transactional
public AppAuthLoginRespVO smsLogin(AppAuthSmsLoginReqVO reqVO, Integer terminal) { public AppAuthLoginRespVO smsLogin(AppAuthSmsLoginReqVO reqVO) {
// 校验验证码 // 校验验证码
String userIp = getClientIP(); String userIp = getClientIP();
smsCodeApi.useSmsCode(AuthConvert.INSTANCE.convert(reqVO, SmsSceneEnum.MEMBER_LOGIN.getScene(), userIp)); smsCodeApi.useSmsCode(AuthConvert.INSTANCE.convert(reqVO, SmsSceneEnum.MEMBER_LOGIN.getScene(), userIp));
// 获得获得注册用户 // 获得获得注册用户
MemberUserDO user = userService.createUserIfAbsent(reqVO.getMobile(), userIp, terminal); MemberUserDO user = userService.createUserIfAbsent(reqVO.getMobile(), userIp, getTerminal());
Assert.notNull(user, "获取用户失败,结果为空"); Assert.notNull(user, "获取用户失败,结果为空");
// 如果 socialType 非空说明需要绑定社交用户 // 如果 socialType 非空说明需要绑定社交用户
@ -107,10 +108,13 @@ public class MemberAuthServiceImpl implements MemberAuthService {
throw exception(AUTH_THIRD_LOGIN_NOT_BIND); throw exception(AUTH_THIRD_LOGIN_NOT_BIND);
} }
// 自动登录 // 情况一已绑定自动登录
MemberUserDO user = userService.getUser(socialUser.getUserId()); MemberUserDO user = userService.getUser(socialUser.getUserId());
if (user == null) { if (user == null) {
throw exception(USER_NOT_EXISTS); throw exception(USER_NOT_EXISTS);
// 情况二未绑定注册登录
} else {
user = userService.createUser(user.getNickname(), user.getAvatar(), getClientIP(), getTerminal());
} }
// 创建 Token 令牌记录登录日志 // 创建 Token 令牌记录登录日志

View File

@ -49,6 +49,18 @@ public interface MemberUserService {
*/ */
MemberUserDO createUserIfAbsent(@Mobile String mobile, String registerIp, Integer terminal); MemberUserDO createUserIfAbsent(@Mobile String mobile, String registerIp, Integer terminal);
/**
* 创建用户
* 目的三方登录时如果未绑定用户时自动创建对应用户
*
* @param nickname 昵称
* @param avtar 头像
* @param registerIp 注册 IP
* @param terminal 终端 {@link TerminalEnum}
* @return 用户对象
*/
MemberUserDO createUser(String nickname, String avtar, String registerIp, Integer terminal);
/** /**
* 更新用户的最后登陆信息 * 更新用户的最后登陆信息
* *

View File

@ -81,10 +81,17 @@ public class MemberUserServiceImpl implements MemberUserService {
return user; return user;
} }
// 用户不存在则进行创建 // 用户不存在则进行创建
return createUser(mobile, registerIp, terminal); return createUser(mobile, null, null, registerIp, terminal);
} }
private MemberUserDO createUser(String mobile, String registerIp, Integer terminal) { @Override
@Transactional(rollbackFor = Exception.class)
public MemberUserDO createUser(String nickname, String avtar, String registerIp, Integer terminal) {
return createUser(null, nickname, avtar, registerIp, terminal);
}
private MemberUserDO createUser(String mobile, String nickname, String avtar,
String registerIp, Integer terminal) {
// 生成密码 // 生成密码
String password = IdUtil.fastSimpleUUID(); String password = IdUtil.fastSimpleUUID();
// 插入用户 // 插入用户
@ -92,8 +99,8 @@ public class MemberUserServiceImpl implements MemberUserService {
user.setMobile(mobile); user.setMobile(mobile);
user.setStatus(CommonStatusEnum.ENABLE.getStatus()); // 默认开启 user.setStatus(CommonStatusEnum.ENABLE.getStatus()); // 默认开启
user.setPassword(encodePassword(password)); // 加密密码 user.setPassword(encodePassword(password)); // 加密密码
user.setRegisterIp(registerIp); user.setRegisterIp(registerIp).setRegisterTerminal(terminal);
user.setRegisterTerminal(terminal); user.setNickname(nickname).setAvatar(avtar); // 基础信息
memberUserMapper.insert(user); memberUserMapper.insert(user);
// 发送 MQ 消息用户创建 // 发送 MQ 消息用户创建

View File

@ -36,9 +36,9 @@ public class LoginLogCreateReqDTO {
private Integer userType; private Integer userType;
/** /**
* 用户账号 * 用户账号
*
* 不再强制校验 username 非空因为 Member 社交登录时此时暂时没有 username(mobile
*/ */
@NotBlank(message = "用户账号不能为空")
@Size(max = 30, message = "用户账号长度不能超过30个字符")
private String username; private String username;
/** /**

View File

@ -15,9 +15,17 @@ import lombok.NoArgsConstructor;
public class SocialUserRespDTO { public class SocialUserRespDTO {
/** /**
* 社交用户 openid * 社交用户 openid
*/ */
private String openid; private String openid;
/**
* 社交用户的昵称
*/
private String nickname;
/**
* 社交用户的头像
*/
private String avatar;
/** /**
* 关联的用户编号 * 关联的用户编号

View File

@ -158,7 +158,7 @@ public class AdminAuthServiceImpl implements AdminAuthService {
// 使用 code 授权码进行登录然后获得到绑定的用户编号 // 使用 code 授权码进行登录然后获得到绑定的用户编号
SocialUserRespDTO socialUser = socialUserService.getSocialUser(UserTypeEnum.ADMIN.getValue(), reqVO.getType(), SocialUserRespDTO socialUser = socialUserService.getSocialUser(UserTypeEnum.ADMIN.getValue(), reqVO.getType(),
reqVO.getCode(), reqVO.getState()); reqVO.getCode(), reqVO.getState());
if (socialUser == null) { if (socialUser == null || socialUser.getUserId() == null) {
throw exception(AUTH_THIRD_LOGIN_NOT_BIND); throw exception(AUTH_THIRD_LOGIN_NOT_BIND);
} }

View File

@ -99,13 +99,11 @@ public class SocialUserServiceImpl implements SocialUserService {
SocialUserDO socialUser = authSocialUser(socialType, userType, code, state); SocialUserDO socialUser = authSocialUser(socialType, userType, code, state);
Assert.notNull(socialUser, "社交用户不能为空"); Assert.notNull(socialUser, "社交用户不能为空");
// 如果未绑定的社交用户则无法自动登录进行报错 // 获得绑定用户
SocialUserBindDO socialUserBind = socialUserBindMapper.selectByUserTypeAndSocialUserId(userType, SocialUserBindDO socialUserBind = socialUserBindMapper.selectByUserTypeAndSocialUserId(userType,
socialUser.getId()); socialUser.getId());
if (socialUserBind == null) { return new SocialUserRespDTO(socialUser.getOpenid(), socialUser.getNickname(), socialUser.getAvatar(),
throw exception(AUTH_THIRD_LOGIN_NOT_BIND); socialUserBind != null ? socialUserBind.getUserId() : null);
}
return new SocialUserRespDTO(socialUser.getOpenid(), socialUserBind.getUserId());
} }
/** /**