Jelajahi Sumber

fix 邮箱登录

zoujiajian 3 tahun lalu
induk
melakukan
d1a4f6c665

+ 18 - 0
netflix-common/src/main/java/com/cyksj/common/util/StringUtil.java

@@ -6,6 +6,7 @@ import java.io.PrintWriter;
 import java.io.StringWriter;
 import java.util.ArrayList;
 import java.util.List;
+import java.util.Random;
 
 /**
  * @author  chan 字符串操作辅助类
@@ -408,4 +409,21 @@ public final class StringUtil {
 			sb.append(randomStr.charAt(number));
 		}
 	}
+
+	/**
+	 * 生成4位\6位随机数
+	 */
+	public static String getRandomCodeStr(Integer digit) {
+		if (null == digit) {
+			digit = 6;
+		}
+		String code;
+		// 生成验证码
+		if (digit == 4) {
+			code = new Random().nextInt(8999) + 1000 + "";
+		} else {
+			code = new Random().nextInt(899999) + 100000 + "";
+		}
+		return code;
+	}
 }

+ 3 - 3
netflix-dao/src/main/java/com/cyksj/mapper/manage/statistics/StatisticsUserDataMapper.java

@@ -20,13 +20,13 @@ public interface StatisticsUserDataMapper extends BaseMapper<StatisticsUserData>
 	@Select("select count(distinct unionid) from user where update_time between #{yesZeroDate} and #{thisZeroDate} and unionid != ''")
 	Integer getNumOfActiveUser(@Param("yesZeroDate") Date yesZeroDate, @Param("thisZeroDate") Date thisZeroDate);
 
-	@Select("select count(*) from user where login_phone != ''")
+	@Select("select count(*) from user where (login_phone != '' or email != '')")
 	Integer getPcTotalOfUser();
 
-	@Select("select count(*) from user where created_time between #{yesZeroDate} and #{thisZeroDate} and login_phone != ''")
+	@Select("select count(*) from user where created_time between #{yesZeroDate} and #{thisZeroDate} and (login_phone != '' or email != '')")
 	Integer getPcNumOfNewUser(@Param("yesZeroDate") Date yesZeroDate, @Param("thisZeroDate") Date thisZeroDate);
 
-	@Select("select count(*) from user where update_time between #{yesZeroDate} and #{thisZeroDate} and login_phone != ''")
+	@Select("select count(*) from user where update_time between #{yesZeroDate} and #{thisZeroDate} and (login_phone != '' or email != '')")
 	Integer getPcNumOfActiveUser(@Param("yesZeroDate") Date yesZeroDate, @Param("thisZeroDate") Date thisZeroDate);
 
 	@Select("select count(*) from user_distribute_shared where created_time between #{yesZeroDate} and #{thisZeroDate}")

+ 4 - 0
netflix-dao/src/main/java/com/cyksj/model/entity/User.java

