package ceshi
import (
"time"
"github.com/brianvoe/sjwt"
"github.com/gin-gonic/gin"
)
var CeshiController *ceshiController
type ceshiController struct{}
func (*ceshiController) CreateToken(ctx *gin.Context) {
claims := sjwt.New()
claims.SetTokenID() // UUID generated
claims.SetSubject("Subject Title") // Subject of the token
claims.SetIssuer("Google") // Issuer of the token
claims.SetAudience([]string{"Google", "Facebook"}) // Audience the toke is for
claims.SetIssuedAt(time.Now()) // 签发时间
claims.SetNotBeforeAt(time.Now()) // 生效时间
claims.SetExpiresAt(time.Now().Add(time.Hour * 24 * 365)) // Token expires in 1 year
claims.Set("user_id", 100) //PublicClaims
jwt_secret := []byte("123456")
jwt := claims.Generate(jwt_secret)
ctx.JSON(200, jwt)
}
func (*ceshiController) ParseToken(ctx *gin.Context) {
jwt_secret := []byte("123456")
jwt := ctx.Request.Header.Get("Authorization")
//jwt := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsiR29vZ2xlIiwiRmFjZWJvb2siXSwiZXhwIjoxNzIxODA1ODAzLCJpYXQiOjE2OTAyNjk4MDMsImlzcyI6Ikdvb2dsZSIsImp0aSI6ImRhZTZkMjQyLWMyZDgtNDUzMS1iNzhmLWRiMjQzNDUxZjFkZSIsIm5iZiI6MTY5MDI2OTgwMywic3ViIjoiU3ViamVjdCBUaXRsZSIsInVzZXJfaWQiOjEwMH0.JRh3igLvHKggfZxqwa6EdXFCJEvzITjKbDvGzPofDok"
if jwt == "" {
ctx.JSON(400, "令牌不能为空")
return
}
// 验证token
ok := sjwt.Verify(jwt, jwt_secret)
if !ok {
ctx.JSON(400, "令牌验证失败")
return
}
//解析token
claims, err := sjwt.Parse(jwt)
if err != nil {
ctx.JSON(400, "令牌解析错误")
return
}
//验证token是否过期
err = claims.Validate()
if err != nil {
ctx.JSON(400, err.Error())
return
}
user_id, _ := claims.GetInt("user_id")
//ctx.Set("user_id", user_id)
var data = make(map[string]any, 0)
data["user_id"] = user_id
ctx.JSON(200, data)
}