internal/auth_token.go

110 lines · 3465 bytes

  1package internal
  2
  3import (
  4	"fmt"
  5	"net/http"
  6	"os"
  7	"path/filepath"
  8	"strings"
  9)
 10
 11func isInvalidTokenResponse(statusCode int, body []byte) bool {
 12	lower := strings.ToLower(string(body))
 13	if strings.Contains(lower, "invalid token") || strings.Contains(lower, "invalid_token") {
 14		return true
 15	}
 16	return statusCode == http.StatusUnauthorized
 17}
 18
 19func isInvalidTokenError(err error) bool {
 20	if err == nil {
 21		return false
 22	}
 23	lower := strings.ToLower(err.Error())
 24	return strings.Contains(lower, "invalid token") || strings.Contains(lower, "invalid_token")
 25}
 26
 27func anilistTokenPath(config *CurdConfig) string {
 28	return filepath.Join(os.ExpandEnv(config.StoragePath), "anilist_token.json")
 29}
 30
 31// anilistTokenForAPI resolves the real AniList access token for GraphQL calls.
 32// Callers pass the tracker token (user.Token), which is the MyAnimeList token
 33// when tracking is configured as myanimelist/both; AniList rejects that with
 34// "Invalid token", which the app misread as expiry and forced a browser
 35// re-auth on every run. Prefer the token persisted at anilist_token.json and
 36// fall back to the caller's token only when none is stored.
 37func anilistTokenForAPI(config *CurdConfig, current string) string {
 38	if config == nil {
 39		config = GetGlobalConfig()
 40	}
 41	if config != nil && strings.TrimSpace(config.StoragePath) != "" {
 42		if stored, err := GetTokenFromFile(anilistTokenPath(config)); err == nil && strings.TrimSpace(stored) != "" {
 43			return stored
 44		}
 45	}
 46	return current
 47}
 48
 49func ReauthenticateAniList(config *CurdConfig, user *User, reason string) (string, error) {
 50	if config == nil {
 51		config = GetGlobalConfig()
 52	}
 53	if config == nil {
 54		return "", fmt.Errorf("missing config for AniList reauthentication")
 55	}
 56
 57	tokenPath := anilistTokenPath(config)
 58	if reason != "" {
 59		CurdOut(fmt.Sprintf("AniList sign-in required (%s). Opening browser...", reason))
 60		Log(fmt.Sprintf("AniList token invalid (%s), starting browser authentication", reason))
 61	} else {
 62		CurdOut("AniList sign-in required. Opening browser...")
 63		Log("AniList token invalid, starting browser authentication")
 64	}
 65
 66	if err := os.Remove(tokenPath); err != nil && !os.IsNotExist(err) {
 67		Log(fmt.Sprintf("Failed to clear stale AniList token file: %v", err))
 68	}
 69
 70	accessToken, err := authenticateWithBrowser(tokenPath)
 71	if err != nil {
 72		return "", err
 73	}
 74
 75	if user != nil {
 76		user.Token = accessToken
 77	} else if globalUser := GetGlobalUser(); globalUser != nil {
 78		globalUser.Token = accessToken
 79	}
 80
 81	return accessToken, nil
 82}
 83
 84func tryRenewAniListTokenForAPI(currentToken string, reason string) (string, bool, error) {
 85	config := GetGlobalConfig()
 86	if config == nil {
 87		return currentToken, false, nil
 88	}
 89
 90	// The failing token may be a tracker token (e.g. the MyAnimeList token when
 91	// tracking is myanimelist/both) rather than the AniList token. Don't force a
 92	// browser OAuth re-auth in that case; just use the stored AniList token.
 93	if stored, err := GetTokenFromFile(anilistTokenPath(config)); err == nil && strings.TrimSpace(stored) != "" {
 94		if currentToken == "" || currentToken != stored {
 95			return stored, true, nil
 96		}
 97	}
 98
 99	newToken, err := ReauthenticateAniList(config, GetGlobalUser(), reason)
100	if err != nil {
101		return currentToken, false, err
102	}
103	return newToken, true, nil
104}
105
106func clearStoredTokenFile(tokenPath string) {
107	if err := os.Remove(tokenPath); err != nil && !os.IsNotExist(err) {
108		Log(fmt.Sprintf("Failed to clear stale token file %s: %v", tokenPath, err))
109	}
110}