Add token management

This commit is contained in:
Ben Adrian Sarmiento
2024-06-28 13:19:09 +02:00
parent 962845fb81
commit c3aea427d0
9 changed files with 100 additions and 114 deletions

View File

@@ -13,7 +13,7 @@ type Token struct {
type DownloadTokenManager struct {
tokens []Token
current int
mu sync.Mutex
mu sync.RWMutex
}
// NewDownloadTokenManager initializes a new DownloadTokenManager with the given tokens.
@@ -27,8 +27,8 @@ func NewDownloadTokenManager(tokenStrings []string) *DownloadTokenManager {
// GetCurrentToken returns the current non-expired token.
func (dtm *DownloadTokenManager) GetCurrentToken() (string, error) {
dtm.mu.Lock()
defer dtm.mu.Unlock()
dtm.mu.RLock()
defer dtm.mu.RUnlock()
for {
if !dtm.tokens[dtm.current].expired {
@@ -43,13 +43,19 @@ func (dtm *DownloadTokenManager) GetCurrentToken() (string, error) {
}
}
// SetCurrentTokenExpired sets the current token as expired.
func (dtm *DownloadTokenManager) SetCurrentTokenExpired() {
// SetTokenAsExpired sets the specified token as expired.
func (dtm *DownloadTokenManager) SetTokenAsExpired(token string) error {
dtm.mu.Lock()
defer dtm.mu.Unlock()
dtm.tokens[dtm.current].expired = true
dtm.current = (dtm.current + 1) % len(dtm.tokens)
for i, t := range dtm.tokens {
if t.value == token {
dtm.tokens[i].expired = true
return nil
}
}
return fmt.Errorf("token not found")
}
// ResetAllTokens resets all tokens to expired=false.