forked from deploymenttheory/go-api-sdk-jamfpro
-
Notifications
You must be signed in to change notification settings - Fork 0
/
http_client_auth_token_management.go
56 lines (49 loc) · 1.69 KB
/
http_client_auth_token_management.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// http_client_auth_token_management.go
package http_client
import (
"fmt"
"time"
)
// TokenResponse represents the structure of a token response from the API.
type TokenResponse struct {
Token string `json:"token"`
Expires time.Time `json:"expires"`
}
// ValidAuthTokenCheck checks if the current token is valid and not close to expiry.
// If the token is invalid, it tries to refresh it.
// It returns a boolean indicating the validity of the token and an error if there's a failure.
func (c *Client) ValidAuthTokenCheck() (bool, error) {
if c.Token == "" {
if c.AuthMethod == "bearer" {
err := c.ObtainToken()
if err != nil {
return false, fmt.Errorf("failed to obtain bearer token: %w", err)
}
} else if c.AuthMethod == "oauth" {
err := c.ObtainOAuthToken(c.config.Auth)
if err != nil {
return false, fmt.Errorf("failed to obtain OAuth token: %w", err)
}
} else {
return false, fmt.Errorf("no valid credentials provided. Unable to obtain a token")
}
}
// If token exists and is close to expiry or already expired
if time.Until(c.Expiry) < c.config.TokenRefreshBufferPeriod {
var err error
if c.AuthMethod == "bearer" {
err = c.RefreshToken()
} else if c.AuthMethod == "oauth" {
err = c.ObtainOAuthToken(c.config.Auth)
} else {
return false, fmt.Errorf("unknown auth method: %s", c.AuthMethod)
}
if err != nil {
return false, fmt.Errorf("failed to refresh token: %w", err)
}
}
if time.Until(c.Expiry) < c.config.TokenRefreshBufferPeriod {
return false, fmt.Errorf("token lifetime setting less than buffer. Buffer setting: %v, Time (seconds) until Exp: %v", c.config.TokenRefreshBufferPeriod, time.Until(c.Expiry))
}
return true, nil
}