Java integrated Alibaba big fish platform SMS service sending verification code -- supplement registration part

Keywords: Operation & Maintenance Mobile axios Redis less

It's still the previous chart

1, back end

  • Server verification needs to be performed again before registration
    • Is the user name registered
    • Is the mobile number registered
    • Whether the verification code is wrong
    • Whether the verification code is implemented
  • Password is encrypted with BCrypt

Controller layer

The method of user name verification and mobile phone number verification is not pasted here, simple query and judgment

package com.czxy.controller;

import com.czxy.pojo.User;
import com.czxy.service.UserService;
import com.czxy.vo.BaseResult;
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;

/**
 * @author Cloud before court
 * @Date 2020/3/20 21:52
 * @description
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/register")
    public BaseResult register(@RequestBody User user) {
        //Server verification
        User result = userService.findByUsername(user.getUsername());
        if (result != null) {
            return BaseResult.error("User name already exists");
        }

        result = userService.findByMobile(user.getMobile());
        if (result != null) {
            return BaseResult.error("The mobile number has been registered");
        }

        //Verification Code
        String code = stringRedisTemplate.opsForValue().get("sms_register" + user.getMobile());

        if (code == null) {
            return BaseResult.error("Invalid verification code");
        }
        if (!code.equalsIgnoreCase(user.getCode())) {
            return BaseResult.error("Incorrect verification code");
        }
        //register
        userService.register(user);
        // Delete the verification code in redis after registration
        stringRedisTemplate.delete("sms_register" + user.getMobile());
        return BaseResult.ok("login was successful");
    }
}



Note: delete the verification code in redis after the registration is completed. It must be placed after the judgment statement. Otherwise, if the verification code is accidentally input incorrectly, click the registration button, and delete it directly in redis without judgment, and then input the correct one. Even if the expiration time is less than 5 minutes, the verification code will return "invalid". Daily rolling thunder

UserServiceImpl

Encrypt with BCrypt password

package com.czxy.service.Impl;

import com.czxy.mapper.UserMapper;
import com.czxy.pojo.User;
import com.czxy.service.UserService;
import com.czxy.utils.BCrypt;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author Cloud before court
 * @Date 2020/3/20 21:47
 * @description
 */
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    /**
     * User registration
     */
    public void register(User user){
        //Cipher encryption
        String password = BCrypt.hashpw(user.getPassword());
        user.setPassword(password);

       //Register (add)
        userMapper.insert(user);
    }
}

2, front-end

Nuxt.js is used in the front end. If you want to get started, click to Nuxt.js learning (1) --- let you clearly understand the environment construction of nuxt.js and nuxt.js , a complete set, systematic and comprehensive learning.

There is nothing at the front end. Some checks and calls to the back end interface are still in the code

Register.vue

<template>
  <div>
    <TopNav></TopNav>
    <div style="clear:both;"></div>
    <HeaderLogo></HeaderLogo>
    <div style="clear:both;"></div>
    <!-- text -->
    <!-- Contents of registration start -->
    <div class="login w990 bc mt10 regist">
      <div class="login_hd">
        <h2>User registration</h2>
        <b></b>
      </div>
      <div class="login_bd">
        <div class="login_form fl">
          <form action method="post">
            <ul>
              <li>
                <label for>User name:</label>
                <input
                  type="text"
                  class="txt"
                  v-model="user.username"
                  name="username"
                  @blur="checkUsername"
                />
                <p>3-20 Character, can be composed of Chinese, letters, numbers and underscores</p>
                <p :class="userMsg.username.code==1?'success':'error'">{{userMsg.username.message}}</p>
              </li>
              <li>
                <label for>Password:</label>
                <input
                  type="password"
                  class="txt"
                  name="password"
                  v-model="user.p1"
                  @blur="checkpassword1"
                />
                <p>6-20 The combination of letters, numbers and symbols can be used instead of pure numbers, letters and symbols</p>
                <p v-if="userMsg.password1.code==0" class="error">{{userMsg.password1.message}}</p>
              </li>
              <li>
                <label for>Confirm password:</label>
                <input
                  type="password"
                  class="txt"
                  name="password"
                  v-model="user.p2"
                  @blur="checkpassword2"
                />
                <p>Please enter the password again</p>
                <p v-if="userMsg.password2.code==0" class="error">{{userMsg.password2.message}}</p>
              </li>
              <li>
                <label for>phone number:</label>
                <input
                  type="text"
                  class="txt"
                  name="mobile"
                  v-model="user.mobile"
                  @blur="checkmobile"
                />
                <p>Please enter your mobile number</p>
                <p v-if="userMsg.mobile.code==1" class="success">{{userMsg.mobile.message}}</p>
                <p v-else class="error">{{userMsg.mobile.message}}</p>
              </li>
              <li class="checkcode">
                <label for>Verification Code:</label>
                <input type="text" name="checkcode" v-model="user.code" />
                <!-- prevent Prevent incident bubbling -->
                <button :disabled="btnDisabled" @click.prevent="sendSms">
                  //Send verification code
                  <span v-show="btnDisabled">{{senconds}}second</span>
                </button>
                <span :class="userMsg.smsData.code==1?'success':'error'">{{userMsg.smsData.message}}</span>
              </li>
              <li>
                <label for>&nbsp;</label>
                <input type="checkbox" class="chb" checked="checked" /> I have read and agreed to the user registration agreement
              </li>
              <li>
                <label for>&nbsp;</label>
                <input type="submit" value @click.prevent="register" class="login_btn" />
              </li>
            </ul>
          </form>
        </div>
        <div class="mobile fl">
          <h3>Mobile quick sign up</h3>
          <p>
            //Mobile phone users in mainland China, edit SMS“
            <strong>XX</strong>"Send to:
          </p>
          <p>
            <strong>1069099988</strong>
          </p>
        </div>
      </div>
    </div>
    <!-- register footer -->
    <div style="clear:both;"></div>
    <Footer></Footer>
  </div>
