直播网站程序源码,实现邮箱验证码登录(代码部分)

代码实现

前端部分

 

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0,user-scalable=no,minimal-ui">
        <title>馅饼研究所</title>
        <link rel="icon" href="../images/favico.ico">
        <!--不同屏幕尺寸根字体设置-->
        <script src="../js/base.js"></script>
        <!--element-ui的样式-->
        <link rel="stylesheet" href="../../backend/plugins/element-ui/index.css" />
        <!--引入vant样式-->
        <link rel="stylesheet" href="../styles/vant.min.css"/>
        <!-- 引入样式  -->
        <link rel="stylesheet" href="../styles/index.css" />
        <!--本页面内容的样式-->
        <link rel="stylesheet" href="../styles/login.css" />
      </head>
    <body>
        <div id="login" v-loading="loading">
            <div>登录</div>
            <div>
                <el-input placeholder=" 请输入邮箱" v-model="form.phone"  maxlength='30'/></el-input>
                <div></div>
                <el-input placeholder=" 请输入验证码" v-model="form.code"  maxlength='20'/></el-input>
                <span @click='getCode' :disabled="canClick">{{ verifyCode }}</span>
            </div>
            <div v-if="msgFlag">邮箱格式输入不正确,请重新输入</div>
            <el-button type="primary" :class="{btnSubmit:1===1,btnNoPhone:!form.phone,btnPhone:form.phone}" @click="btnLogin">登录</el-button>
        </div>
        <!-- 开发环境版本,包含了有帮助的命令行警告 -->
        <script src="../../backend/plugins/vue/vue.js"></script>
        <!-- 引入组件库 -->
        <script src="../../backend/plugins/element-ui/index.js"></script>
        <!-- 引入vant样式 -->
        <script src="../js/vant.min.js"></script>
        <!-- 引入axios -->
        <script src="../../backend/plugins/axios/axios.min.js"></script>
        <script src="../js/request.js"></script>
        <script src="../api/login.js"></script>
    </body>
    <script>
        new Vue({
            el:"#login",
            data(){
                return {
                    form:{
                        phone:'',
                        code:''
                    },
                    msgFlag:false,
                    loading:false,
                    verifyCode : '发送验证码',
                    totalTime: 60,
                    canClick: false
                }
            },
            computed:{},
            created(){},
            mounted(){},
            methods:{
                getCode(){
                    if (this.canClick) return
                    this.form.code = ''
                    //验证手机号
                    // const regex = /^(13[0-9]{9})|(15[0-9]{9})|(17[0-9]{9})|(18[0-9]{9})|(19[0-9]{9})$/;
                    //验证邮箱
                    const regex = /^(\w|-|_)+@\w+\.([a-zA-Z]{2,4})$/;
                    if (regex.test(this.form.phone)) {
                        this.msgFlag = false
                        //this.form.code = (Math.random()*1000000).toFixed(0)
                        sendMsgApi({phone:this.form.phone})
                    }else{
                        this.msgFlag = true
                    }
                    this.canClick = true
                    this.verifyCode = this.totalTime + 's后重新发送'
                    let clock = window.setInterval(() => {
                     //倒计时功能
                        this.totalTime--
                        this.verifyCode = this.totalTime + 's后重新发送'
                        if (this.totalTime < 0) {
                            window.clearInterval(clock)
                            this.verifyCode = '重新获取验证码'
                            this.totalTime = 60
                            this.canClick = false
                        }
                    }, 1000)
                },
                async btnLogin(){
                    if(this.form.phone && this.form.code){
                        this.loading = true
                        const res = await loginApi(this.form)
                        this.loading = false
                        if(res.code === 1){
                            sessionStorage.setItem("userPhone",this.form.phone)
                            window.requestAnimationFrame(()=>{
                                window.location.href= '/front/index.html'
                            })                           
                        }else{
                            this.$notify({ type:'warning', message:res.msg});
                        }
                    }else{
                        this.$notify({ type:'warning', message:'请输入手机号码'});
                    }
                }
            }
        })
    </script>
</html>

前端部分实现并不难,一开始我使用的是手机号作为登录验证,后来才改回的邮箱,所以变量名才是phone,我这里就不再改了,不影响使用。为了交互友好性,我这里引入了一个简单的倒计时功能,让用户在60秒之后才能第二次获取验证码,以防止用户恶意点击造成验证码频繁发送。

 

后端部分

2.1:工具类

 


package com.my.reggie.util;
import org.apache.commons.mail.HtmlEmail;
/**
 * 发送邮箱验证码工具类
 */
