GetValidToken returns a valid authentication token, refreshing if necessary. For API token authentication, this method returns a dummy AuthToken containing the API token string. For password authentication, this method returns the cached token if valid, or performs re-authentication if the token is
(ctx context.Context)
| 226 | // } |
| 227 | // // Use token for API requests |
| 228 | func (am *AuthManager) GetValidToken(ctx context.Context) (*AuthToken, error) { |
| 229 | if am.token != "" { |
| 230 | // Using API token authentication, return a dummy token |
| 231 | return &AuthToken{ |
| 232 | Ticket: am.token, |
| 233 | CSRFToken: "", |
| 234 | Username: "api-token", |
| 235 | ExpiresAt: time.Now().Add(24 * time.Hour), // API tokens don't expire |
| 236 | }, nil |
| 237 | } |
| 238 | |
| 239 | // Fast path: Check with read lock if token is valid |
| 240 | am.mu.RLock() |
| 241 | token := am.authToken |
| 242 | am.mu.RUnlock() |
| 243 | |
| 244 | if token != nil && token.IsValid() { |
| 245 | return token, nil |
| 246 | } |
| 247 | |
| 248 | // Token is invalid or missing, need to authenticate |
| 249 | // The authenticate() method handles concurrent calls with write lock |
| 250 | return am.authenticate(ctx) |
| 251 | } |
| 252 | |
| 253 | // authenticate performs the authentication flow with Proxmox API using username/password. |
| 254 | // |