</template>

<script>
import TopNav from "../components/TopNav";
import HeaderLogo from "../components/HeaderLogo";
import Footer from "../components/Footer";
export default {
  head: {
    title: "Registration page",
    link: [{ rel: "stylesheet", href: "style/login.css" }],
    script: [
      { type: "text/javascript", src: "js/header.js" },
      { type: "text/javascript", src: "js/index.js" }
    ]
  },
  components: {
    TopNav,
    HeaderLogo,
    Footer
  },
  data() {
    return {
      user: {
        mobile: "",
        p1: "",
        p2: ""
      },
      userMsg: {
        //Error prompt data
        smsData: "",
        username: {},
        mobile: {},
        password1: {},
        password2: {}
      },
      btnDisabled: false, //Countdown control variable
      senconds: 30, //Default countdown
      timer: null //Receive timer, clear timer
    };
  },
  methods: {
    //Verify user name
    async checkUsername() {
      if (this.user.username == null) {
        this.userMsg.username = {
          code: 0,
          message: "User name cannot be empty"
        };
        return;
      }
      let { data } = await this.$request.checkUsername(this.user.username);
      this.userMsg.username = data;
    },
    //Verify cell phone number
    async checkmobile() {
      console.info(this.user);
      let { data } = await this.$request.checkmobile(this.user);
      this.userMsg.mobile = data;
    },
    //Check password
    checkpassword1() {
      if (this.user.p1 == "") {
        this.userMsg.password1 = {
          code: 0,
          message: "Password cannot be empty"
        };
      }
    },
    //Verify confirm password
    checkpassword2() {
      if (this.user.p2 == "") {
        this.userMsg.password2 = {
          code: 0,
          message: "Confirm password cannot be empty"
        };
      } else if (this.user.p2 != this.user.p1) {
        this.userMsg.password2 = {
          code: 0,
          message: "The two passwords are inconsistent"
        };
      }
    },
    async sendSms() {
      //Simple check
      if (!this.user.username) {
        this.userMsg.username = {
          code: 0,
          message: "User name cannot be empty"
        };
        return;
      }
      if (!this.user.mobile) {
        this.userMsg.mobile = {
          code: 0,
          message: "Mobile number cannot be empty"
        };
        return;
      }

      //Count down
      //Button status becomes unavailable
      this.btnDisabled = true;
      this.timer = setInterval(() => {
        //Less than 1 reset
        if (this.senconds <= 1) {
          //Button back to available
          this.btnDisabled = false;
          //off timer 
          clearInterval(this.timer);
        } else {
          this.senconds--;
        }
      }, 1000);

      //Continue sending
      let { data } = await this.$request.sendSms(this.user);
      if (data.code == 1) {
        //Send successfully
        alert(data.message);
      } else {
        //error message
        this.userMsg.code = data.message;
      }
    },
    async register() {
      let { data } = await this.$request.register(this.user);
      if (data.code == 1) {
        this.$router.push("/login");
      } else {
        this.userMsg.smsData = data;
      }
    }
  }
};
</script>

<style>
</style>

api.js

//Custom function
const request = {
    //checkUsername
    checkUsername: (username) => {
        return axios.post('/cgwebservice/user/checkusername', { username })
    },
    //checkmobile
    checkmobile: (user) => {
        return axios.post('/cgwebservice/user/checkmobile', user)
    },
    //Send verification code
    sendSms: (user) => {
        return axios.post('/cgwebservice/sms', user)
    },
    register: (user) => {
        return axios.post('/cgwebservice/user/register', user)
    }
}

var axios = null
export default ({ $axios }, inject) => {

    //3) Save built-in axios
    axios = $axios

    //4) Hand over the custom function to nuxt
    // Usage 1: in vue, this.$request.xxx()
    // Usage 2: in asyncData of nuxt, content.app.$request.xxx()

    inject('request', request)
}

Posted by nexgen_x on Fri, 27 Mar 2020 08:14:08 -0700