1、登录接口的路由
2、获取参数并验证参数
3、验证手机号是否存在
4、判断密码是否正确
5、给前端返回token
6、返回结果
7、测试
8、bcrypt使用对密码进行加密解密(gin自动导入包)
加密:
解密:
验证:
10、总结(整体代码)
路由:
r.POST("/api/auth/login", controller.Login)
控制器代码:
func Login(c *gin.Context) { //引入DB DB := commom.GetDB() // 获取参数(手机号和密码) telephone := c.PostForm("telephone") password := c.PostForm("password") //对接受的数据进行验证 if len(telephone) != 11 { c.JSON(http.StatusUnprocessableEntity, gin.H{"code": 422, "msg": "手机号必须是11位"}) return } if len(password) < 6 { c.JSON(http.StatusUnprocessableEntity, gin.H{"code": 422, "msg": "密码不能少于6位"}) return } // 判断手机号是否存在 var user model.User DB.Where("telephone=?", telephone).First(&user) if user.ID == 0 { c.JSON(http.StatusUnprocessableEntity, gin.H{"code": 422, "msg": "用户不存在"}) return } // 判断密码是否正确 if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); err != nil { c.JSON(http.StatusBadRequest, gin.H{"code": 400, "msg": "密码错误"}) return } //返回token token := "123" // 返回结果 c.JSON(200, gin.H{ "code": 200, "data": gin.H{"token": token}, "msg": "登录成功", }) }