Parcourir la source

feat(app): 实现微信登录功能

- 新增微信登录接口 /loginByCode
- 实现微信登录逻辑,包括获取 openid、创建用户、生成 token
- 优化现有登录接口,增加参数校验
- 新增 LoginUserVO 类用于登录响应
SheepHy il y a 3 semaines
Parent
commit
de4105b99c

+ 17 - 5
national-motion-module-system/national-motion-system-biz/src/main/java/org/jeecg/modules/app/controller/AppUserController.java

@@ -1,14 +1,13 @@
 package org.jeecg.modules.app.controller;
 
+import io.swagger.v3.oas.annotations.media.Schema;
 import io.swagger.v3.oas.annotations.tags.Tag;
 import lombok.extern.slf4j.Slf4j;
 import org.jeecg.common.api.vo.Result;
 import org.jeecg.modules.app.dto.UserWechatRegisterDTO;
 import org.jeecg.modules.app.service.IUserService;
-import org.springframework.web.bind.annotation.PostMapping;
-import org.springframework.web.bind.annotation.RequestBody;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RestController;
+import org.jeecg.modules.app.vo.LoginUserVO;
+import org.springframework.web.bind.annotation.*;
 
 import javax.annotation.Resource;
 import javax.servlet.http.HttpServletRequest;
