auth

package
v0.2.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 19, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// QwenPortalModelCoder is the model used for coding tasks in the portal.
	QwenPortalModelCoder = "coder-model"

	// QwenPortalModelVision is the multimodal model used in the portal.
	QwenPortalModelVision = "vision-model"

	// QwenPortalDailyLimit represents the undocumented daily request limit.
	QwenPortalDailyLimit = 2000
)

Undocumented Qwen Portal Constants discovered via testing

Variables

This section is empty.

Functions

func GetDefaultTokenPath

func GetDefaultTokenPath(providerName string) (string, error)

GetDefaultTokenPath 导出默认 token 路径供外部使用

Types

type AuthClientProvider

type AuthClientProvider interface {
	GetProviderName() string
	Authenticate() (*OAuthToken, error)
	RefreshToken(refreshToken string) (*OAuthToken, error)
}

type AuthManager

type AuthManager struct {
	// contains filtered or unexported fields
}

AuthManager handles authentication and token lifecycle management for AI provider clients. It supports automatic token refresh and persistent token storage.

AuthManager is safe for concurrent use. Multiple goroutines can call GetToken simultaneously; proper locking ensures tokens are refreshed only when necessary.

Example:

manager := core.NewAuthManager(provider, "token.json")
if err := manager.Login(); err != nil {
    log.Fatal(err)
}
token, err := manager.GetToken()
// use token for API requests

func Gemini

func Gemini(clientID, clientSecret, callbackURL, listenAddr string, tokenFile ...string) *AuthManager

GeminiWithConfig 使用完整配置创建 Gemini 的 AuthManager

func MiniMax

func MiniMax(region string, tokenFile ...string) *AuthManager

MiniMax 创建 MiniMax 的 AuthManager region: "cn" 表示国内版,其他值表示国际版 tokenFile 可选参数:当提供时启用文件存储,否则使用内存存储

func NewAuthManager

func NewAuthManager(provider AuthClientProvider, filename string) *AuthManager

NewAuthManager creates a new AuthManager with file-based token storage. The filename specifies where tokens should be persisted. If the file exists, tokens will be loaded from it on first access.

Parameters:

  • provider: The authentication provider implementing GetProviderName, Authenticate, and RefreshToken
  • filename: Path to the file where tokens are stored

Returns a configured AuthManager

func NewAuthManagerWithStore

func NewAuthManagerWithStore(provider AuthClientProvider, store TokenStore) *AuthManager

NewAuthManagerWithStore creates a new AuthManager with custom token storage. Use this when you need to store tokens in a different location or format.

Parameters:

  • provider: The authentication provider
  • store: Custom implementation of TokenStore

Returns a configured AuthManager

func Qwen

func Qwen(tokenFile ...string) *AuthManager

Qwen 创建 Qwen (通义千问) 的 AuthManager tokenFile 可选参数:当提供时启用文件存储,否则使用内存存储

func (*AuthManager) GetToken

func (m *AuthManager) GetToken() (*OAuthToken, error)

GetToken returns a valid authentication token, refreshing it if necessary. This is the main method used by API clients to obtain valid credentials.

The method first checks if a token exists. If not, it attempts to load from the store. If the token is expired or will expire soon, it attempts to refresh the token using the provider's RefreshToken method.

Returns a valid OAuthToken and nil on success. Returns nil and an error if no token is available, loading fails, or refresh fails.

func (*AuthManager) LoadToken

func (m *AuthManager) LoadToken() error

LoadToken loads a previously stored token from the token store. This is used to restore session state without requiring re-authentication. If no token store is configured or the store is empty, an error is returned.

Returns an error if loading fails (file not found, corrupted data, etc.)

func (*AuthManager) Login

func (m *AuthManager) Login() error

Login authenticates the user and stores the resulting token. This method should be called once when the user first logs in. The token is stored persistently and will be reused on subsequent program starts via LoadToken.

Returns an error if authentication fails

func (*AuthManager) SetExpiryBuffer

func (m *AuthManager) SetExpiryBuffer(buffer time.Duration)

