Skip to content

Commit 83aa4ca

Browse files
committed
Refactor authentication token management and logging
1 parent da2c1db commit 83aa4ca

File tree

4 files changed

+24
-21
lines changed

4 files changed

+24
-21
lines changed

internal/httpclient/http_client_auth_token_management.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,12 +21,12 @@ func (c *Client) ValidAuthTokenCheck(log logger.Logger) (bool, error) {
2121
if c.Token == "" {
2222
c.Logger.Debug("No token found, attempting to obtain a new one")
2323
if c.AuthMethod == "bearer" {
24-
err := c.ObtainToken()
24+
err := c.ObtainToken(log)
2525
if err != nil {
2626
return false, c.Logger.Error("Failed to obtain bearer token", zap.Error(err))
2727
}
2828
} else if c.AuthMethod == "oauth" {
29-
if err := c.ObtainOAuthToken(c.config.Auth); err != nil {
29+
if err := c.ObtainOAuthToken(c.config.Auth, log); err != nil {
3030
return false, c.Logger.Error("Failed to obtain OAuth token", zap.Error(err))
3131
}
3232
} else {
@@ -37,9 +37,9 @@ func (c *Client) ValidAuthTokenCheck(log logger.Logger) (bool, error) {
3737
if time.Until(c.Expiry) < c.config.TokenRefreshBufferPeriod {
3838
var err error
3939
if c.BearerTokenAuthCredentials.Username != "" && c.BearerTokenAuthCredentials.Password != "" {
40-
err = c.RefreshToken()
40+
err = c.RefreshToken(log)
4141
} else if c.OAuthCredentials.ClientID != "" && c.OAuthCredentials.ClientSecret != "" {
42-
err = c.ObtainOAuthToken(c.config.Auth)
42+
err = c.ObtainOAuthToken(c.config.Auth, log)
4343
} else {
4444
return false, c.Logger.Error("Unknown auth method", zap.String("authMethod", c.AuthMethod))
4545
}

internal/httpclient/http_client_bearer_token_auth.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ func (c *Client) SetBearerTokenAuthCredentials(credentials BearerTokenAuthCreden
2828

2929
// ObtainToken fetches and sets an authentication token using the stored basic authentication credentials.
3030
func (c *Client) ObtainToken(log logger.Logger) error {
31-
authenticationEndpoint := c.ConstructAPIAuthEndpoint(BearerTokenEndpoint)
31+
authenticationEndpoint := APIHandler.ConstructAPIAuthEndpoint(BearerTokenEndpoint)
3232

3333
log.Debug("Attempting to obtain token for user", zap.String("Username", c.BearerTokenAuthCredentials.Username))
3434

internal/httpclient/http_client_defaultconfig.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,12 @@ package httpclient
22

33
import (
44
"time"
5+
6+
"github.com/deploymenttheory/go-api-http-client/internal/logger"
57
)
68

79
const (
8-
DefaultLogLevel = LogLevelInfo
10+
DefaultLogLevel = logger.LogLevelInfo
911
DefaultMaxRetryAttempts = 3
1012
DefaultEnableDynamicRateLimiting = true
1113
DefaultMaxConcurrentRequests = 5

internal/httpclient/http_client_oauth.go

Lines changed: 16 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import (
1414
"strings"
1515
"time"
1616

17+
"github.com/deploymenttheory/go-api-http-client/internal/logger"
1718
"go.uber.org/zap"
1819
)
1920

@@ -41,32 +42,32 @@ func (c *Client) SetOAuthCredentials(credentials OAuthCredentials) {
4142

4243
// ObtainOAuthToken fetches an OAuth access token using the provided OAuthCredentials (Client ID and Client Secret).
4344
// It updates the client's Token and Expiry fields with the obtained values.
44-
func (c *Client) ObtainOAuthToken(credentials AuthConfig) error {
45+
func (c *Client) ObtainOAuthToken(credentials AuthConfig, log logger.Logger) error {
4546
authenticationEndpoint := c.ConstructAPIAuthEndpoint(OAuthTokenEndpoint)
4647
data := url.Values{}
4748
data.Set("client_id", credentials.ClientID)
4849
data.Set("client_secret", credentials.ClientSecret)
4950
data.Set("grant_type", "client_credentials")
5051

51-
c.logger.Debug("Attempting to obtain OAuth token", zap.String("ClientID", credentials.ClientID))
52+
log.Debug("Attempting to obtain OAuth token", zap.String("ClientID", credentials.ClientID))
5253

5354
req, err := http.NewRequest("POST", authenticationEndpoint, strings.NewReader(data.Encode()))
5455
if err != nil {
55-
c.logger.Error("Failed to create request for OAuth token", zap.Error(err))
56+
log.Error("Failed to create request for OAuth token", zap.Error(err))
5657
return err
5758
}
5859
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
5960

6061
resp, err := c.httpClient.Do(req)
6162
if err != nil {
62-
c.logger.Error("Failed to execute request for OAuth token", zap.Error(err))
63+
log.Error("Failed to execute request for OAuth token", zap.Error(err))
6364
return err
6465
}
6566
defer resp.Body.Close()
6667

6768
bodyBytes, err := io.ReadAll(resp.Body)
6869
if err != nil {
69-
c.logger.Error("Failed to read response body", zap.Error(err))
70+
log.Error("Failed to read response body", zap.Error(err))
7071
return err
7172
}
7273

@@ -76,23 +77,23 @@ func (c *Client) ObtainOAuthToken(credentials AuthConfig) error {
7677
oauthResp := &OAuthResponse{}
7778
err = json.Unmarshal(bodyBytes, oauthResp)
7879
if err != nil {
79-
c.logger.Error("Failed to decode OAuth response", zap.Error(err))
80+
log.Error("Failed to decode OAuth response", zap.Error(err))
8081
return err
8182
}
8283

8384
if oauthResp.Error != "" {
84-
c.logger.Error("Error obtaining OAuth token", zap.String("Error", oauthResp.Error))
85+
log.Error("Error obtaining OAuth token", zap.String("Error", oauthResp.Error))
8586
return fmt.Errorf("error obtaining OAuth token: %s", oauthResp.Error)
8687
}
8788

8889
if oauthResp.AccessToken == "" {
89-
c.logger.Error("Empty access token received")
90+
log.Error("Empty access token received")
9091
return fmt.Errorf("empty access token received")
9192
}
9293

9394
expiresIn := time.Duration(oauthResp.ExpiresIn) * time.Second
9495
expirationTime := time.Now().Add(expiresIn)
95-
c.logger.Info("OAuth token obtained successfully", zap.String("AccessToken", oauthResp.AccessToken), zap.Duration("ExpiresIn", expiresIn), zap.Time("ExpirationTime", expirationTime))
96+
log.Info("OAuth token obtained successfully", zap.String("AccessToken", oauthResp.AccessToken), zap.Duration("ExpiresIn", expiresIn), zap.Time("ExpirationTime", expirationTime))
9697

9798
c.Token = oauthResp.AccessToken
9899
c.Expiry = expirationTime
@@ -102,32 +103,32 @@ func (c *Client) ObtainOAuthToken(credentials AuthConfig) error {
102103

103104
// InvalidateOAuthToken invalidates the current OAuth access token.
104105
// After invalidation, the token cannot be used for further API requests.
105-
func (c *Client) InvalidateOAuthToken() error {
106+
func (c *Client) InvalidateOAuthToken(log logger.Logger) error {
106107
invalidateTokenEndpoint := c.ConstructAPIAuthEndpoint(TokenInvalidateEndpoint)
107108

108-
c.logger.Debug("Attempting to invalidate OAuth token", zap.String("Endpoint", invalidateTokenEndpoint))
109+
log.Debug("Attempting to invalidate OAuth token", zap.String("Endpoint", invalidateTokenEndpoint))
109110

110111
req, err := http.NewRequest("POST", invalidateTokenEndpoint, nil)
111112
if err != nil {
112-
c.logger.Error("Failed to create new request for token invalidation", zap.Error(err))
113+
log.Error("Failed to create new request for token invalidation", zap.Error(err))
113114
return err
114115
}
115116
req.Header.Add("Authorization", "Bearer "+c.Token)
116117

117118
resp, err := c.httpClient.Do(req)
118119
if err != nil {
119-
c.logger.Error("Failed to make request for token invalidation", zap.Error(err))
120+
log.Error("Failed to make request for token invalidation", zap.Error(err))
120121
return err
121122
}
122123
defer resp.Body.Close()
123124

124125
if resp.StatusCode != http.StatusNoContent {
125126
errMsg := fmt.Errorf("failed to invalidate token, status code: %d", resp.StatusCode)
126-
c.logger.Error("Failed to invalidate OAuth token", zap.Int("StatusCode", resp.StatusCode), zap.Error(errMsg))
127+
log.Error("Failed to invalidate OAuth token", zap.Int("StatusCode", resp.StatusCode), zap.Error(errMsg))
127128
return errMsg
128129
}
129130

130-
c.logger.Info("OAuth token invalidated successfully", zap.String("Endpoint", invalidateTokenEndpoint))
131+
log.Info("OAuth token invalidated successfully", zap.String("Endpoint", invalidateTokenEndpoint))
131132

132133
return nil
133134
}

0 commit comments

Comments
 (0)