Commit dbf4835e by levphon

微信小程序C端账号体系

1 parent 83a5ac51
......@@ -35,7 +35,7 @@
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>wx-java-miniapp-spring-boot-starter</artifactId>
<version>4.2.7.B</version>
<version>4.3.5.B</version>
</dependency>
<dependency>
......
package cn.com.glsx.app.modules;
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.com.glsx.app.modules.model.AppUser;
import cn.com.glsx.app.modules.model.LoginByAccountBO;
import cn.com.glsx.app.modules.service.LoginService;
......@@ -8,6 +9,7 @@ import com.glsx.plat.core.web.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
......@@ -34,6 +36,9 @@ public class LocalLoginController {
@Autowired
private LoginService loginService;
@Autowired
private WxMaService wxMaService;
@GetMapping(value = "/")
public String index() {
return "success";
......@@ -44,10 +49,12 @@ public class LocalLoginController {
*/
@ApiOperation(value = "登录系统")
@PostMapping(value = "/login")
public R login(@RequestBody @Validated LoginByAccountBO loginBO) {
public R login(@RequestBody @Validated LoginByAccountBO loginBO) throws WxErrorException {
//本地登录授权
AppUser user = loginService.localAuth(loginBO);
//关联微信账号
loginService.linkWxAuth(loginBO.getCodeForWx(), user);
//创建授权令牌
String token = userService.createToken(user);
Map<String, Object> rtnMap = new HashMap<>();
......
......@@ -4,9 +4,9 @@ import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.com.glsx.app.common.enums.LoginType;
import cn.com.glsx.app.common.enums.MiniUserType;
import cn.com.glsx.app.common.exception.AppServerException;
import cn.com.glsx.app.modules.entity.UserAuthRel;
import cn.com.glsx.app.modules.model.AppUser;
import cn.com.glsx.app.modules.model.QQOAuth2AccessToken;
import cn.com.glsx.app.modules.service.LoginService;
import cn.com.glsx.app.modules.service.UserService;
import cn.hutool.json.JSONUtil;
......@@ -46,29 +46,11 @@ public class ThirdLoginController {
private WxMaService wxMaService;
@NoLogin
@ApiOperation(value = "QQ授权登录")
@GetMapping(value = "/qqAuth")
public R qqAuth(@RequestParam String code) {
//获取openId、unionId等
QQOAuth2AccessToken accessToken = new QQOAuth2AccessToken();
log.info("QQ code[{}]获取的Session信息为{}", code, JSONUtil.toJsonStr(accessToken));
UserAuthRel authRel = loginService.qqAuth(accessToken);
Map<String, Object> rtnMap = thirdLogin(LoginType.QQ, 0, authRel);
return R.ok().data(rtnMap);
}
@NoLogin
@ApiOperation(value = "微信授权登录")
@GetMapping(value = "/wechatAuth")
public R wechatAuth(@RequestParam String code, @RequestParam Integer accessMode) throws WxErrorException {
//获取openId、unionid、session_key
WxMaJscode2SessionResult sessionInfo = null;//wxMaService.getUserService().getSessionInfo(code);
sessionInfo = new WxMaJscode2SessionResult();
sessionInfo.setOpenid("ocDtn5a60SvMC33CbObTUUMVGOwE");
WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(code);
log.info("微信code[{}]获取的Session信息为{}", code, JSONUtil.toJsonStr(sessionInfo));
UserAuthRel authRel = loginService.wechatAuth(sessionInfo, accessMode);
......@@ -89,32 +71,31 @@ public class ThirdLoginController {
private Map<String, Object> thirdLogin(LoginType loginType, Integer accessMode, UserAuthRel authRel) {
Map<String, Object> rtnMap = new HashMap<>();
Optional<Long> optUserId = Optional.ofNullable(authRel.getUserId());
if (!optUserId.isPresent() || optUserId.get() == 0L) {
throw new AppServerException("登录失败,请联系管理员");
}
//分两种情况:
if (MiniUserType.NORMAL.getFlag().equals(accessMode)) {
//1、常规免登录(通过小程序正常入口)
Optional<Long> optUserId = Optional.ofNullable(authRel.getUserId());
if (optUserId.isPresent()) {
//已绑定本地账号
AppUser user = userService.getAppUserByUserId(authRel.getUserId());
String token = userService.createToken(user);
rtnMap.put("user", user);
rtnMap.put("token", token);
} else {
//未绑定本地账号,跳转登录界面登录,回传此id
rtnMap.put("authRelId", authRel.getId());
}
//已绑定本地账号返回引用账号
AppUser user = userService.getRelUserByUserId(authRel.getUserId());
String token = userService.createToken(user);
rtnMap.put("user", user);
rtnMap.put("token", token);
} else if (MiniUserType.SHARED.getFlag().equals(accessMode)) {
//2、通过分享车辆地址登录,也分两种情况
//a、存在账号的openid发起免登录
//b、不存在账号的openid发起免登录
AppUser user = userService.getAppUserByAuthId(loginType, authRel.getAuthId());
AppUser user = userService.getLocalUserByUserId(authRel.getUserId());
user.setUserType(MiniUserType.SHARED.getType());
String token = userService.createToken(user);
rtnMap.put("user", user);
rtnMap.put("token", token);
} else {
// TODO: 2022/6/29 抛出异常
throw new AppServerException("登录方式参数有误");
}
return rtnMap;
}
......
package cn.com.glsx.app.modules.entity;
import com.glsx.plat.mybatis.base.BaseEntity;
import lombok.Data;
import javax.persistence.Column;
import javax.persistence.Table;
@Data
@Table(name = "t_cust_user_qq_account")
public class UserQQAccount extends BaseEntity {
/**
* 认证id
*/
@Column(name = "auth_id")
private Long authId;
/**
* 平台id
*/
@Column(name = "union_id")
private String unionId;
/**
* QQ头像
*/
@Column(name = "qq_avatar")
private String avatar;
/**
* QQ名
*/
@Column(name = "qq_name")
private String qqName;
}
\ No newline at end of file
package cn.com.glsx.app.modules.mapper;
import cn.com.glsx.app.modules.entity.UserAuthRel;
import cn.com.glsx.app.modules.entity.UserThirdAuth;
import com.glsx.plat.mybatis.mapper.CommonBaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
......@@ -12,6 +13,8 @@ public interface UserAuthRelMapper extends CommonBaseMapper<UserAuthRel> {
UserAuthRel selectByAuthTypeAndAuthId(@Param("authType") String authType, @Param("authId") Long authId);
List<UserAuthRel> selectByAuthTypeAndUserId(@Param("authType") String authType, @Param("userId") Long userId);
}
\ No newline at end of file
......@@ -12,6 +12,8 @@ public interface UserLocalAccountMapper extends CommonBaseMapper<UserLocalAccoun
UserLocalAccount selectByAuthId(@Param("authId") Long authId);
AppUser selectAppUserByUserId(@Param("userId") Long userId);
AppUser selectLocalUserByUserId(@Param("userId") Long userId);
AppUser selectRelUserByUserId(@Param("userId") Long userId);
}
\ No newline at end of file
package cn.com.glsx.app.modules.mapper;
import cn.com.glsx.app.modules.entity.UserQQAccount;
import com.glsx.plat.mybatis.mapper.CommonBaseMapper;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface UserQQAccountMapper extends CommonBaseMapper<UserQQAccount> {
UserQQAccount selectByAuthId(Long authId);
}
\ No newline at end of file
......@@ -12,4 +12,6 @@ public interface UserThirdAuthMapper extends CommonBaseMapper<UserThirdAuth> {
UserThirdAuth selectByLoginTypeAndAuthId(@Param("loginType") String loginType, @Param("authId") Long authId);
UserThirdAuth selectByLoginTypeAndUserId(@Param("loginType") String loginType, @Param("userId") Long userId);
}
\ No newline at end of file
......@@ -10,9 +10,11 @@ public class AppUser {
* 看具体用户类型(userType):normal用户id(对应后台t_user表id),C端被分享用户用户id(对应后台t_cust_user表id)
*/
private Long userId;
private Long cuserId;
private String account;
private String username;
private String avatar;
/**
* 用户类型:normal常规用户,shared被分享用户,见枚举MiniUserType
*/
......
package cn.com.glsx.app.modules.service;
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.com.glsx.app.common.enums.AuthType;
import cn.com.glsx.app.common.enums.LoginType;
......@@ -10,13 +11,13 @@ import cn.com.glsx.app.modules.entity.*;
import cn.com.glsx.app.modules.mapper.*;
import cn.com.glsx.app.modules.model.AppUser;
import cn.com.glsx.app.modules.model.LoginByAccountBO;
import cn.com.glsx.app.modules.model.QQOAuth2AccessToken;
import cn.com.glsx.auth.api.AuthFeignClient;
import cn.com.glsx.auth.model.SimpleUser;
import com.glsx.plat.common.utils.StringUtils;
import com.glsx.plat.core.enums.SysConstants;
import com.glsx.plat.core.web.R;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
......@@ -48,7 +49,7 @@ public class LoginService {
private UserWechatAccountMapper wechatAccountMapper;
@Resource
private UserQQAccountMapper qqAccountMapper;
private WxMaService wxMaService;
@Autowired
private AuthFeignClient authFeignClient;
......@@ -69,12 +70,16 @@ public class LoginService {
User user = register(simpleUser);
//返给前端的用户信息
return UserConverter.INSTANCE.su2au(simpleUser);
} else if (loginBO.getLoginType() == 2) {
//验证码校验
//smsService.verifyCode(loginBO.getAccount(), loginBO.getCode());
AppUser appUser = UserConverter.INSTANCE.su2au(simpleUser);
appUser.setCuserId(user.getId());
appUser.setUserType(MiniUserType.NORMAL.getType());
return appUser;
}
return null;
// else if (loginBO.getLoginType() == 2) {
// //验证码校验
// smsService.verifyCode(loginBO.getAccount(), loginBO.getCode());
// }
throw new AppServerException("登录失败");
}
/**
......@@ -126,42 +131,70 @@ public class LoginService {
userAuthRel.setUserId(user.getId());
userAuthRel.setAuthId(localAuth.getId());
userAuthRel.setAuthType(AuthType.LOCAL.getType());
userAuthRel.setCreatedDate(new Date());
userAuthRelMapper.insertUseGeneratedKeys(userAuthRel);
return user;
} else {
user = userMapper.selectById(userAuthRel.getUserId());
if (user == null) {
// TODO: 2022/6/30 抛出异常
throw new AppServerException("登录失败,请联系管理员");
}
}
return user;
}
public void linkWxAuth(String code, AppUser user) throws WxErrorException {
UserThirdAuth userThirdAuth = userThirdAuthMapper.selectByLoginTypeAndUserId(LoginType.WECHAT.getType(), user.getCuserId());
WxMaJscode2SessionResult sessionResult = wxMaService.getUserService().getSessionInfo(code);
if (sessionResult != null) {
if (userThirdAuth == null) {
//关联c端用户openid
wechatAuth(sessionResult, user.getCuserId());
} else {
log.info("用户{}已关联微信,Openid为{},新Openid为{}", user.getAccount(), userThirdAuth.getOpenid(), sessionResult.getOpenid());
//更新用户openid
if (!sessionResult.getOpenid().equals(userThirdAuth.getOpenid())) {
userThirdAuth.setOpenid(sessionResult.getOpenid());
userThirdAuth.setUpdatedDate(new Date());
userThirdAuthMapper.updateByPrimaryKeySelective(userThirdAuth);
}
//todo 当c端账号先存在,常规账号后存在时,需要更新账号信息(比如:当某个用户通过被分享车辆链接登录产生了c端账号(账号信息是随机的),后来平台给开了常规账号,这种情况两种账号可以通过openid联系起来)
UserLocalAuth userLocalAuth = userLocalAuthMapper.selectByUserId(user.getUserId());
UserLocalAccount userLocalAccount = userLocalAccountMapper.selectByAuthId(userLocalAuth.getId());
}
}
}
@Transactional(rollbackFor = Exception.class)
public UserAuthRel qqAuth(QQOAuth2AccessToken accessToken) {
UserThirdAuth thirdAuth = userThirdAuthMapper.selectByOpenid(accessToken.getOpenId());
public UserAuthRel wechatAuth(WxMaJscode2SessionResult sessionInfo, Long userId) {
UserThirdAuth thirdAuth = userThirdAuthMapper.selectByOpenid(sessionInfo.getOpenid());
if (thirdAuth == null) {
thirdAuth = new UserThirdAuth();
thirdAuth.setOpenid(accessToken.getOpenId());
thirdAuth.setAccessToken(accessToken.getAccessToken());
thirdAuth.setLoginType(LoginType.QQ.getType());
thirdAuth.setOpenid(sessionInfo.getOpenid());
thirdAuth.setAccessToken(sessionInfo.getSessionKey());
thirdAuth.setLoginType(LoginType.WECHAT.getType());
userThirdAuthMapper.insertUseGeneratedKeys(thirdAuth);
}
UserAuthRel authRel = userAuthRelMapper.selectByAuthTypeAndAuthId(AuthType.THIRD.getType(), thirdAuth.getId());
if (authRel == null) {
authRel = new UserAuthRel();
authRel.setUserId(userId);
authRel.setAuthId(thirdAuth.getId());
authRel.setAuthType(AuthType.THIRD.getType());
userAuthRelMapper.insertUseGeneratedKeys(authRel);
}
UserQQAccount qqAccount = qqAccountMapper.selectByAuthId(thirdAuth.getId());
if (qqAccount == null) {
qqAccount = new UserQQAccount();
qqAccount.setAuthId(thirdAuth.getId());
qqAccount.setUnionId(accessToken.getUnionId());
qqAccountMapper.insertUseGeneratedKeys(qqAccount);
UserWechatAccount wechatAccount = wechatAccountMapper.selectByAuthId(thirdAuth.getId());
if (wechatAccount == null) {
wechatAccount = new UserWechatAccount();
wechatAccount.setAuthId(thirdAuth.getId());
wechatAccount.setUnionId(sessionInfo.getUnionid());
wechatAccountMapper.insertUseGeneratedKeys(wechatAccount);
}
return authRel;
}
......@@ -177,21 +210,20 @@ public class LoginService {
userThirdAuthMapper.insertUseGeneratedKeys(thirdAuth);
}
User user = null;
if (MiniUserType.SHARED.getFlag().equals(accessMode)) {
SimpleUser simpleUser = new SimpleUser();
// simpleUser.setId();
// simpleUser.setAccount();
// simpleUser.setUsername();
simpleUser.setBlacklist(SysConstants.EnableStatus.enable.getCode());
user = register(simpleUser);
}
UserAuthRel authRel = userAuthRelMapper.selectByAuthTypeAndAuthId(AuthType.THIRD.getType(), thirdAuth.getId());
if (authRel == null) {
User user = null;
//如果是分享链接登录,没有存在C端账号,则新建C端账号
if (MiniUserType.SHARED.getFlag().equals(accessMode)) {
SimpleUser simpleUser = new SimpleUser();
simpleUser.setAccount(thirdAuth.getLoginType() + "_user" + thirdAuth.getId());
simpleUser.setUsername(thirdAuth.getLoginType() + "_user");
simpleUser.setBlacklist(SysConstants.EnableStatus.enable.getCode());
user = register(simpleUser);
}
authRel = new UserAuthRel();
authRel.setUserId(user != null ? user.getId() : null);
authRel.setUserId(user != null ? user.getId() : 0L);
authRel.setAuthId(thirdAuth.getId());
authRel.setAuthType(AuthType.THIRD.getType());
userAuthRelMapper.insertUseGeneratedKeys(authRel);
......
package cn.com.glsx.app.modules.service;
import cn.com.glsx.app.common.enums.AuthType;
import cn.com.glsx.app.common.enums.LoginType;
import cn.com.glsx.app.modules.entity.UserAuthRel;
import cn.com.glsx.app.modules.entity.UserThirdAuth;
import cn.com.glsx.app.modules.mapper.UserAuthRelMapper;
import cn.com.glsx.app.modules.mapper.UserLocalAccountMapper;
import cn.com.glsx.app.modules.mapper.UserThirdAuthMapper;
......@@ -54,18 +50,14 @@ public class UserService {
return jwtUtils.createToken(userMap);
}
public AppUser getAppUserByUserId(Long userId) {
//获取用户本地信息
return userLocalAccountMapper.selectAppUserByUserId(userId);
public AppUser getLocalUserByUserId(Long userId) {
//获取C端用户信息
return userLocalAccountMapper.selectLocalUserByUserId(userId);
}
public AppUser getAppUserByAuthId(LoginType loginType, Long authId) {
//获取具体第三方授权
UserThirdAuth thirdAuth = userThirdAuthMapper.selectByLoginTypeAndAuthId(loginType.getType(), authId);
//获取第三方授权关联
UserAuthRel userAuthRel = userAuthRelMapper.selectByAuthTypeAndAuthId(AuthType.THIRD.getType(), thirdAuth.getId());
//获取用户本地信息
return this.getAppUserByUserId(userAuthRel.getUserId());
public AppUser getRelUserByUserId(Long userId) {
//获取后台用户信息
return userLocalAccountMapper.selectRelUserByUserId(userId);
}
}
......@@ -32,7 +32,22 @@
and del_flag = 0
</select>
<select id="selectAppUserByUserId" resultType="cn.com.glsx.app.modules.model.AppUser">
<select id="selectLocalUserByUserId" resultType="cn.com.glsx.app.modules.model.AppUser">
select tcu.id as userId,
tcu.id as cuserId,
tcula.account,
tcula2.username,
tcu.blacklist
from t_cust_user_local_auth tcula
inner join t_cust_user_auth_rel tcuar on tcula.id = tcuar.auth_id
left join t_cust_user_local_account tcula2 on tcuar.auth_id = tcula2.auth_id
left join t_cust_user tcu on tcuar.user_id = tcu.id
where tcula.del_flag = 0
and tcuar.auth_type = 'local'
and tcuar.user_id = #{userId} limit 1
</select>
<select id="selectRelUserByUserId" resultType="cn.com.glsx.app.modules.model.AppUser">
select tcu.rel_user_id as userId,
tcu.id as cuserId,
tcula.account,
......
......@@ -35,7 +35,7 @@
<insert id="saveOrUpdate" useGeneratedKeys="true" keyProperty="id" parameterType="cn.com.glsx.app.modules.entity.User">
INSERT INTO t_cust_user (id, rel_user_id, blacklist, del_flag, created_date)
VALUES (#{id}, #{linkerId}, #{blacklist}, 0, sysdate()) ON DUPLICATE KEY
VALUES (#{id}, #{relUserId}, #{blacklist}, 0, sysdate()) ON DUPLICATE KEY
UPDATE updated_date = sysdate()
</insert>
</mapper>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.com.glsx.app.modules.mapper.UserQQAccountMapper">
<resultMap id="BaseResultMap" type="cn.com.glsx.app.modules.entity.UserQQAccount">
<!--
WARNING - @mbg.generated
-->
<id column="id" jdbcType="INTEGER" property="id"/>
<result column="auth_id" jdbcType="INTEGER" property="authId"/>
<result column="union_id" jdbcType="VARCHAR" property="unionId"/>
<result column="qq_avatar" jdbcType="VARCHAR" property="avatar"/>
<result column="qq_name" jdbcType="VARCHAR" property="qqName"/>
<result column="del_flag" jdbcType="TINYINT" property="delFlag"/>
<result column="created_date" jdbcType="TIMESTAMP" property="createdDate"/>
<result column="created_by" jdbcType="INTEGER" property="createdBy"/>
<result column="updated_date" jdbcType="TIMESTAMP" property="updatedDate"/>
<result column="updated_by" jdbcType="INTEGER" property="updatedBy"/>
</resultMap>
<sql id="Base_Column_List">
<!--
WARNING - @mbg.generated
-->
id, auth_id, union_id, qq_avatar, qq_name, del_flag, created_date, created_by, updated_date,
updated_by
</sql>
<select id="selectByAuthId" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from t_cust_user_qq_account
where auth_id = #{authId}
and del_flag = 0
</select>
</mapper>
\ No newline at end of file
......@@ -38,6 +38,18 @@
where tcuta.del_flag = 0
and tcuar.auth_type = 'third'
and tcuta.login_type = #{loginType}
and tcuar.auth_id = #{userId};
and tcuar.auth_id = #{authId}
</select>
<select id="selectByLoginTypeAndUserId" resultMap="BaseResultMap">
select tcuta.*
from t_cust_user_third_auth tcuta,
t_cust_user_auth_rel tcuar
where tcuta.del_flag = 0
and tcuta.id = tcuar.auth_id
and tcuar.auth_type = 'third'
and tcuta.login_type = #{loginType}
and tcuar.user_id = #{userId}
order by tcuta.id desc limit 1
</select>
</mapper>
\ No newline at end of file
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!