jwt.go 951 字节
package contextdata

import (
	"context"
	"github.com/golang-jwt/jwt/v4"
	"time"
)

type UserToken struct {
	UserId     int64
	CompanyId  int64
	EmployeeId int64
}

func (tk UserToken) GenerateToken(secret string, expire int64) (string, error) {
	claims := make(jwt.MapClaims)
	claims["exp"] = time.Now().Unix() + expire
	claims["iat"] = time.Now().Unix()
	claims[CtxKeyJwtUserId] = tk.UserId
	claims[CtxKeyJwtCompanyId] = tk.CompanyId
	claims[CtxKeyJwtEmployeeId] = tk.EmployeeId

	token := jwt.New(jwt.SigningMethodHS256)
	token.Claims = claims

	return token.SignedString([]byte(secret))
}

func ParseToken(ctx context.Context, secret string, tokenStr string) (context.Context, error) {
	token, err := jwt.Parse(tokenStr, func(token *jwt.Token) (interface{}, error) {
		return []byte(secret), nil
	})
	if err != nil {
		return ctx, err
	}
	for k, v := range token.Claims.(jwt.MapClaims) {
		ctx = context.WithValue(ctx, k, v)
	}
	return ctx, nil
}