Skip to content

Commit

Permalink
fix 🐛: fix expired oauth2 token
Browse files Browse the repository at this point in the history
Signed-off-by: Victor Hang <[email protected]>
  • Loading branch information
Banh-Canh committed Sep 22, 2024
1 parent 4cce289 commit fef60f5
Showing 1 changed file with 19 additions and 2 deletions.
21 changes: 19 additions & 2 deletions pkg/youtube/youtube_oauth2.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"os"
"os/exec"
"path/filepath"
"time"

"go.uber.org/zap"
"golang.org/x/oauth2"
Expand Down Expand Up @@ -68,6 +69,17 @@ func loadToken(filename string) (*oauth2.Token, error) {
return token, nil
}

// isTokenExpired checks if the token is expired.
func isTokenExpired(token *oauth2.Token) bool {
utils.Logger.Debug("Checking if token is expired.")
if token == nil || !token.Valid() || time.Now().After(token.Expiry) {
utils.Logger.Info("Token is expired or invalid.")
return true
}
utils.Logger.Debug("Token is valid.")
return false
}

// NewYouTubeAPI initializes the YouTube API by handling the OAuth2 flow.
func NewYouTubeAPI(clientID, clientSecret string) (chan *YouTubeAPI, error) {
utils.Logger.Info("Initializing YouTube API.", zap.String("client_id", clientID))
Expand All @@ -90,8 +102,13 @@ func NewYouTubeAPI(clientID, clientSecret string) (chan *YouTubeAPI, error) {
defer close(apiChan)
utils.Logger.Debug("Loading OAuth2 token.")
token, err := loadToken(tokenFile)
if err != nil {
utils.Logger.Error("Failed to load token.", zap.String("token_file", tokenFile), zap.Error(err))
if err != nil || isTokenExpired(token) {
// If token loading fails or token is expired, start OAuth flow
if err != nil {
utils.Logger.Error("Failed to load token.", zap.String("token_file", tokenFile), zap.Error(err))
} else {
utils.Logger.Info("Token is expired. Starting OAuth2 flow.")
}
utils.Logger.Debug("Starting OAuth2 flow.")
if startOAuthErr = startOAuthFlow(config, apiChan, tokenFile); startOAuthErr != nil {
utils.Logger.Error("OAuth2 flow failed.", zap.Error(startOAuthErr))
Expand Down

0 comments on commit fef60f5

Please sign in to comment.