package jwts

import (
"fmt"
"github.com/dgrijalva/jwt-go"
"github.com/kataras/iris/v12"
"strings"
"time"
)



// 生成token
func (config *ClaimsConfigJson) TokenObtain() (string, error) {

config.IssuedAt = time.Now().Unix()
config.ExpiresAt = time.Now().Add(ExpireTime).Unix()

token := jwt.NewWithClaims(jwt.SigningMethodHS256, config)
signedToken, err := token.SignedString([]byte(SignKey))
if err != nil {

return "", err
}
return signedToken, nil
}

// =======================

// 刷新token
func (config *ClaimsConfigJson) tokenRefresh(ctx iris.Context) {
jwtObj := ctx.GetHeader("Authorization")
if jwtObj == "" {
_, _ = ctx.JSON("未登录或已失效")
return
}
StrToken := strings.Split(jwtObj, " ")[1]
token, err := jwt.ParseWithClaims(StrToken, &ClaimsConfigJson{}, func(token *jwt.Token) (interface{}, error) {
return []byte(SignKey), nil
})
if err != nil {
println(err)
return
}
claims, ok := token.Claims.(*ClaimsConfigJson)
if !ok {
println("test")
return
}
if err := token.Claims.Valid(); err != nil {
println(err)
return
}
claims.UserId = config.UserId
claims.ExpiresAt = time.Now().Unix() + (claims.ExpiresAt - claims.IssuedAt)

newToken := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
signedToken, err := newToken.SignedString([]byte(SignKey))
if err != nil {
println(err)
return
}
fmt.Println(signedToken)
}

// =====================

// 路由中间件
func JwtHandle(ctx iris.Context) {
jwtObj := ctx.GetHeader("Authorization")
if jwtObj == "" {
_, _ = ctx.JSON("未登录或已失效")
return
}
jwtStr := strings.Split(jwtObj, " ")[1]

token, err := jwt.ParseWithClaims(jwtStr, &ClaimsConfigJson{}, func(token *jwt.Token) (interface{}, error) {
return []byte(SignKey), nil
})
if err != nil {
_, _ = ctx.JSON("令牌已过期")
return
}
claims, ok := token.Claims.(*ClaimsConfigJson)
if !ok {
_, _ = ctx.JSON("解析用户数据错误")
return
}
if err := token.Claims.Valid(); err != nil {
_, _ = ctx.JSON("令牌已失效")
return
}
ctx.Values().Set(DataKey, claims)
ctx.Next()
}