@@ -19,6 +19,10 @@ public class User extends BaseEntity implements Serializable{
     private String phone ;
     /** 手机号登录 */
     private String loginPhone;
+    /**
+     * 邮箱登录
+     */
+    private String email;
     /** 昵称;昵称 */
     private String nickname ;
     /** 头像;头像 */

+ 10 - 0
netflix-dao/src/main/java/com/cyksj/model/request/LoginPhoneReq.java

@@ -14,6 +14,11 @@ import lombok.Setter;
 public class LoginPhoneReq {
 	private String phone;
 
+	/**
+	 * 邮箱
+	 */
+	private String email;
+
 	/**
 	 * 验证码
 	 */
@@ -23,4 +28,9 @@ public class LoginPhoneReq {
 	 * 分销人用户id
 	 */
 	private Long sharedId;
+
+	/**
+	 * 1短信登录、2邮箱登录
+	 */
+	private Integer type;
 }

+ 6 - 0
netflix-service/pom.xml

@@ -29,6 +29,12 @@
             <artifactId>spring-boot-configuration-processor</artifactId>
             <optional>true</optional>
         </dependency>
+
+        <!-- 邮箱jar -->
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-mail</artifactId>
+        </dependency>
     </dependencies>
 
 </project>

+ 2 - 1
netflix-service/src/main/java/com/cyksj/redis/RedisService.java

@@ -589,7 +589,8 @@ public class RedisService {
 	    CORP_ACCESSO_TOKEN_KEY("corp:access_token:", "corp_access_token", 60 * 30L),
 	    MAPPING_INDEX_KEY("mapper:index:", "授权跳转", 60 * 10L),
         WX_LOGIN_AUTH_URI("wx_login_auth_uri:%s", "微信网页授权登录uri", 60 * 60 * 24L),
-        RECOMMEND_COUPON_DAY("recommend_coupon_day:%s", "推荐优惠券弹窗", 60 * 60 * 24L)
+        RECOMMEND_COUPON_DAY("recommend_coupon_day:%s", "推荐优惠券弹窗", 60 * 60 * 24L),
+        EMAIL_CODE_KEY("email_code_key:%s", "邮箱验证码", 60 * 3)
         ;
 
         private String name;

+ 15 - 0
netflix-web/src/main/java/com/cyksj/web/controller/mail/MailService.java

@@ -0,0 +1,15 @@
+package com.cyksj.web.controller.mail;
+
+/*
+ *项目名: netflix
+ *文件名: MailService
+ *创建者: JavaZou
+ *创建时间:2023/1/3 15:31
+ */
+public interface MailService {
+
+	/**
+	 * 邮箱登录验证码
+	 */
+	String sendLoginCodeEmailToPeople(Integer digit, String toAddress);
+}

+ 64 - 0
netflix-web/src/main/java/com/cyksj/web/controller/mail/impl/MailServiceImpl.java

@@ -0,0 +1,64 @@
+package com.cyksj.web.controller.mail.impl;
+
+import com.cyksj.common.util.StringUtil;
+import com.cyksj.redis.RedisService;
+import com.cyksj.web.controller.mail.MailService;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.mail.MailException;
+import org.springframework.mail.SimpleMailMessage;
+import org.springframework.mail.javamail.JavaMailSender;
+import org.springframework.stereotype.Service;
+
+/*
+ *项目名: netflix
+ *文件名: MailServiceImpl
+ *创建者: JavaZou
+ *创建时间:2023/1/3 15:54
+ */
+@Service
+@RequiredArgsConstructor
+@Slf4j
+public class MailServiceImpl implements MailService {
+	@Value("${spring.mail.username}")
+	private String from;
+
+	private final JavaMailSender mailSender;
+
+	private final RedisService redisService;
+
+	@Override
+	public String sendLoginCodeEmailToPeople(Integer digit, String toAddress) {
+		// 生成验证码
+		String code = StringUtil.getRandomCodeStr(digit);
+		String subject = "【银河录像局】登录验证码";
+		String content = String.format("尊敬的用户,您的验证码为%s,此验证码仅用于银河录像。【银河录像局】", code);
+		boolean flag = sendMail(toAddress, subject, content);
+		if (flag) {
+			//删除之前的验证码缓存key
+			String key = RedisService.key.EMAIL_CODE_KEY.getNameFormat(toAddress);
+			redisService.del(key);
+			//将验证码存入redis
+			redisService.set(key, code, RedisService.key.EMAIL_CODE_KEY.getTimeout());
+			return code;
+		}
+		return null;
+	}
+
+
+	public boolean sendMail(String toAddress, String subject, String text) {
+		SimpleMailMessage msg = new SimpleMailMessage();
+		msg.setFrom(from);
+		msg.setTo(toAddress);
+		msg.setSubject(subject);
+		msg.setText(text);
+		try {
+			mailSender.send(msg);
+		} catch (MailException ex) {
+			log.error(ex.getMessage());
+			return false;
+		}
+		return true;
+	}
+}

+ 65 - 30
netflix-web/src/main/java/com/cyksj/web/controller/user/AuthorizationController.java

@@ -6,13 +6,16 @@ import cn.hutool.core.date.DateUtil;
 import cn.hutool.core.lang.Validator;
 import cn.hutool.core.util.StrUtil;
 import cn.hutool.json.JSONObject;
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
 import com.baomidou.mybatisplus.core.toolkit.Wrappers;
 import com.cyksj.common.EnvCommonService;
+import com.cyksj.common.annotation.NoSubmit;
 import com.cyksj.common.exception.BusinessRuntimeException;
 import com.cyksj.common.snowflake.Sequence;
 import com.cyksj.common.util.Codec;
 import com.cyksj.common.util.Jsons;
 import com.cyksj.common.util.SmsUtil;
+import com.cyksj.common.util.StringUtil;
 import com.cyksj.config.WeChatConfig;
 import com.cyksj.config.wxlogin.WxOpenPlatYHLXLoginConfig;
 import com.cyksj.dto.Result;
@@ -34,6 +37,7 @@ import com.cyksj.service.authorization.AuthorizationService;
 import com.cyksj.service.order.OrderDonService;
 import com.cyksj.service.user.UserService;
 import com.cyksj.service.wechat.WeChatService;
+import com.cyksj.web.controller.mail.MailService;
 import com.cyksj.web.util.StpUserUtil;
 import lombok.RequiredArgsConstructor;
 import lombok.extern.slf4j.Slf4j;
@@ -48,7 +52,6 @@ import javax.servlet.http.HttpServletResponse;
 import java.net.URLEncoder;
 import java.nio.charset.StandardCharsets;
 import java.util.Date;
-import java.util.Random;
 
 /**
  * @author chan
@@ -88,6 +91,8 @@ public class AuthorizationController {
 
     private final UserDistributeSharedMapper userDistributeSharedMapper;
 
+    private final MailService mailService;
+
     @GetMapping(value = "/weChat")
     public void base(String url,Long sharedId, String authType, HttpServletResponse response) throws Exception {
 
@@ -255,25 +260,18 @@ public class AuthorizationController {
      * 获取手机验证码
      */
     @GetMapping("/get/phone/code")
+    @NoSubmit
     public Result<String> getPhoneCode(String phone, Integer digit) {
         if (StrUtil.isBlank(phone) || !Validator.isMobile(phone)) {
             throw BusinessRuntimeException.getInstance("请输入正确手机号");
         }
-        if (null == digit) {
-            digit = 6;
-        }
+
         PhoneCode phoneCode = phoneCodeMapper.selectOne(Wrappers.lambdaQuery(PhoneCode.class).eq(PhoneCode::getPhone, phone).last("limit 1"));
         if (phoneCode == null) {
             phoneCode = new PhoneCode();
             phoneCode.setPhone(phone);
         }
-        String code;
-        // 生成验证码
-        if (digit == 4) {
-            code = new Random().nextInt(8999) + 1000 + "";
-        } else {
-            code = new Random().nextInt(899999) + 100000 + "";
-        }
+        String code = StringUtil.getRandomCodeStr(digit);
         phoneCode.setCode(code);
         if (phoneCode.getId() == null) {
             phoneCodeMapper.insert(phoneCode);
@@ -285,34 +283,71 @@ public class AuthorizationController {
     }
 
     /**
-     * 手机号授权登录
+     * 发放邮箱验证码
      */
-    @PostMapping("/login/phone")
-    public Result<LoginPhoneRep> loginByPhone(@RequestBody LoginPhoneReq loginPhoneReq, HttpServletResponse response) throws Exception {
-        if (StrUtil.hasEmpty(loginPhoneReq.getPhone(), loginPhoneReq.getCode())) {
-            throw BusinessRuntimeException.getInstance("请输入对应信息");
-        }
-        DateTime now = DateTime.now();
-        PhoneCode phoneCode = phoneCodeMapper.selectOne(Wrappers.lambdaQuery(PhoneCode.class).eq(PhoneCode::getPhone, loginPhoneReq.getPhone()).last("limit 1"));
-        if (phoneCode == null || StrUtil.isEmpty(phoneCode.getCode())) {
-            throw BusinessRuntimeException.getInstance("请重新获取手机验证码");
+    @GetMapping("/get/email/code")
+    @NoSubmit
+    public Result<String> getEmailCode(String email, Integer digit) {
+        if (email == null || !Validator.isEmail(email)) {
+            throw BusinessRuntimeException.getInstance("请输入正确邮箱");
         }
-        //3分钟失效
-        Date updateTime = phoneCode.getUpdateTime();
-        DateTime afterFiveMinutes = DateUtil.offsetMinute(updateTime, 3);
-        if (now.isAfter(afterFiveMinutes)) {
-            throw BusinessRuntimeException.getInstance("手机验证码已失效,请重新获取");
+        String code = mailService.sendLoginCodeEmailToPeople(digit, email);
+        if (code == null) {
+            throw BusinessRuntimeException.getInstance("获取邮箱验证码错误");
         }
-        if (!StrUtil.equals(loginPhoneReq.getCode(), phoneCode.getCode())) {
-            throw BusinessRuntimeException.getInstance("手机验证码错误,请重新输入");
+        return GatewayResponse.SUCCESS.newBuilder().toResult("发送成功");
+    }
+
+    /**
+     * 手机号授权登录
+     */
+    @PostMapping("/login/phone")
+    @NoSubmit
+    public Result<LoginPhoneRep> loginByPhone(@RequestBody LoginPhoneReq loginPhoneReq) throws Exception {
+        LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery(User.class).last("limit 1");
+        if (loginPhoneReq.getType() == 1) {
+            if (StrUtil.hasEmpty(loginPhoneReq.getPhone(), loginPhoneReq.getCode())) {
+                throw BusinessRuntimeException.getInstance("请输入对应信息");
+            }
+            DateTime now = DateTime.now();
+            PhoneCode phoneCode = phoneCodeMapper.selectOne(Wrappers.lambdaQuery(PhoneCode.class).eq(PhoneCode::getPhone, loginPhoneReq.getPhone()).last("limit 1"));
+            if (phoneCode == null || StrUtil.isEmpty(phoneCode.getCode())) {
+                throw BusinessRuntimeException.getInstance("请重新获取手机验证码");
+            }
+            //3分钟失效
+            Date updateTime = phoneCode.getUpdateTime();
+            DateTime afterFiveMinutes = DateUtil.offsetMinute(updateTime, 3);
+            if (now.isAfter(afterFiveMinutes)) {
+                throw BusinessRuntimeException.getInstance("手机验证码已失效,请重新获取");
+            }
+            if (!StrUtil.equals(loginPhoneReq.getCode(), phoneCode.getCode())) {
+                throw BusinessRuntimeException.getInstance("手机验证码错误,请重新输入");
+            }
+            wrapper.eq(User::getLoginPhone, loginPhoneReq.getPhone());
+        }else if (loginPhoneReq.getType() == 2){
+            if (StrUtil.isEmpty(loginPhoneReq.getEmail())) {
+                throw BusinessRuntimeException.getInstance("邮箱不能为空");
+            }
+            String code = redisService.getStr(RedisService.key.EMAIL_CODE_KEY.getNameFormat(loginPhoneReq.getEmail()));
+            if (StrUtil.isEmpty(code)) {
+                throw BusinessRuntimeException.getInstance("邮箱验证码已失效,请重新获取");
+            }
+            wrapper.eq(User::getEmail, loginPhoneReq.getEmail());
+            redisService.del(RedisService.key.EMAIL_CODE_KEY.getNameFormat(loginPhoneReq.getEmail()));
+        }else {
+            throw BusinessRuntimeException.getInstance("系统异常,请刷新页面重新操作");
         }
         //保存用户信息
-        User user = userService.getOne(Wrappers.lambdaQuery(User.class).eq(User::getLoginPhone, loginPhoneReq.getPhone()).last("limit 1"));
+        User user = userService.getOne(wrapper);
         UserDistributeShared userDistributeShared = null;
         Long sharedId = loginPhoneReq.getSharedId();
         if (user == null) {
             user = new User();
-            user.setLoginPhone(loginPhoneReq.getPhone());
+            if (loginPhoneReq.getType() == 1) {
+                user.setLoginPhone(loginPhoneReq.getPhone());
+            } else if (loginPhoneReq.getType() == 2) {
+                user.setEmail(loginPhoneReq.getEmail());
+            }
             user.setNickname(String.format("银河用户%s", Codec.DoDigest.custom().setAlgorithm(Codec.DoDigest.Algorithm.MD5).setStringData(String.format("%s%s", user.getId(), user.getLoginPhone())).toHexString().substring(0, 6)));
             //默认头像
             user.setHeadimgurl("https://cdn.sxfoundation.com/picture/f6ee11101c4f5f0bc48d88aca7a5dbfd-1666945673391.png");

File diff ditekan karena terlalu besar
+ 0 - 0
netflix-web/src/main/resources/application-dev.yml


File diff ditekan karena terlalu besar
+ 0 - 0
netflix-web/src/main/resources/application-prd.yml


Beberapa file tidak ditampilkan karena terlalu banyak file yang berubah dalam diff ini