MCPcopy
hub / github.com/crowdsecurity/crowdsec / LoadAPICToken

Method LoadAPICToken

pkg/database/token.go:29–62  ·  view source on GitHub ↗

LoadAPICToken attempts to retrieve and validate a JWT token from the local database. Errors are returned if the token can't be read, is not valid, expired or has no expiration.

(ctx context.Context, logger logrus.FieldLogger)

Source from the content-addressed store, hash-verified

27// LoadAPICToken attempts to retrieve and validate a JWT token from the local database.
28// Errors are returned if the token can't be read, is not valid, expired or has no expiration.
29func (c *Client) LoadAPICToken(ctx context.Context, logger logrus.FieldLogger) (APICToken, error) {
30 token, err := c.GetConfigItem(ctx, APICTokenKey) // TokenKey is a constant string representing the key for the token in the database
31 if err != nil {
32 return APICToken{}, fmt.Errorf("loading token: %w", err)
33 }
34
35 if token == "" {
36 return APICToken{}, ErrTokenNotFound
37 }
38
39 parser := new(jwt.Parser)
40
41 tok, _, err := parser.ParseUnverified(token, jwt.MapClaims{})
42 if err != nil {
43 return APICToken{}, fmt.Errorf("%w: %s", ErrTokenParse, err)
44 }
45
46 claims, ok := tok.Claims.(jwt.MapClaims)
47 if !ok {
48 return APICToken{}, ErrTokenParse
49 }
50
51 expFloat, ok := claims["exp"].(float64)
52 if !ok {
53 return APICToken{}, fmt.Errorf("%w: exp", ErrTokenMissingClaim)
54 }
55
56 exp := time.Unix(int64(expFloat), 0)
57 if time.Now().UTC().After(exp.Add(-1 * time.Minute)) {
58 return APICToken{}, ErrTokenExpired
59 }
60
61 return APICToken{Raw: token, ExpiresAt: exp}, nil
62}
63
64// SaveAPICToken stores the given JWT token in the local database under the appropriate config item.
65func (c *Client) SaveAPICToken(ctx context.Context, token string) error {

Callers 1

AuthenticateMethod · 0.80

Calls 2

GetConfigItemMethod · 0.95
AddMethod · 0.45

Tested by

no test coverage detected