hcmp/route/jwt.go
2024-07-31 15:47:50 +08:00

101 lines
2.2 KiB
Go

package route
import (
"errors"
"net/http"
"time"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt"
"github.com/shockliu/logger"
)
var (
jwtSecret = []byte("www.cnrehab.cn")
)
type devClaims struct {
User int `json:"user"` // 用户
jwt.StandardClaims
}
func CreateToken(user int) string {
// 生成token
claims := devClaims{
User: user,
StandardClaims: jwt.StandardClaims{
NotBefore: int64(time.Now().Unix() - 10), // 签名生效时间
// ExpiresAt: int64(time.Now().Unix() + 14*24*3600), // 签名过期时间
ExpiresAt: int64(time.Now().Unix() + 6*3600), // 签名过期时间
Issuer: "cnrehab.cn", // 签名颁发者
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
ts, err := token.SignedString(jwtSecret)
if err != nil {
logger.Error(err.Error())
return ""
}
return ts
}
// midware for token-auth
func TokenAuth() gin.HandlerFunc {
return func(c *gin.Context) {
ts := c.Request.Header.Get("Token")
if ts == "" {
logger.Warnf("请求未携带Token,无访问权限")
c.JSON(http.StatusOK, gin.H{
"code": 90001,
"msg": "请求未携带Token,无访问权限",
})
c.Abort()
return
}
// 解析token
claims, err := parseToken(ts)
if err == nil {
//fmt.Println("ParseToken:",claims)
c.Set("TK_User", claims.User)
return
} else {
// expired
logger.Warnf("Token失效,请重新登录")
logger.Debugf("测试token-1:%s\n", CreateToken(1))
c.JSON(http.StatusOK, gin.H{
"code": 90001,
"msg": "Token失效,请重新登录",
})
c.Abort()
}
}
}
/*
解析token
*/
func parseToken(tokenstring string) (*devClaims, error) {
token, err := jwt.ParseWithClaims(tokenstring, &devClaims{}, func(token *jwt.Token) (any, error) {
return jwtSecret, nil
})
if err != nil {
return nil, errors.New("Token不可用")
}
if claims, ok := token.Claims.(*devClaims); ok && token.Valid {
//fmt.Println("ParseToken:",claims,ok)
return claims, nil
}
return nil, errors.New("token无效")
}
func FreshToken(c *gin.Context) {
user := c.MustGet("TK_User").(int)
ts := CreateToken(user)
logger.Debugf("刷新Token成功:%d-%s\n", user, ts)
c.JSON(http.StatusOK, gin.H{
"code": 0,
"token": ts,
})
}