github.com/dhax/go-base@v0.0.0-20231004214136-8be7e5c1972b/auth/jwt/claims.go (about)

     1  package jwt
     2  
     3  import (
     4  	"errors"
     5  
     6  	"github.com/lestrrat-go/jwx/v2/jwt"
     7  )
     8  
     9  type CommonClaims struct {
    10  	ExpiresAt int64 `json:"exp,omitempty"`
    11  	IssuedAt  int64 `json:"iat,omitempty"`
    12  }
    13  
    14  // AppClaims represent the claims parsed from JWT access token.
    15  type AppClaims struct {
    16  	ID    int      `json:"id,omitempty"`
    17  	Sub   string   `json:"sub,omitempty"`
    18  	Roles []string `json:"roles,omitempty"`
    19  	CommonClaims
    20  }
    21  
    22  // ParseClaims parses JWT claims into AppClaims.
    23  func (c *AppClaims) ParseClaims(claims map[string]interface{}) error {
    24  	id, ok := claims["id"]
    25  	if !ok {
    26  		return errors.New("could not parse claim id")
    27  	}
    28  	c.ID = int(id.(float64))
    29  
    30  	sub, ok := claims[jwt.SubjectKey]
    31  	if !ok {
    32  		return errors.New("could not parse claim sub")
    33  	}
    34  	c.Sub = sub.(string)
    35  
    36  	rl, ok := claims["roles"]
    37  	if !ok {
    38  		return errors.New("could not parse claims roles")
    39  	}
    40  
    41  	var roles []string
    42  	if rl != nil {
    43  		for _, v := range rl.([]interface{}) {
    44  			roles = append(roles, v.(string))
    45  		}
    46  	}
    47  	c.Roles = roles
    48  
    49  	return nil
    50  }
    51  
    52  // RefreshClaims represents the claims parsed from JWT refresh token.
    53  type RefreshClaims struct {
    54  	ID    int    `json:"id,omitempty"`
    55  	Token string `json:"token,omitempty"`
    56  	CommonClaims
    57  }
    58  
    59  // ParseClaims parses the JWT claims into RefreshClaims.
    60  func (c *RefreshClaims) ParseClaims(claims map[string]interface{}) error {
    61  	token, ok := claims["token"]
    62  	if !ok {
    63  		return errors.New("could not parse claim token")
    64  	}
    65  	c.Token = token.(string)
    66  	return nil
    67  }