1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
|
// 执行登录
func (this *Apiv1Controller) DoLogin() {
user := models.User{}
err := this.BindJSON(&user)
if err != nil {
this.Data["json"] = map[string]interface{}{
"status": 201,
"msg": "参数错误",
}
this.ServeJSON()
return
}
user2 := models.User{}
models.Db.Where("phone=?", user.Phone).Find(&user2)
if user2.Id == 0 {
this.Data["json"] = map[string]interface{}{
"status": 401,
"msg": "账号错误!",
}
this.ServeJSON()
return
}
// 账号验证通过,验证密码
md5Hash := models.Md5(user.Password)
if user2.Password != md5Hash {
this.Data["json"] = map[string]interface{}{
"status": 402,
"msg": "密码错误!",
}
this.ServeJSON()
return
}
// 密码和账号都正确登录成功
// 设置加密秘钥
hmacSampleSecret := []byte("12345aasdadzx")
//自定义结构体
type MyClaims struct {
Uid int
Phone string
jwt.StandardClaims
}
//token过期时间
expireTime := time.Now().Add(24 * time.Hour).Unix()
// 实例化自己定义的结构体
myClaim := MyClaims{
user2.Id,
user2.Phone,
jwt.StandardClaims{
ExpiresAt: expireTime,
},
}
// Create a new token object, specifying signing method and the claims
//创建token对象,指定签名方法和结构体
// you would like it to contain.
token := jwt.NewWithClaims(jwt.SigningMethodHS256, myToken)
// Sign and get the complete encoded token as a string using the secret
//使用自定义的秘钥签名生成一个token字符串,返回给客户端
tokenString, err := token.SignedString(hmacSampleSecret)
this.Data["json"] = map[string]interface{}{
"status": 200,
"msg": "登录成功!",
"data": map[string]interface{}{
"token": "Bearer " + tokenString,
"phone": user2.Phone,
},
}
this.ServeJSON()
}
|