SetExpiryBuffer changes the buffer time used to determine when to proactively refresh tokens. The default is 60 seconds.

A larger buffer gives more time for network delays but increases the frequency of token refreshes. A smaller buffer may cause requests to fail if refresh takes too long.

Parameters:

  • buffer: The duration before expiration to trigger refresh

type FileTokenStore

type FileTokenStore struct {
	Filename string
}

FileTokenStore is a simple file-based implementation of TokenStore.

func NewFileTokenStore

func NewFileTokenStore(filename string) *FileTokenStore

NewFileTokenStore creates a new FileTokenStore.

func (*FileTokenStore) Load

func (s *FileTokenStore) Load() (*OAuthToken, error)

Load reads the token from a file.

func (*FileTokenStore) Save

func (s *FileTokenStore) Save(token *OAuthToken) error

Save writes the token to a file as JSON.

type GeminiProvider

type GeminiProvider struct {
	ClientID     string
	ClientSecret string
	CallbackURL  string // 例如: http://localhost:8080/oauth2/callback
	ListenAddr   string // 例如: ":8080"
	HTTPClient   *http.Client
	TokenURL     string // For testing override
}

GeminiProvider Gemini 提供商 (标准 OAuth2 Authorization Code Flow)

func NewGeminiProvider

func NewGeminiProvider(clientID, clientSecret, callbackURL, listenAddr string) *GeminiProvider

NewGeminiProvider 创建 Gemini 提供商

func (*GeminiProvider) Authenticate

func (p *GeminiProvider) Authenticate() (*OAuthToken, error)

Authenticate 执行标准 OAuth2 授权码流程

func (*GeminiProvider) GetProviderName

func (p *GeminiProvider) GetProviderName() string

GetProviderName 获取提供商名称

func (*GeminiProvider) RefreshToken

func (p *GeminiProvider) RefreshToken(refreshToken string) (*OAuthToken, error)

RefreshToken 刷新令牌

type MiniMaxOAuthAuthorization

type MiniMaxOAuthAuthorization struct {
	UserCode        string `json:"user_code"`
	VerificationURI string `json:"verification_uri"`
	ExpiredIn       int    `json:"expired_in"`
	Interval        int    `json:"interval,omitempty"`
	State           string `json:"state"`
}

MiniMaxOAuthAuthorization MiniMax OAuth 授权响应

type MiniMaxProvider

type MiniMaxProvider struct {
	HTTPClient    *http.Client
	TokenHelper   *TokenHelper
	PKCEHelper    *PKCEHelper
	Region        string
	BaseURL       string
	ClientID      string
	OAuthCodeURL  string // For testing override
	OAuthTokenURL string // For testing override
}

MiniMaxProvider MiniMax 提供商

func NewMiniMaxProvider

func NewMiniMaxProvider(region string) *MiniMaxProvider

NewMiniMaxProvider 创建 MiniMax 提供商

func (*MiniMaxProvider) Authenticate

func (p *MiniMaxProvider) Authenticate() (*OAuthToken, error)

Authenticate 执行认证流程

func (*MiniMaxProvider) GetProviderName

func (p *MiniMaxProvider) GetProviderName() string

GetProviderName 获取提供商名称

func (*MiniMaxProvider) PollOAuthToken

func (p *MiniMaxProvider) PollOAuthToken(userCode, verifier string) (status string, token *OAuthToken, errorMsg string)

PollOAuthToken 轮询 OAuth 令牌

func (*MiniMaxProvider) RefreshToken

func (p *MiniMaxProvider) RefreshToken(refreshToken string) (*OAuthToken, error)

RefreshToken 刷新令牌

func (*MiniMaxProvider) RequestOAuthCode

func (p *MiniMaxProvider) RequestOAuthCode() (*MiniMaxOAuthAuthorization, string, string, error)

RequestOAuthCode 请求 OAuth 授权码

type OAuthToken

