Skip to content

Commit

Permalink
ref: isTokenAboutToExpire for clarity and maintainability
Browse files Browse the repository at this point in the history
Signed-off-by: guipguia <[email protected]>
  • Loading branch information
guipguia committed Jul 29, 2024
1 parent ccdd0c3 commit 6302af7
Showing 1 changed file with 32 additions and 21 deletions.
53 changes: 32 additions & 21 deletions backend/cmd/headlamp.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,8 @@ const ContextCacheTTL = 5 * time.Minute // minutes

const ContextUpdateChacheTTL = 20 * time.Second // seconds

const JWTExpirationTTL = 10 * time.Second // seconds

type clientConfig struct {
Clusters []Cluster `json:"clusters"`
IsDyanmicClusterEnabled bool `json:"isDynamicClusterEnabled"`
Expand Down Expand Up @@ -685,41 +687,50 @@ func parseClusterAndToken(r *http.Request) (string, string) {
return cluster, token
}

func isTokenAboutToExpire(token string) bool {
const TokenParts = 3

// parse expiry time from token
parts := strings.Split(token, ".")
if len(parts) != TokenParts {
return false
func decodePayload(payload string) (map[string]interface{}, error) {
payloadBytes, err := base64.RawStdEncoding.DecodeString(payload)
if err != nil {
return nil, err
}

payloadPart := parts[1]
var payloadMap map[string]interface{}
if err := json.Unmarshal(payloadBytes, &payloadMap); err != nil {
return nil, err
}

payloadBytes, err := base64.RawStdEncoding.DecodeString(payloadPart)
if err != nil {
logger.Log(logger.LevelError, nil, err, "failed to decode payload")
return payloadMap, nil
}

return false
func getExpiryTime(payload map[string]interface{}) (time.Time, error) {
exp, ok := payload["exp"].(float64)
if !ok {
return time.Time{}, errors.New("expiry time not found or invalid")
}

var payload map[string]interface{}
if err := json.Unmarshal(payloadBytes, &payload); err != nil {
logger.Log(logger.LevelError, nil, err, "failed to unmarshal payload")
return time.Unix(int64(exp), 0), nil
}

func isTokenAboutToExpire(token string) bool {
const tokenParts = 3

parts := strings.Split(token, ".")
if len(parts) != tokenParts {
return false
}

// check if token is expired
exp, ok := payload["exp"].(float64)
if !ok {
payload, err := decodePayload(parts[1])
if err != nil {
logger.Log(logger.LevelError, nil, err, "failed to decode payload")
return false
}

// if token is not about to expire, then skip
expTime := time.Unix(int64(exp), 0)
expiryTime, err := getExpiryTime(payload)
if err != nil {
logger.Log(logger.LevelError, nil, err, "failed to get expiry time")
return false
}

return time.Until(expTime) <= time.Second*10
return time.Until(expiryTime) <= JWTExpirationTTL
}

//nolint:funlen
Expand Down

0 comments on commit 6302af7

Please sign in to comment.