当前位置:网站首页>7. development of mobile login function

7. development of mobile login function

2022-06-30 09:57:00 xjhqre

Mobile login function development

It is difficult to apply for SMS service , The function of sending text messages is not done . Verification code directly with log Print it out in the form of a log .

1、 Sort out the interaction process

  1. On the login page (front/ page/login.html) Enter phone number , Click on 【 Get verification code 】 Button , Page sending ajax request , Call the SMS service at the server API Send verification code SMS to the specified mobile phone number
  2. Enter the verification code on the login page , Click on 【 land 】 Button , send out ajax request , Handle the login request on the server

2、 preparation

Create basic classes and interfaces :

  • Entity class User( Import directly from the course materials )
  • Mapper Interface UserMapper
  • Business layer interface UserService
  • Business layer implementation classes UserServicelmpl
  • Control layer UserController
  • Tool class SMSutils、ValidateCodeutils ( Import directly from the course materials )

2.1、 modify LoginCheckFilter

When we log in with the mobile verification code , Requests sent need to be released directly when processed by this filter

modify LoginCheckFilter Of doFilter There are two ways .

image-20220624134238780

Add "judge mobile user login" under "judge user login"

image-20220623164842489

// 4.2  Determine whether to log in for mobile phone users 
if (request.getSession().getAttribute("user") != null) {
    
    log.info(" Mobile user has logged in , user id by :{}", request.getSession().getAttribute("user"));

    Long userId = (Long) request.getSession().getAttribute("user");
    BaseContext.setCurrentId(userId);

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

3、 Simulate sending SMS

stay UserController Created in sendMsg Method to simulate SMS sending

package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
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.servlet.http.HttpSession;
import java.util.Map;

/** * @Author: xjhqre * @DateTime: 2022/6/15 16:50 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    

    @Autowired
    private UserService userService;

    /** *  Send SMS verification code  * @param user * @return */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) {
    
        //  Get cell phone number 
        String phone = user.getPhone();

        if(StringUtils.isNotEmpty(phone)) {
    
            //  Generate random 4 Bit verification code 
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("4 The bit verification code is :{}", code);

            //  Call the SMS service provided by Alibaba cloud API Finish sending SMS 
            //...

            //  Save the generated verification code to Session
            session.setAttribute(phone, code);

            return R.success(" Mobile phone verification code SMS sent successfully ");
        }


        return R.error(" SMS sending failed ");
    }

    @PostMapping("/login")
    public R<String> login(@RequestBody Map<String, String> map, HttpSession session) {
    
        log.info(map.toString());
        return R.error(" Login failed ");
    }

    
}

3.1、 Modify the front page ( Optional )

The mobile landing page given in the course materials , Click send verification code and it will be directly displayed in the form , There is no back-end interface . The following is the method to request the back-end interface instead

1、 stay front/api/login.js Add in sendMsgApi Method

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

2、 And then modify front/page/login.html page

image-20220624125902437

3.2、 Test Click to get the verification code

4、 Landing function

Input the verification code on the front-end login page and click login to send the request

image-20220624135501897

stay UserController Write the login method login

@PostMapping("/login")
public R<User> login(@RequestBody Map map, HttpSession session) {
    
    log.info(map.toString());

    //  Get cell phone number 
    String phone = map.get("phone").toString();

    //  Get the verification code entered by the user 
    String code = map.get("code").toString();

    //  from Session Get the saved verification code from 
    String sessionCode = (String) session.getAttribute(phone);

    //  Verification code verification 
    if(sessionCode != null && sessionCode.equals(code)) {
    
        //  After successful verification, determine whether the user is logging in for the first time , It needs to be saved to the database 
        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); //  You can leave it blank , The default value of the database is 1
            userService.save(user);
        }
        session.setAttribute("user", user.getId());
        return R.success(user);
    }
    return R.error(" Login failed ");
}

4.1、 Test the login function

Follow the above steps to write the interface , Click the login button to find that there is only one parameter in the page request phone, Without code Parameters . The front-end request code needs to be modified

modify front/page/login.html On the page btnLogin The method can

image-20220624141728989

Test again and you will be successful

原网站

版权声明
本文为[xjhqre]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/181/202206300909168092.html