@@ -20,6 +19,19 @@ import javax.servlet.http.HttpServletRequest;
 public class AppUserController {
     @Resource
     private IUserService userService;
+
+
+    /**
+     * 登录
+     *
+     * @param code
+     * @return {@link Result}<{@link ?}>
+     */
+    @GetMapping("/loginByCode")
+    public Result<LoginUserVO> wechatLogin(@RequestParam @Schema(description = "微信登录返回的code") String code){
+        return Result.ok(userService.wechatLogin(code));
+    }
+
     /**
      * 微信小程序获取用户信息接口
      *
@@ -28,7 +40,7 @@ public class AppUserController {
      * @return {@link Result}<{@link ?}>
      */
     @PostMapping("/wechatRegister")
-    public Result<?> wechatInfo(@RequestBody UserWechatRegisterDTO userWechatRegisterDTO, HttpServletRequest request){
+    public Result<LoginUserVO> wechatInfo(@RequestBody UserWechatRegisterDTO userWechatRegisterDTO, HttpServletRequest request){
         return Result.ok(userService.wechatInfo(userWechatRegisterDTO, request));
     }
 }

+ 3 - 0
national-motion-module-system/national-motion-system-biz/src/main/java/org/jeecg/modules/app/service/IUserService.java

@@ -8,6 +8,7 @@ import org.jeecg.modules.app.vo.LoginUserVO;
 import javax.servlet.http.HttpServletRequest;
 
 public interface IUserService extends IService<User> {
+
     LoginUserVO wechatInfo(UserWechatRegisterDTO userWechatRegisterDTO, HttpServletRequest request);
 
     /**
@@ -16,4 +17,6 @@ public interface IUserService extends IService<User> {
      * @return
      */
     LoginUserVO getLoginUserVO(User user);
+
+    LoginUserVO wechatLogin(String code);
 }

+ 52 - 21
national-motion-module-system/national-motion-system-biz/src/main/java/org/jeecg/modules/app/service/impl/UserServiceImpl.java

@@ -38,23 +38,21 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IU
     @Override
     public LoginUserVO wechatInfo(UserWechatRegisterDTO userWechatRegisterDTO, HttpServletRequest request) {
         try {
-            if (userWechatRegisterDTO == null) {
-                throw new JeecgBootException("参数不能为空",SC_JEECG_NO_AUTHZ);
+            if (userWechatRegisterDTO == null || 
+                StringUtils.isAnyBlank(userWechatRegisterDTO.getCode(), userWechatRegisterDTO.getUserName(), userWechatRegisterDTO.getUserAvatar(), userWechatRegisterDTO.getGender())) {
+                throw new JeecgBootException("参数不能为空", SC_JEECG_NO_AUTHZ);
             }
             String code = userWechatRegisterDTO.getCode();
             String userName = userWechatRegisterDTO.getUserName();
             String userAvatar = userWechatRegisterDTO.getUserAvatar();
             String gender = userWechatRegisterDTO.getGender();
-            if (StringUtils.isAnyBlank(code, userName, userAvatar,gender)) {
-                throw new JeecgBootException("参数不能为空",SC_JEECG_NO_AUTHZ);
-            }
             WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(code);
             String openid = session.getOpenid();
             String sessionKey = session.getSessionKey();
             // 单机锁
             synchronized (openid.intern()) {
                 // 查询用户是否已存在
-                User user = this.getOne(Wrappers.<User>lambdaQuery().eq(User::getOpenid, openid).eq(User::getDelFlag,0));
+                User user = this.getOne(Wrappers.<User>lambdaQuery().eq(User::getOpenid, openid).eq(User::getDelFlag, 0));
                 // 用户不存在则创建
                 if (user == null) {
                     user = new User();
@@ -67,30 +65,63 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IU
                     user.setGender(gender);
                     boolean result = this.save(user);
                     if (!result) {
-                        throw new JeecgBootException("登录失败",SC_INTERNAL_SERVER_ERROR_500);
+                        throw new JeecgBootException("登录失败", SC_INTERNAL_SERVER_ERROR_500);
                     }
                 }
                 // 记录用户的登录态
                 request.getSession().setAttribute(USER_LOGIN_STATE, user);
-                LoginUserVO loginUserVO = this.getLoginUserVO(user);
-                String userAccount = user.getUserAccount();
-                String userPassword = user.getUserPassword();
-                //1.生成token
-                String token = JwtUtil.sign(userAccount, userPassword);
-                // 设置token缓存有效时间
-                redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
-                redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME * 2 / 1000);
-                loginUserVO.setToken(token);
-                return loginUserVO;
+                return generateLoginUserVO(user);
             }
         } catch (WxErrorException e) {
-            log.error(e.getMessage(), e);
-            throw new JeecgBootException("小程序登录失败:" + e,SC_INTERNAL_SERVER_ERROR_500);
+            log.error("微信登录失败: {}"+ e.getMessage());
+            throw new JeecgBootException("小程序登录失败:" + e, SC_INTERNAL_SERVER_ERROR_500);
         } finally {
-            WxMaConfigHolder.remove();//清理ThreadLocal
+            WxMaConfigHolder.remove(); // 清理ThreadLocal
         }
     }
 
+    @Override
+    public LoginUserVO wechatLogin(String code) {
+        try {
+            WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(code);
+            String openid = session.getOpenid();
+            // 通过openId获取在系统中是否是已经绑定过的用户
+            User user = this.getOne(Wrappers.<User>lambdaQuery().eq(User::getOpenid, openid).eq(User::getDelFlag, 0));
+            if (null == user) {
+                // 用户不存在则创建
+                    user = new User();
+                    user.setOpenid(openid);
+                    user.setUserAccount(IdUtil.getSnowflakeNextIdStr());
+                    String encryptPassword = DigestUtils.md5DigestAsHex((SALTA_APP).getBytes());
+                    user.setUserPassword(encryptPassword);
+                    user.setUserName("微信用户");
+                    boolean result = this.save(user);
+                    if (!result) {
+                        throw new JeecgBootException("登录失败", SC_INTERNAL_SERVER_ERROR_500);
+                }
+            }
+            return generateLoginUserVO(user);
+        } catch (WxErrorException e) {
+            log.error("微信登录失败: " + e.getMessage());
+            throw new JeecgBootException("小程序登录失败:" + e, SC_INTERNAL_SERVER_ERROR_500);
+        } finally {
+            WxMaConfigHolder.remove(); // 清理ThreadLocal
+        }
+    }
+
+    private LoginUserVO generateLoginUserVO(User user) {
+        String userAccount = user.getUserAccount();
+        String userPassword = user.getUserPassword();
+        // 1.生成token
+        String token = JwtUtil.sign(userAccount, userPassword);
+        // 设置token缓存有效时间
+        redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
+        redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME * 2 / 1000);
+        LoginUserVO loginUserVO = getLoginUserVO(user);
+        loginUserVO.setToken(token);
+        return loginUserVO;
+    }
+
     @Override
     public LoginUserVO getLoginUserVO(User user) {
         if (user == null) {
@@ -100,4 +131,4 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IU
         BeanUtils.copyProperties(user, loginUserVO);
         return loginUserVO;
     }
-}
+}