github.com/machinefi/w3bstream@v1.6.5-rc9.0.20240426031326-b8c7c4876e72/pkg/depends/conf/jwt/jwt.go (about)

     1  package jwt
     2  
     3  import (
     4  	"time"
     5  
     6  	"github.com/golang-jwt/jwt/v4"
     7  
     8  	"github.com/machinefi/w3bstream/pkg/depends/base/types"
     9  )
    10  
    11  type Jwt struct {
    12  	Issuer  string         `env:""`
    13  	ExpIn   types.Duration `env:""`
    14  	SignKey string         `env:""`
    15  	// Method  SigningMethod  `env:""`
    16  }
    17  
    18  func (c *Jwt) SetDefault() {}
    19  
    20  func (c *Jwt) Init() {
    21  	if c.ExpIn == 0 {
    22  		c.ExpIn = types.Duration(time.Hour)
    23  	}
    24  	if c.SignKey == "" {
    25  		c.SignKey = "xxxx" // stringsx.GenRandomVisibleString(16)
    26  	}
    27  }
    28  
    29  func (c *Jwt) ExpiresAt() *jwt.NumericDate {
    30  	if c.ExpIn == 0 {
    31  		return nil
    32  	}
    33  	return &jwt.NumericDate{Time: time.Now().UTC().Add(c.ExpIn.Duration())}
    34  }
    35  
    36  func (c *Jwt) GenerateTokenByPayload(payload interface{}) (string, error) {
    37  	claim := &Claims{
    38  		Payload: payload,
    39  		RegisteredClaims: jwt.RegisteredClaims{
    40  			ExpiresAt: c.ExpiresAt(),
    41  			Issuer:    c.Issuer,
    42  		},
    43  	}
    44  	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claim)
    45  	return token.SignedString([]byte(c.SignKey))
    46  }
    47  
    48  func (c *Jwt) GenerateTokenWithoutExpByPayload(payload interface{}) (string, error) {
    49  	claim := &Claims{
    50  		Payload: payload,
    51  		RegisteredClaims: jwt.RegisteredClaims{
    52  			ExpiresAt: nil,
    53  			Issuer:    c.Issuer,
    54  		},
    55  	}
    56  	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claim)
    57  	return token.SignedString([]byte(c.SignKey))
    58  }
    59  
    60  func (c *Jwt) ParseToken(v string) (*Claims, error) {
    61  	t, err := jwt.ParseWithClaims(
    62  		v,
    63  		&Claims{},
    64  		func(token *jwt.Token) (interface{}, error) {
    65  			return []byte(c.SignKey), nil
    66  		},
    67  	)
    68  	if err != nil {
    69  		return nil, InvalidToken.StatusErr().WithDesc(err.Error())
    70  	}
    71  	if t == nil {
    72  		return nil, InvalidToken
    73  	}
    74  	claim, ok := t.Claims.(*Claims)
    75  	if !ok || !t.Valid {
    76  		return nil, InvalidClaim
    77  	}
    78  	return claim, nil
    79  }
    80  
    81  type Claims struct {
    82  	Payload interface{}
    83  	jwt.RegisteredClaims
    84  }