Spaces:
Sleeping
Sleeping
File size: 2,194 Bytes
bb9df9e | 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 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 | package api
import (
"log"
"sublink/middlewares"
"sublink/models"
"sublink/utils"
"time"
"github.com/dgrijalva/jwt-go"
"github.com/gin-gonic/gin"
)
// 获取token
func GetToken(username string) (string, error) {
c := &middlewares.JwtClaims{
Username: username,
StandardClaims: jwt.StandardClaims{
ExpiresAt: time.Now().Add(time.Hour * 24 * 14).Unix(), // 设置14天过期
IssuedAt: time.Now().Unix(), // 签发时间
Subject: username, // 用户
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, c)
return token.SignedString(middlewares.Secret)
}
// 获取captcha图形验证码
func GetCaptcha(c *gin.Context) {
id, bs4, _, err := utils.GetCaptcha()
if err != nil {
log.Println("获取验证码失败")
c.JSON(400, gin.H{
"msg": "获取验证码失败",
})
return
}
c.JSON(200, gin.H{
"code": "00000",
"data": gin.H{
"captchaKey": id,
"captchaBase64": bs4,
},
"msg": "获取验证码成功",
})
}
// 用户登录
func UserLogin(c *gin.Context) {
username := c.PostForm("username")
password := c.PostForm("password")
captchaCode := c.PostForm("captchaCode")
captchaKey := c.PostForm("captchaKey")
// 验证验证码
if !utils.VerifyCaptcha(captchaKey, captchaCode) {
log.Println("验证码错误")
c.JSON(400, gin.H{
"msg": "验证码错误",
})
return
}
user := &models.User{Username: username, Password: password}
err := user.Verify()
if err != nil {
log.Println("账号或者密码错误")
c.JSON(400, gin.H{
"msg": "账号或者密码错误",
})
return
}
// 生成token
token, err := GetToken(username)
if err != nil {
log.Println("获取token失败")
c.JSON(400, gin.H{
"msg": "获取token失败",
})
return
}
// 登录成功返回token
c.JSON(200, gin.H{
"code": "00000",
"data": gin.H{
"accessToken": token,
"tokenType": "Bearer",
"refreshToken": nil,
"expires": nil,
},
"msg": "登录成功",
})
}
func UserOut(c *gin.Context) {
// 拿到jwt中的username
if _, Is := c.Get("username"); Is {
c.JSON(200, gin.H{
"code": "00000",
"msg": "退出成功",
})
}
}
|