Pārlūkot izejas kodu

新增app 微信登陆

xiaoshushu 4 gadi atpakaļ
vecāks
revīzija
0e87390597

+ 82 - 25
ruoyi-app/src/main/java/com/ruoyi/app/controller/AppLoginController.java

@@ -1,23 +1,20 @@
 package com.ruoyi.app.controller;
 
 
-import com.alibaba.fastjson.JSON;
 import com.alibaba.fastjson.JSONObject;
-import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
 import com.ruoyi.app.annotation.PassToken;
 import com.ruoyi.app.base.AppLoginUser;
 import com.ruoyi.app.base.AppTokenService;
-import com.ruoyi.app.domain.TbAppUser;
 import com.ruoyi.app.domain.vo.AppLoginVo;
 import com.ruoyi.app.domain.vo.AppMemberVo;
 import com.ruoyi.app.service.ITbAppUserService;
 import com.ruoyi.app.util.AliSMSUtil;
-import com.ruoyi.common.constant.Constants;
+import com.ruoyi.common.config.RuoYiConfig;
 import com.ruoyi.common.core.domain.AjaxResult;
-import com.ruoyi.common.core.redis.RedisCache;
 import com.ruoyi.common.utils.DateUtils;
 import com.ruoyi.common.utils.ServletUtils;
 import com.ruoyi.common.utils.StringUtils;
+import com.ruoyi.common.utils.file.FileUtils;
 import com.ruoyi.common.utils.ip.IpUtils;
 import io.swagger.annotations.Api;
 import io.swagger.annotations.ApiImplicitParam;
@@ -27,7 +24,12 @@ import lombok.RequiredArgsConstructor;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.web.bind.annotation.*;
 
-import javax.servlet.http.HttpServletRequest;
+import javax.net.ssl.HttpsURLConnection;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.URL;
 import java.util.Date;
 import java.util.Map;
 
@@ -37,10 +39,10 @@ import java.util.Map;
  * @author Alex
  * @date 2020-09-24
  */
-@Api(value = "APP登录",tags = "APP登录")
+@Api(value = "APP登录", tags = "APP登录")
 @RequiredArgsConstructor(onConstructor_ = @Autowired)
 @RestController