type OAuthToken struct {
	// Access is the bearer token used to authenticate API requests.
	// Include this as a Bearer token in the Authorization header.
	Access string `json:"access"`

	// Refresh is the token used to obtain a new access token when it expires.
	// Store this securely for refreshing expired tokens.
	Refresh string `json:"refresh"`

	// Expires is the Unix timestamp in milliseconds when this token expires.
	// Use this to determine when to refresh the token proactively.
	Expires int64 `json:"expires"`

	// ResourceUrl is an optional endpoint for accessing the resource.
	// This may be provided by some OAuth providers.
	ResourceUrl *string `json:"resourceUrl,omitempty"`

	// NotificationMessage may contain a message from the OAuth provider.
	// This could include warnings or important notices.
	NotificationMessage *string `json:"notification_message,omitempty"`
}

OAuthToken represents an OAuth token received from an AI provider. It contains the credentials needed to authenticate API requests, along with expiration information for token lifecycle management.

type PKCEHelper

type PKCEHelper struct{}

PKCEHelper PKCE 辅助工具

func (*PKCEHelper) GeneratePKCE

func (h *PKCEHelper) GeneratePKCE() (verifier, challenge string, err error)

GeneratePKCE 生成 PKCE verifier 和 challenge

func (*PKCEHelper) GenerateState

func (h *PKCEHelper) GenerateState() (string, error)

GenerateState 生成随机 state

func (*PKCEHelper) GenerateUUID

func (h *PKCEHelper) GenerateUUID() (string, error)

GenerateUUID 生成随机 UUID

type QwenDeviceAuthorization

type QwenDeviceAuthorization struct {
	DeviceCode              string `json:"device_code"`
	UserCode                string `json:"user_code"`
	VerificationURI         string `json:"verification_uri"`
	VerificationURIComplete string `json:"verification_uri_complete,omitempty"`
	ExpiresIn               int    `json:"expires_in"`
	Interval                int    `json:"interval,omitempty"`
}

QwenDeviceAuthorization Qwen 设备授权响应

type QwenProvider

type QwenProvider struct {
	HTTPClient    *http.Client
	TokenHelper   *TokenHelper
	PKCEHelper    *PKCEHelper
	DeviceCodeURL string // For testing override
	TokenURL      string // For testing override
}

QwenProvider Qwen 提供商

func NewQwenProvider

func NewQwenProvider() *QwenProvider

NewQwenProvider 创建 Qwen 提供商

func (*QwenProvider) Authenticate

func (p *QwenProvider) Authenticate() (*OAuthToken, error)

Authenticate 执行认证流程

func (*QwenProvider) GetProviderName

func (p *QwenProvider) GetProviderName() string

GetProviderName 获取提供商名称

func (*QwenProvider) PollForToken

func (p *QwenProvider) PollForToken(deviceCode, verifier string) (status string, token *OAuthToken, slowDown bool, errorMsg string)

PollForToken 轮询获取令牌

func (*QwenProvider) RefreshToken

func (p *QwenProvider) RefreshToken(refreshToken string) (*OAuthToken, error)

RefreshToken 刷新令牌

func (*QwenProvider) RequestDeviceCode

func (p *QwenProvider) RequestDeviceCode() (*QwenDeviceAuthorization, string, error)

RequestDeviceCode 请求设备码

type TokenHelper

type TokenHelper struct{}

TokenHelper 令牌辅助工具

func (*TokenHelper) IsTokenExpired

func (h *TokenHelper) IsTokenExpired(token *OAuthToken) bool

IsTokenExpired 检查令牌是否过期

func (*TokenHelper) LoadToken

func (h *TokenHelper) LoadToken(filename string) (*OAuthToken, error)

LoadToken 从文件加载令牌

func (*TokenHelper) SaveToken

func (h *TokenHelper) SaveToken(token *OAuthToken, filename string) error

SaveToken 保存令牌到文件

type TokenStore

type TokenStore interface {
	Save(token *OAuthToken) error
	Load() (*OAuthToken, error)
}

TokenStore defines the interface for persisting and retrieving OAuth tokens. This allows developers to use custom storage like databases, Redis, or memory.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL