06 手机号 + 短信验证

发布时间 2023-07-01 18:30:09作者: 阿四与你

短信发送

启用阿里云短信服务

image

image

设置签名模板

image

image

image

设置accesskey

image

image

添加权限

image

代码开发

image

sdk帮助文档

image

image

在pom.xml文件导入依赖

        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-core</artifactId>
            <version>4.5.16</version>
        </dependency>

        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-dysmsapi</artifactId>
            <version>2.1.0</version>
        </dependency>

复制**SMSUtils.java**到utils包(自行创建)下。

手机号验证码登录

预准备

image

image

image

image

前端代码

image

image

基础工作

1)拷贝user.java到entity下,创建基本结构,再复制ValidateCodeUtils工具类。

image

2)修改front/api/login.js:加上下面的代码:

function sendMsgApi(data) {
  return $axios({
    'url': '/user/sendMsg',
    'method': 'post',
      data
  })
}

3)修改front/page/login.html的以下部分(注:第8、17、20行为修改处):

            methods:{
                getCode(){
                    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})$/;
                    if (regex.test(this.form.phone)) {
                        this.msgFlag = false
                        sendMsgApi({phone:this.form.phone});
                        this.form.code = (Math.random()*10000).toFixed(0)
                    }else{
                        this.msgFlag = true
                    }
                },
                async btnLogin(){
                    if(this.form.phone && this.form.code){
                        this.loading = true
                        const res = await loginApi({phone:this.form.phone,code:this.form.code})
                        this.loading = false
                        if(res.code === 1){
                            sessionStorage.setItem("userPhone",this.form.phone)
                            sessionStorage.setItem("userCode",this.form.code)
                            window.requestAnimationFrame(()=>{
                                window.location.href= '/front/index.html'
                            })                       
                        }else{
                            this.$notify({ type:'warning', message:res.msg});
                        }
                    }else{
                        this.$notify({ type:'warning', message:'请输入手机号码'});
                    }
                }
            }

代码开发

LoginCheckFilter类下面,修改代码:


        //4-1判断登陆状态,如果已登录,则直接放行
        if(request.getSession().getAttribute("employee")!=null){
            log.info("用户已登录,用户id为:{}",request.getSession().getAttribute("employee"));

            //存入id到线程当中
            Long empId=(Long)request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(empId);

//            long id =Thread.currentThread().getId();
//            log.info("线程id为{}",id);

            filterChain.doFilter(request,response);
            return;
        }

        //4-2判断移动端登陆状态,如果已登录,则直接放行
        if(request.getSession().getAttribute("user")!=null){
            log.info("用户已登录,用户id为:{}",request.getSession().getAttribute("user"));

            //存入id到线程当中
            Long userId=(Long)request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userIdId);

//            long id =Thread.currentThread().getId();
//            log.info("线程id为{}",id);

            filterChain.doFilter(request,response);
            return;
        }

UserController类下发送验证码的:

    /**
     * 发送手机短信验证码。因为前端发送的是json,所以要加上注解。
     * @param user
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        //获取手机号
        String phone = user.getPhone();

        if(!StringUtils.isEmpty(phone)){
            //生成随机的的4位验证码
            String code= ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("code={}",code);

            //调用阿里云提供的短信API服务完成发送短信
            SMSUtils.sendMessage("瑞吉外卖","",phone,code);
            //需要将生成的验证码保存到session
            session.setAttribute(phone,code);
            return R.success("手机短信验证码发送成功");
        }
        return R.error("短信发送失败");
    }

注意:这里要在阿里云上申请对应签名的模板,签名+模板一起审核通过才能用。

登录:

image

提交了两项数据。

    /**
     * 移动端用户登录
     * @param map 用来对应数据
     * @return
     */
    @PostMapping("/login")
    public R<String> login(@RequestBody Map map, HttpSession session){
        log.info(map.toString());
        //获取手机号
        String phone=map.get("phone").toString();

        //获取验证码
        String code=map.get("code").toString();

        //从Session中获取保存的验证码
        Object codeInSession =session.getAttribute(phone);

        //进行验证码比对(页面提交的验证码和session中保存的验证码比对)
        if(codeInSession!=null&&codeInSession.equals(code)){
            //如果能比对成功,说明登录成功
            LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone,phone);//根据手机号查对应的值

            User user = userService.getOne(queryWrapper);
            if(user==null){
                //判断当前手机号对应的用户是否为新用户,如果是新用户就自动完成注册
                user=new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            //存user就好进入移动端界面
            session.setAttribute("user",user.getId());
            //不知道为啥传入不了user
            return R.success("登陆成功");
        }
        return R.error("登录失败");
    }