public class SendEmailUtils {
    /**
     * 发送验证码
     * @param email  接收邮箱
     * @param code   验证码
     * @return  void
     */
    public static void sendAuthCodeEmail(String email,String code) {
        try {
            HtmlEmail mail = new HtmlEmail();
            /*发送邮件的服务器 126邮箱为smtp.126.com,163邮箱为163.smtp.com,QQ为smtp.qq.com*/
            mail.setHostName("smtp.qq.com");
            /*不设置发送的消息有可能是乱码*/
            mail.setCharset("UTF-8");
            /*IMAP/SMTP服务的密码 username为你开启发送验证码功能的邮箱号 password为你在qq邮箱获取到的一串字符串*/
            mail.setAuthentication("666@qq.com", "rtyhushbaeg");
            /*发送邮件的邮箱和发件人*/
            mail.setFrom("666@qq.com", "馅饼研究所");
            /*使用安全链接*/
            mail.setSSLOnConnect(true);
            /*接收的邮箱*/
            mail.addTo(email);
            /*设置邮件的主题*/
            mail.setSubject("登录验证码");
            /*设置邮件的内容*/
            mail.setMsg("尊敬的用户:你好! 登录验证码为:" + code + "(有效期为一分钟)");
            mail.send();//发送
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

 

2.2:UserController

 


package com.my.reggie.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.my.reggie.common.R;
import com.my.reggie.pojo.User;
import com.my.reggie.service.UserService;
import com.my.reggie.util.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
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 javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 发送验证码
     *
     * @param user
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) {
        // 获取邮箱号
        String phone = user.getPhone();
        if (phone == null) {
            return R.error("邮箱号为空!");
        }
        // 随机生成4位验证码
        String code = String.valueOf(ValidateCodeUtils.generateValidateCode(4));
        log.info("验证码为:{}", code);
        //发送验证码到邮箱
        // SendEmailUtils.sendAuthCodeEmail(phone,code);
        // 将验证码保存到session
        // session.setAttribute("code", code);
        //将验证码缓存到Redis(有效时间为1分钟)
        stringRedisTemplate.opsForValue().set("code",code,1, TimeUnit.MINUTES);
        //将手机号保存到session
        session.setAttribute("phone",phone);
        return R.success("验证码发送成功!");
    }
    /**
     * 登录功能
     * @param map
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map<String, String> map, HttpSession session) {
        // 获取手机号
        String phone = map.get("phone");
        // 获取验证码
        String code = map.get("code");
        // 从session中获取验证码
        // String codeInSession = (String) session.getAttribute("code");
        // 从缓存中获取验证码
        String codeInRedis = stringRedisTemplate.opsForValue().get("code");
        //从session中获取请求验证码的手机号
        String phoneInSession = (String) session.getAttribute("phone");
        // 进行验证码比对
        if (codeInRedis == null || phoneInSession == null || !codeInRedis.equals(code) || !phoneInSession.equals(phone)) {
            return R.error("验证码错误");
        }
        // 判断该用户是否注册
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getPhone, phone);
        User user = userService.getOne(lqw);
        if (user == null) {
            // 用户还未注册,自动注册
            user = new User();
            user.setPhone(phone);
            userService.save(user);
        }
        //设置session
        session.setAttribute("user", user.getId());
        session.setMaxInactiveInterval(6*60*60);
        //删除验证码缓存
        stringRedisTemplate.delete("code");
        return R.success(user);
    }
    /**
     * 退出登录
     * @return
     */
    @PostMapping("/loginout")
    public R<String> logout(HttpServletRequest request){
        //清除session
        request.getSession().removeAttribute("user");
        request.getSession().removeAttribute("phone");
        // request.getSession().removeAttribute("code");
        return R.success("退出登录成功");
    }
}

 

以上就是 直播网站程序源码,实现邮箱验证码登录(代码部分),更多内容欢迎关注之后的文章

 

原文地址:http://www.cnblogs.com/yunbaomengnan/p/16813314.html

1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长! 2. 分享目的仅供大家学习和交流,请务用于商业用途! 3. 如果你也有好源码或者教程,可以到用户中心发布,分享有积分奖励和额外收入! 4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解! 5. 如有链接无法下载、失效或广告,请联系管理员处理! 6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需! 7. 如遇到加密压缩包,默认解压密码为"gltf",如遇到无法解压的请联系管理员! 8. 因为资源和程序源码均为可复制品,所以不支持任何理由的退款兑现,请斟酌后支付下载 声明:如果标题没有注明"已测试"或者"测试可用"等字样的资源源码均未经过站长测试.特别注意没有标注的源码不保证任何可用性