后台用户登录验证功能是很多项目的必须要有的逻辑 , 也是常见的技术需求 .

要实现这个逻辑首先要有数据库表结构如下:

CREATE TABLE `user` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `name` varchar(50) NOT NULL DEFAULT '',
 `password` varchar(50) NOT NULL DEFAULT '',
 `nickname` varchar(50) NOT NULL DEFAULT '',
 `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
 `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
 `deleted_at` timestamp NULL DEFAULT NULL,
 `avator` varchar(100) NOT NULL DEFAULT '',
 PRIMARY KEY (`id`),
 KEY `idx_name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

gin框架路由入口去获取post的数据

func LoginCheckPass(c *gin.Context) {
  password := c.PostForm("password")
  username := c.PostForm("username")

  info, uRole, ok := CheckKefuPass(username, password)
  userinfo := make(map[string]interface{})
  if !ok {
    c.JSON(200, gin.H{
      "code": 400,
      "msg": "验证失败",
    })
    return
  }
  userinfo["name"] = info.Name
  userinfo["kefu_id"] = info.ID
  userinfo["type"] = "kefu"
  if uRole.RoleId != 0 {
    userinfo["role_id"] = uRole.RoleId
  } else {
    userinfo["role_id"] = 2
  }
  userinfo["create_time"] = time.Now().Unix()

  token, _ := tools.MakeToken(userinfo)
  userinfo["ref_token"] = true
  refToken, _ := tools.MakeToken(userinfo)
  c.JSON(200, gin.H{
    "code": 200,
    "msg": "验证成功,正在跳转",
    "result": gin.H{
      "token":    token,
      "ref_token":  refToken,
      "create_time": userinfo["create_time"],
    },
  })
}

先忽略掉生成token部分 ,只看查询数据库用户名密码部分

func CheckKefuPass(username string, password string) (models.User, models.User_role, bool) {
  info := models.FindUser(username)
  var uRole models.User_role
  if info.Name == "" || info.Password != tools.Md5(password) {
    return info, uRole, false
  }
  uRole = models.FindRoleByUserId(info.ID)

  return info, uRole, true
}

model里面

func FindUser(username string) User {
  var user User
  DB.Where("name = ", username).First(&user)
  return user
}
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!