-@RequestMapping("/app" )
+@RequestMapping("/app")
 public class AppLoginController {
 
     private final AppTokenService appTokenService;
@@ -52,11 +54,11 @@ public class AppLoginController {
     @PassToken
     @ApiOperation(value = "APP登录", notes = "APP登录")
     @PostMapping("/login")
-    public AjaxResult login(@RequestBody AppLoginVo loginVo){
+    public AjaxResult login(@RequestBody AppLoginVo loginVo) {
         if (StringUtils.isBlank(loginVo.getMobile())) {
             return AjaxResult.error("手机号不能为空");
         }
-        if (StringUtils.isBlank(loginVo.getCaptcha())){
+        if (StringUtils.isBlank(loginVo.getCaptcha())) {
             return AjaxResult.error("验证码不能为空");
         }
         //手机短信验证
@@ -65,7 +67,7 @@ public class AppLoginController {
 //            return AjaxResult.error("验证码错误");
 //        }
 
-        AppMemberVo appUser = userService.getAppMember(null,loginVo.getMobile());
+        AppMemberVo appUser = userService.getAppMember(null, loginVo.getMobile());
         boolean ck;
         Date date = new Date();
         // 为空则新增
@@ -76,7 +78,7 @@ public class AppLoginController {
             appUser.setQrcode(DateUtils.getCurrentTimeRandom());
             appUser.setCreateTime(date);
             ck = userService.saveOrUpdate(appUser);
-            if (!ck){
+            if (!ck) {
                 return AjaxResult.error("未知异常,登录失败");
             }
             appUser.setCreateBy(appUser.getUserId().toString());
@@ -88,14 +90,14 @@ public class AppLoginController {
         appUser.setUpdateBy(appUser.getUserId().toString());
         appUser.setUpdateTime(date);
         ck = userService.saveOrUpdate(appUser);
-        if (!ck){
+        if (!ck) {
             return AjaxResult.error("未知异常,登录失败");
         }
 
         //每次登录前,先删除缓存,保证登录唯一性
         appTokenService.delLoginUser(loginVo.getMobile());
         JSONObject jsonObject = new JSONObject();
-        AppLoginUser loginUser =  new AppLoginUser();
+        AppLoginUser loginUser = new AppLoginUser();
         loginUser.setUser(appUser);
         String token = appTokenService.createToken(loginUser);
 
@@ -107,24 +109,77 @@ public class AppLoginController {
 
 
     /**
+     * 微信登录
+     */
+    @PassToken
+    @ApiOperation(value = "APP微信登录", notes = "APP微信登录")
+    @PostMapping("/wxLogin")
+    public AjaxResult wxLogin(@RequestBody AppLoginVo loginVo) throws Exception {
+        AppMemberVo appUser = userService.getAppMember(null, loginVo.getOpenid());
+        // 为空则第一次微信登陆
+        if (appUser == null) {
+            appUser = new AppMemberVo();
+            appUser.setOpenid(loginVo.getOpenid());
+            appUser.setNickName(loginVo.getNickName());
+            //微信头像下载到本地保存
+            appUser.setAvatar("/profile/upload/" + FileUtils.avatarUrl(loginVo.getAvatar()));
+            appUser.setQrcode(DateUtils.getCurrentTimeRandom());
+            appUser.setCreateTime(new Date());
+            boolean flag = userService.saveOrUpdate(appUser);
+            if (!flag) {
+                return AjaxResult.error("登陆失败");
+            }
+            appUser.setCreateBy(appUser.getUserId().toString());
+        }
+        //绑定手机号
+        if (StringUtils.isNotBlank(loginVo.getMobile())) {
+            appUser.setMobile(loginVo.getMobile());
+        }
+        String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
+        appUser.setClientId(loginVo.getClientId());
+        appUser.setLoginIp(ip);
+        appUser.setLoginTime(new Date());
+        appUser.setUpdateBy(appUser.getUserId().toString());
+        appUser.setUpdateTime(new Date());
+        userService.saveOrUpdate(appUser);
+
+        //如果没有绑定手机号
+        if (StringUtils.isEmpty(appUser.getMobile())) {
+            return AjaxResult.error(900, "请绑定手机号");
+        }
+        //每次登录前,先删除缓存,保证登录唯一性
+        appTokenService.delLoginUser(loginVo.getMobile());
+        JSONObject jsonObject = new JSONObject();
+        AppLoginUser loginUser = new AppLoginUser();
+        loginUser.setUser(appUser);
+        String token = appTokenService.createToken(loginUser);
+
+        jsonObject.put("token", token);
+        jsonObject.put("user", appUser);
+
+        return AjaxResult.success(jsonObject);
+    }
+
+    /**
      * 发送短信验证码
-     * @param type 1、用户注册;2、登录确认;3、身份验证;4、登录异常;5、修改密码;6、信息变更;
+     *
+     * @param type   1、用户注册;2、登录确认;3、身份验证;4、登录异常;5、修改密码;6、信息变更;
      * @param mobile 手机号码
      * @return
      */
     @PassToken
     @ApiOperation(value = "发送短信验证码", notes = "发送短信验证码")
     @ApiImplicitParams({
-            @ApiImplicitParam(name = "type", value = "1.用户注册;2.登录确认;3.身份验证;4.登录异常;5.修改密码;6.信息变更",paramType="int"),
-            @ApiImplicitParam(name = "mobile", value = "手机号",paramType="string")
+            @ApiImplicitParam(name = "type", value = "1.用户注册;2.登录确认;3.身份验证;4.登录异常;5.修改密码;6.信息变更", paramType = "int"),
+            @ApiImplicitParam(name = "mobile", value = "手机号", paramType = "string")
     })
     @GetMapping("/captchaSend")
-    public AjaxResult sendCaptcha(Integer type, String mobile){
-        if(StringUtils.isBlank(mobile)){
+    public AjaxResult sendCaptcha(Integer type, String mobile) {
+        if (StringUtils.isBlank(mobile)) {
             return AjaxResult.error("请输入手机号");
         }
-        Map<String,String> map = AliSMSUtil.getInstance().sendSmsCode(type, mobile);
-        if(map.get("code").equals("200")) {
+        Map<String, String> map = AliSMSUtil.getInstance().sendSmsCode(type, mobile);
+        if (map.get("code").equals("200")) {
             return AjaxResult.success("发送成功");
         }
         return AjaxResult.error(map.get("msg"));
@@ -132,6 +187,7 @@ public class AppLoginController {
 
     /**
      * 校验验证码
+     *
      * @param mobile
      * @param captcha
      * @return
@@ -140,14 +196,14 @@ public class AppLoginController {
     @ApiOperation(value = "校验短信验证码", notes = "校验短信验证码")
     @GetMapping("/captchaValidate")
     @ApiImplicitParams({
-            @ApiImplicitParam(name = "mobile", value = "手机号",paramType="string"),
-            @ApiImplicitParam(name = "captcha", value = "验证码",paramType="string")
+            @ApiImplicitParam(name = "mobile", value = "手机号", paramType = "string"),
+            @ApiImplicitParam(name = "captcha", value = "验证码", paramType = "string")
     })
-    public AjaxResult validateCaptcha(String mobile, String captcha){
+    public AjaxResult validateCaptcha(String mobile, String captcha) {
         if (StringUtils.isBlank(mobile)) {
             return AjaxResult.error("手机号不能为空");
         }
-        if (StringUtils.isBlank(captcha)){
+        if (StringUtils.isBlank(captcha)) {
             return AjaxResult.error("验证码不能为空");
         }
         //手机短信验证
@@ -165,4 +221,5 @@ public class AppLoginController {
         appTokenService.delLoginUser(user.getMobile());
         return AjaxResult.success();
     }
+
 }

+ 1 - 1
ruoyi-app/src/main/java/com/ruoyi/app/controller/FamilyController.java

@@ -278,7 +278,7 @@ public class FamilyController extends AppBaseController {
     @ApiOperation("获取家族详细信息")
     @ApiImplicitParam(name = "id", value = "主键id",paramType="Long")
     @GetMapping(value = "/getById/{id}" )
-    public AjaxResult getInfo(Long id) {
+    public AjaxResult getInfo(@PathVariable Long id) {
         if (id == null){
             return AjaxResult.error("id不能为空");
         }

+ 60 - 56
ruoyi-common/src/main/java/com/ruoyi/common/utils/file/FileUtils.java

@@ -1,68 +1,55 @@
 package com.ruoyi.common.utils.file;
 
+import com.ruoyi.common.config.RuoYiConfig;
+
 import java.io.*;
+import java.net.URL;
 import java.net.URLEncoder;
+import javax.net.ssl.HttpsURLConnection;
 import javax.servlet.http.HttpServletRequest;
 
 /**
  * 文件处理工具类
- * 
+ *
  * @author ruoyi
  */
-public class FileUtils extends org.apache.commons.io.FileUtils
-{
+public class FileUtils extends org.apache.commons.io.FileUtils {
     public static String FILENAME_PATTERN = "[a-zA-Z0-9_\\-\\|\\.\\u4e00-\\u9fa5]+";
 
     /**
      * 输出指定文件的byte数组
-     * 
+     *
      * @param filePath 文件路径
-     * @param os 输出流
+     * @param os       输出流
      * @return
      */
-    public static void writeBytes(String filePath, OutputStream os) throws IOException
-    {
+    public static void writeBytes(String filePath, OutputStream os) throws IOException {
         FileInputStream fis = null;
-        try
-        {
+        try {
             File file = new File(filePath);
-            if (!file.exists())
-            {
+            if (!file.exists()) {
                 throw new FileNotFoundException(filePath);
             }
             fis = new FileInputStream(file);
             byte[] b = new byte[1024];
             int length;
-            while ((length = fis.read(b)) > 0)
-            {
+            while ((length = fis.read(b)) > 0) {
                 os.write(b, 0, length);
             }
-        }
-        catch (IOException e)
-        {
+        } catch (IOException e) {
             throw e;
-        }
-        finally
-        {
-            if (os != null)
-            {
-                try
-                {
+        } finally {
+            if (os != null) {
+                try {
                     os.close();
-                }
-                catch (IOException e1)
-                {
+                } catch (IOException e1) {
                     e1.printStackTrace();
                 }
             }
-            if (fis != null)
-            {
-                try
-                {
+            if (fis != null) {
+                try {
                     fis.close();
-                }
-                catch (IOException e1)
-                {
+                } catch (IOException e1) {
                     e1.printStackTrace();
                 }
             }
@@ -71,17 +58,15 @@ public class FileUtils extends org.apache.commons.io.FileUtils
 
     /**
      * 删除文件
-     * 
+     *
      * @param filePath 文件
      * @return
      */
-    public static boolean deleteFile(String filePath)
-    {
+    public static boolean deleteFile(String filePath) {
         boolean flag = false;
         File file = new File(filePath);
         // 路径为文件且不为空则进行删除
-        if (file.isFile() && file.exists())
-        {
+        if (file.isFile() && file.exists()) {
             file.delete();
             flag = true;
         }
@@ -90,50 +75,42 @@ public class FileUtils extends org.apache.commons.io.FileUtils
 
     /**
      * 文件名称验证
-     * 
+     *
      * @param filename 文件名称
      * @return true 正常 false 非法
      */
-    public static boolean isValidFilename(String filename)
-    {
+    public static boolean isValidFilename(String filename) {
         return filename.matches(FILENAME_PATTERN);
     }
 
     /**
      * 下载文件名重新编码
-     * 
-     * @param request 请求对象
+     *
+     * @param request  请求对象
      * @param fileName 文件名
      * @return 编码后的文件名
      */
     public static String setFileDownloadHeader(HttpServletRequest request, String fileName)
-            throws UnsupportedEncodingException
-    {
+            throws UnsupportedEncodingException {
         final String agent = request.getHeader("USER-AGENT");
         String filename = fileName;
-        if (agent.contains("MSIE"))
-        {
+        if (agent.contains("MSIE")) {
             // IE浏览器
             filename = URLEncoder.encode(filename, "utf-8");
             filename = filename.replace("+", " ");
-        }
-        else if (agent.contains("Firefox"))
-        {
+        } else if (agent.contains("Firefox")) {
             // 火狐浏览器
             filename = new String(fileName.getBytes(), "ISO8859-1");
-        }
-        else if (agent.contains("Chrome"))
-        {
+        } else if (agent.contains("Chrome")) {
             // google浏览器
             filename = URLEncoder.encode(filename, "utf-8");
-        }
-        else
-        {
+        } else {
             // 其它浏览器
             filename = URLEncoder.encode(filename, "utf-8");
         }
         return filename;
     }
+
     /**
      * 获取指定文件的输入流
      *
@@ -143,4 +120,31 @@ public class FileUtils extends org.apache.commons.io.FileUtils
     public static InputStream getResourceAsStream(String logoPath) {
         return FileUtils.class.getResourceAsStream(logoPath);
     }
+
+    /**
+     * 下载微信头像到本地
+     *
+     * @param imageUrl
+     * @return
+     * @throws IOException
+     */
+    public static String avatarUrl(String imageUrl) throws IOException {
+        URL url = new URL(imageUrl);
+        HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
+        // 得到URL的输入流
+        InputStream input = con.getInputStream();
+        // 设置数据缓冲
+        byte[] bs = new byte[1024 * 2];
+        // 读取到的数据长度
+        int len = 0;
+        // 输出的文件流保存图片至本地
+        String fileName = System.currentTimeMillis() + ".jpg";
+        OutputStream os = new FileOutputStream(RuoYiConfig.getUploadPath() + "/" + fileName);
+        while ((len = input.read(bs)) != -1) {
+            os.write(bs, 0, len);
+        }
+        os.close();
+        input.close();
+        return fileName;
+    }
 }

+ 6 - 0
ruoyi-system/src/main/java/com/ruoyi/app/domain/vo/AppLoginVo.java

@@ -16,6 +16,12 @@ public class AppLoginVo implements Serializable {
     String mobile;
     @ApiModelProperty(value="验证码")
     String captcha;
+    @ApiModelProperty(value="微信openid")
+    String openid;
+    @ApiModelProperty(value="头像")
+    String avatar;
+    @ApiModelProperty(value="昵称")
+    String nickName;
     @ApiModelProperty(value="个推客户端id")
     String clientId;
 }

+ 1 - 1
ruoyi-system/src/main/resources/mapper/app/TbAppUserMapper.xml

@@ -100,7 +100,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
                 </if>
             </if>
             <if test="search != null and search != '' ">
-                and (a.mobile = #{search} or a.qrcode = #{search})
+                and (a.mobile = #{search} or a.qrcode = #{search} or a.openid=#{search})
             </if>
         </where>
     </select>