The GO language gin framework implements the administrator authentication login interface

  • 2020-11-18 06:17:25
  • OfStack

Background user login verification function is a necessary logic for many projects, but also a common technical requirement.

To implement this logic, you first need to have the following database table structure:


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

The gin framework routes the entry to fetch post data


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": " Validation fails ",
    })
    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": " Authentication is successful , Is the jump ",
    "result": gin.H{
      "token":    token,
      "ref_token":  refToken,
      "create_time": userinfo["create_time"],
    },
  })
}

Ignore the generation of token and just look at the query database username and password section


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 inside


func FindUser(username string) User {
  var user User
  DB.Where("name = ?", username).First(&user)
  return user
}

Related articles: