oauth

package
v0.260224.1130 Latest Latest
Warning

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

Go to latest
Published: Feb 24, 2026 License: MPL-2.0 Imports: 21 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrTokenNotFound is returned when a token is not found in storage
	ErrTokenNotFound = errors.New("oauth: token not found")

	// ErrInvalidProvider is returned when an invalid provider is specified
	ErrInvalidProvider = errors.New("oauth: invalid provider")

	// ErrInvalidState is returned when the OAuth state parameter is invalid
	ErrInvalidState = errors.New("oauth: invalid state")

	// ErrStateExpired is returned when the OAuth state has expired
	ErrStateExpired = errors.New("oauth: state expired")

	// ErrInvalidCode is returned when the authorization code is invalid
	ErrInvalidCode = errors.New("oauth: invalid authorization code")

	// ErrTokenExchangeFailed is returned when token exchange fails
	ErrTokenExchangeFailed = errors.New("oauth: token exchange failed")

	// ErrNoRefreshToken is returned when a refresh is attempted but no refresh token is available
	ErrNoRefreshToken = errors.New("oauth: no refresh token available")

	// ErrProviderNotConfigured is returned when a provider is not configured
	ErrProviderNotConfigured = errors.New("oauth: provider not configured")

	// ErrInvalidCallback is returned when the callback parameters are invalid
	ErrInvalidCallback = errors.New("oauth: invalid callback")
)

Functions

This section is empty.

Types

type AnthropicHook

type AnthropicHook struct{}

AnthropicHook implements Anthropic Claude Code OAuth specific behavior.

func (*AnthropicHook) AfterToken

func (h *AnthropicHook) AfterToken(ctx context.Context, accessToken string, httpClient *http.Client) (map[string]any, error)

func (*AnthropicHook) BeforeAuth

func (h *AnthropicHook) BeforeAuth(params map[string]string) error

func (*AnthropicHook) BeforeToken

func (h *AnthropicHook) BeforeToken(body map[string]string, header http.Header) error

type AntigravityHook

type AntigravityHook struct{}

AntigravityHook implements Antigravity OAuth specific behavior.

func (*AntigravityHook) AfterToken

func (h *AntigravityHook) AfterToken(ctx context.Context, accessToken string, httpClient *http.Client) (map[string]any, error)

func (*AntigravityHook) BeforeAuth

func (h *AntigravityHook) BeforeAuth(params map[string]string) error

func (*AntigravityHook) BeforeToken

func (h *AntigravityHook) BeforeToken(body map[string]string, header http.Header) error

type AuthStyle

type AuthStyle int

AuthStyle represents how client credentials are sent to the token endpoint

const (
	// AuthStyleAuto detects the auth style automatically
	AuthStyleAuto AuthStyle = iota

	// AuthStyleInHeader sends client credentials in the Authorization header
	AuthStyleInHeader

	// AuthStyleInParams sends client credentials in the POST body
	AuthStyleInParams

	// AuthStyleInNone uses no client authentication (public client)
	AuthStyleInNone
)

type CallbackServer added in v0.260127.1200

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

CallbackServer manages a temporary HTTP server for OAuth callbacks

func NewCallbackServer added in v0.260127.1200

func NewCallbackServer(handler http.HandlerFunc) *CallbackServer

NewCallbackServer creates a new callback server manager

func (*CallbackServer) GetPort added in v0.260127.1200

func (cs *CallbackServer) GetPort() int

GetPort returns the port the server is listening on

func (*CallbackServer) GetURL added in v0.260127.1200

func (cs *CallbackServer) GetURL() string

GetURL returns the base URL for the callback server

func (*CallbackServer) IsRunning added in v0.260127.1200

func (cs *CallbackServer) IsRunning() bool

IsRunning returns true if the server is running

func (*CallbackServer) Start added in v0.260127.1200

func (cs *CallbackServer) Start(port int) error

Start starts the callback server on the specified port If port is 0, it will try to bind to any available port

func (*CallbackServer) Stop added in v0.260127.1200

func (cs *CallbackServer) Stop(ctx context.Context) error

Stop stops the callback server gracefully

func (*CallbackServer) Wait added in v0.260127.1200

func (cs *CallbackServer) Wait()

Wait waits for the server to finish (e.g., after Shutdown)

type CodexHook

type CodexHook struct{}

CodexHook implements Codex (OpenAI) OAuth specific behavior.

func (*CodexHook) AfterToken

func (h *CodexHook) AfterToken(ctx context.Context, accessToken string, httpClient *http.Client) (map[string]any, error)

func (*CodexHook) BeforeAuth

func (h *CodexHook) BeforeAuth(params map[string]string) error

func (*CodexHook) BeforeToken

func (h *CodexHook) BeforeToken(body map[string]string, header http.Header) error

type Config

type Config struct {
	// BaseURL is the base URL of this server for callback generation
	BaseURL string

	// ProviderConfigs maps provider types to their OAuth configurations
	ProviderConfigs map[ProviderType]*ProviderConfig

	// TokenStorage is the storage for OAuth tokens
	TokenStorage TokenStorage

	// StateExpiry is the duration for which OAuth state is valid
	StateExpiry time.Duration

	// TokenExpiryBuffer is the buffer before token expiry to trigger refresh
	TokenExpiryBuffer time.Duration

	// ProxyURL is the HTTP proxy URL for OAuth requests (e.g., "http://proxy.example.com:8080")
	// Can be set via OAUTH_PROXY_URL environment variable
	ProxyURL *url.URL
}

Config holds the OAuth configuration

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns a default OAuth configuration

func (*Config) GetHTTPClient added in v0.260127.1200

func (c *Config) GetHTTPClient() *http.Client

GetHTTPClient returns an HTTP client configured with proxy if set

type DeviceCodeData

type DeviceCodeData struct {
	*DeviceCodeResponse
	Provider     ProviderType
	UserID       string
	RedirectTo   string
	Name         string
	ExpiresAt    time.Time
	InitiatedAt  time.Time
	CodeVerifier string // PKCE code verifier (for Device Code PKCE flow)
}

DeviceCodeData holds device code information with metadata

type DeviceCodePendingError

type DeviceCodePendingError struct {
	Message string
}

DeviceCodePendingError represents a pending device code authorization

func (*DeviceCodePendingError) Error

func (e *DeviceCodePendingError) Error() string

type DeviceCodeResponse

type DeviceCodeResponse struct {
	// DeviceCode is the device verification code
	DeviceCode string `json:"device_code"`

	// UserCode is the end-user verification code
	UserCode string `json:"user_code"`

	// VerificationURI is the end-user verification URI where user enters the user code
	VerificationURI string `json:"verification_uri"`

	// VerificationURIComplete is the end-user verification URI with user_code pre-filled
	VerificationURIComplete string `json:"verification_uri_complete,omitempty"`

	// ExpiresIn is the lifetime in seconds of the device_code and user_code
	ExpiresIn int64 `json:"expires_in"`

	// Interval is the minimum amount of time in seconds that the client SHOULD wait
	// between polling requests to the token endpoint
	Interval int64 `json:"interval,omitempty"`
}

DeviceCodeResponse represents the response from the device authorization endpoint RFC 8628: OAuth 2.0 Device Authorization Grant

type DeviceTokenRequest

type DeviceTokenRequest struct {
	// GrantType is the grant type, must be "urn:ietf:params:oauth:grant-type:device_code"
	GrantType string `json:"grant_type"`

	// DeviceCode is the device code from the device authorization response
	DeviceCode string `json:"device_code"`

	// ClientID is the OAuth client ID
	ClientID string `json:"client_id"`

	// ClientSecret is the OAuth client secret (optional for public clients)
	ClientSecret string `json:"client_secret,omitempty"`
}

DeviceTokenRequest represents the request to poll for token with device code

type GeminiHook

type GeminiHook struct{}

GeminiHook implements Gemini CLI OAuth specific behavior.

func (*GeminiHook) AfterToken

func (h *GeminiHook) AfterToken(ctx context.Context, accessToken string, httpClient *http.Client) (map[string]any, error)

func (*GeminiHook) BeforeAuth

func (h *GeminiHook) BeforeAuth(params map[string]string) error

func (*GeminiHook) BeforeToken

func (h *GeminiHook) BeforeToken(body map[string]string, header http.Header) error

type IFlowHook

type IFlowHook struct {
	ClientID     string
	ClientSecret string
}

IFlowHook implements iFlow OAuth specific behavior.

func (*IFlowHook) AfterToken

func (h *IFlowHook) AfterToken(ctx context.Context, accessToken string, httpClient *http.Client) (map[string]any, error)

func (*IFlowHook) BeforeAuth

func (h *IFlowHook) BeforeAuth(params map[string]string) error

func (*IFlowHook) BeforeToken

func (h *IFlowHook) BeforeToken(body map[string]string, header http.Header) error

type Manager

type Manager struct {
	Debug bool
	// contains filtered or unexported fields
}

Manager handles OAuth flows

func NewManager

func NewManager(config *Config, registry *Registry) *Manager

NewManager creates a new OAuth manager

func (*Manager) CreateSession

func (m *Manager) CreateSession(userID string, provider ProviderType) (*SessionState, error)

CreateSession creates a new OAuth session with pending status

func (*Manager) GetAuthURL

func (m *Manager) GetAuthURL(userID string, providerType ProviderType, redirectTo string, name string, sessionID string) (string, string, error)

GetAuthURL generates the OAuth authorization URL for a provider

func (*Manager) GetConfig

func (m *Manager) GetConfig() *Config

GetConfig returns the OAuth configuration

func (*Manager) GetRegistry

func (m *Manager) GetRegistry() *Registry

GetRegistry returns the provider registry

func (*Manager) GetSession

func (m *Manager) GetSession(sessionID string) (*SessionState, error)

GetSession retrieves a session by ID

func (*Manager) GetToken

func (m *Manager) GetToken(ctx context.Context, userID string, providerType ProviderType, opts ...Option) (*Token, error)

GetToken retrieves a token for a user and provider, refreshing if necessary

func (*Manager) HandleCallback

func (m *Manager) HandleCallback(ctx context.Context, r *http.Request, opts ...Option) (*Token, error)

HandleCallback handles the OAuth callback request

func (*Manager) InitiateDeviceCodeFlow

func (m *Manager) InitiateDeviceCodeFlow(ctx context.Context, userID string, providerType ProviderType, redirectTo string, name string, opts ...Option) (*DeviceCodeData, error)

InitiateDeviceCodeFlow initiates the Device Code flow and returns device code data RFC 8628: OAuth 2.0 Device Authorization Grant

func (*Manager) ListProviders

func (m *Manager) ListProviders(userID string) ([]ProviderType, error)

ListProviders returns all providers that have valid tokens for the user

func (*Manager) PollForToken

func (m *Manager) PollForToken(ctx context.Context, data *DeviceCodeData, callback func(*Token), opts ...Option) (*Token, error)

PollForToken polls the token endpoint until the user completes authentication or the device code expires Polling timeout is limited to 5 minutes (user needs time to complete auth)

func (*Manager) RefreshToken

func (m *Manager) RefreshToken(ctx context.Context, userID string, providerType ProviderType, refreshToken string, opts ...Option) (*Token, error)

RefreshToken refreshes an access token using a refresh token This is a public method that can be called from HTTP handlers

func (*Manager) ResetProxyURL added in v0.260127.1200

func (m *Manager) ResetProxyURL()

ResetProxyURL clears the ProxyURL in the OAuth configuration This should be called after OAuth flow completes

func (*Manager) RevokeToken

func (m *Manager) RevokeToken(userID string, providerType ProviderType) error

RevokeToken removes a token for a user and provider

func (*Manager) SetBaseURL added in v0.260127.1200

func (m *Manager) SetBaseURL(baseURL string)

SetBaseURL updates the BaseURL in the OAuth configuration This is used when starting a dynamic callback server on a specific port

func (*Manager) SetProxyURL added in v0.260127.1200

func (m *Manager) SetProxyURL(proxyURL *url.URL)

SetProxyURL updates the ProxyURL in the OAuth configuration This is used to temporarily set a proxy for a specific OAuth flow

func (*Manager) StoreSession added in v0.260127.1200

func (m *Manager) StoreSession(session *SessionState)

StoreSession stores or updates a session

func (*Manager) UpdateSessionStatus

func (m *Manager) UpdateSessionStatus(sessionID string, status SessionStatus, providerUUID string, errMsg string) error

UpdateSessionStatus updates the status of a session

type MemoryTokenStorage

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

MemoryTokenStorage is an in-memory implementation of TokenStorage

func NewMemoryTokenStorage

func NewMemoryTokenStorage() *MemoryTokenStorage

NewMemoryTokenStorage creates a new in-memory token storage

func (*MemoryTokenStorage) CleanupExpiredTokens

func (s *MemoryTokenStorage) CleanupExpiredTokens()

CleanupExpiredTokens removes all expired tokens from the storage

func (*MemoryTokenStorage) DeleteToken

func (s *MemoryTokenStorage) DeleteToken(userID string, provider ProviderType) error

DeleteToken removes a token for the given user and provider

func (*MemoryTokenStorage) GetToken

func (s *MemoryTokenStorage) GetToken(userID string, provider ProviderType) (*Token, error)

GetToken retrieves a token for the given user and provider

func (*MemoryTokenStorage) ListProviders

func (s *MemoryTokenStorage) ListProviders(userID string) ([]ProviderType, error)

ListProviders returns all providers that have tokens for the user

func (*MemoryTokenStorage) SaveToken

func (s *MemoryTokenStorage) SaveToken(userID string, provider ProviderType, token *Token) error

SaveToken saves a token for the given user and provider

type MetadataTokenStorage

type MetadataTokenStorage interface {
	TokenStorage

	// SaveTokenWithMetadata saves a token with additional metadata
	SaveTokenWithMetadata(userID string, provider ProviderType, token *Token, metadata map[string]string) error

	// GetTokenWithMetadata retrieves a token with metadata
	GetTokenWithMetadata(userID string, provider ProviderType) (*TokenWithMetadata, error)

	// ListAllTokens returns all tokens with their metadata
	ListAllTokens() ([]*TokenWithMetadata, error)
}

MetadataTokenStorage extends TokenStorage with metadata support

type NoopHook

type NoopHook struct{}

NoopHook is a default hook that does nothing. Used when no custom behavior is needed.

func (*NoopHook) AfterToken

func (h *NoopHook) AfterToken(ctx context.Context, accessToken string, httpClient *http.Client) (map[string]any, error)

func (*NoopHook) BeforeAuth

func (h *NoopHook) BeforeAuth(params map[string]string) error

func (*NoopHook) BeforeToken

func (h *NoopHook) BeforeToken(body map[string]string, header http.Header) error

type OAuthMethod

type OAuthMethod int

OAuthMethod represents the OAuth flow method

const (
	// OAuthMethodAuthorizationCode uses standard Authorization Code flow
	OAuthMethodAuthorizationCode OAuthMethod = iota

	// OAuthMethodPKCE uses Authorization Code flow with PKCE (RFC 7636)
	OAuthMethodPKCE

	// OAuthMethodDeviceCode uses Device Code flow (RFC 8628)
	OAuthMethodDeviceCode

	// OAuthMethodDeviceCodePKCE uses Device Code flow with PKCE (RFC 8628 + RFC 7636)
	OAuthMethodDeviceCodePKCE
)

type Option added in v0.260224.0

type Option func(*Options)

Option is a functional option for OAuth operations

func WithHTTPClient added in v0.260224.0

func WithHTTPClient(client *http.Client) Option

WithHTTPClient sets a custom HTTP client

func WithProxyString added in v0.260224.0

func WithProxyString(proxy string) Option

WithProxyString sets a string proxy URL for the request

func WithProxyURL added in v0.260224.0

func WithProxyURL(proxyURL *url.URL) Option

WithProxyURL sets a proxy URL for the request

func WithProxyURLString added in v0.260224.0

func WithProxyURLString(proxyURL string) Option

WithProxyURLString sets a proxy URL from string Returns an option that does nothing if the URL is invalid

type Options added in v0.260224.0

type Options struct {
	// ProxyURL overrides the default proxy for this request
	ProxyURL *url.URL

	// HTTPClient allows passing a custom HTTP client
	HTTPClient *http.Client
}

Options holds optional parameters for OAuth operations

type ProviderConfig

type ProviderConfig struct {
	// Type is the provider type
	Type ProviderType

	GrantType string

	// DisplayName is the human-readable name
	DisplayName string

	// ClientID is the OAuth client ID
	ClientID string

	// ClientSecret is the OAuth client secret
	ClientSecret string

	// AuthURL is the authorization endpoint URL
	AuthURL string

	// DeviceCodeURL is the device authorization endpoint URL (for Device Code flow)
	DeviceCodeURL string

	// TokenURL is the token endpoint URL
	TokenURL string

	// Scopes is the list of OAuth scopes to request
	Scopes []string

	// AuthStyle is the authentication style (in header, body, etc.)
	AuthStyle AuthStyle

	// OAuthMethod is the OAuth flow method (authorization code or PKCE)
	OAuthMethod OAuthMethod

	// RedirectURL is the OAuth redirect URI (optional, uses default if empty)
	RedirectURL string

	// Callback is the callback route path (optional, defaults to "/callback")
	// Some providers require specific callback paths, e.g., codex requires "/auth/callback"
	Callback string

	// ConsoleURL is the URL to the provider's console for creating OAuth apps
	ConsoleURL string

	// TokenRequestFormat specifies the format of token request body
	// Default is TokenRequestFormatForm (standard OAuth)
	TokenRequestFormat TokenRequestFormat

	// StateEncoding specifies the encoding format for OAuth state parameter
	// Default is StateEncodingHex (standard)
	StateEncoding StateEncoding

	// Hook is the request preprocessing hook for provider-specific behavior
	Hook RequestHook

	// CallbackPorts specifies allowed ports for the callback URL
	// Empty = no constraint (any port is allowed)
	// Some providers require specific ports, e.g., codex allows [1455]
	CallbackPorts []int
}

ProviderConfig holds the OAuth configuration for a specific provider

type ProviderInfo

type ProviderInfo struct {
	Type        ProviderType `json:"type"`
	DisplayName string       `json:"display_name"`
	AuthURL     string       `json:"auth_url,omitempty"`
	Scopes      []string     `json:"scopes,omitempty"`
	Configured  bool         `json:"configured"` // Has client credentials
}

ProviderInfo returns information about a provider

type ProviderType

type ProviderType string

ProviderType represents the OAuth provider type

const (
	ProviderClaudeCode  ProviderType = "claude_code"
	ProviderOpenAI      ProviderType = "openai"
	ProviderGoogle      ProviderType = "google"
	ProviderGemini      ProviderType = "gemini" // Gemini CLI OAuth
	ProviderGitHub      ProviderType = "github"
	ProviderQwenCode    ProviderType = "qwen_code"
	ProviderAntigravity ProviderType = "antigravity"
	ProviderIFlow       ProviderType = "iflow"
	ProviderCodex       ProviderType = "codex"
	ProviderMock        ProviderType = "mock"
)

func ParseProviderType

func ParseProviderType(s string) (ProviderType, error)

ParseProviderType parses a provider type from string, case-insensitive

func (ProviderType) String

func (p ProviderType) String() string

String returns the string representation of ProviderType

type QwenHook

type QwenHook struct{}

QwenHook implements Qwen Device Code OAuth specific behavior.

func (*QwenHook) AfterToken

func (h *QwenHook) AfterToken(ctx context.Context, accessToken string, httpClient *http.Client) (map[string]any, error)

func (*QwenHook) BeforeAuth

func (h *QwenHook) BeforeAuth(params map[string]string) error

func (*QwenHook) BeforeToken

func (h *QwenHook) BeforeToken(body map[string]string, header http.Header) error

type Registry

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

Registry manages OAuth provider configurations

func DefaultRegistry

func DefaultRegistry() *Registry

DefaultRegistry returns a registry with default provider configurations Note: Client ID and Secret must be set from environment variables or config

func NewRegistry

func NewRegistry() *Registry

NewRegistry creates a new OAuth provider registry

func (*Registry) Get

func (r *Registry) Get(providerType ProviderType) (*ProviderConfig, bool)

Get returns a provider configuration

func (*Registry) GetProviderInfo

func (r *Registry) GetProviderInfo() []ProviderInfo

GetProviderInfo returns info about all registered providers

func (*Registry) IsRegistered

func (r *Registry) IsRegistered(providerType ProviderType) bool

IsRegistered checks if a provider is registered

func (*Registry) List

func (r *Registry) List() []ProviderType

List returns all registered provider types

func (*Registry) Register

func (r *Registry) Register(config *ProviderConfig)

Register adds or updates a provider configuration

func (*Registry) Unregister

func (r *Registry) Unregister(providerType ProviderType)

Unregister removes a provider configuration

type RequestHook

type RequestHook interface {
	// BeforeAuth is called before building the authorization URL.
	// The params map contains URL query parameters that can be modified or extended.
	BeforeAuth(params map[string]string) error

	// BeforeToken is called before sending any token-related HTTP request.
	// This covers: token exchange, refresh token, device code request, and device token polling.
	// The body map contains request body parameters, header is the HTTP headers.
	BeforeToken(body map[string]string, header http.Header) error

	// AfterToken is called after successful token exchange to fetch additional metadata.
	// Returns additional metadata to be stored with the token (email, project_id, api_key, etc).
	// Can return nil map if no additional metadata is needed.
	AfterToken(ctx context.Context, accessToken string, httpClient *http.Client) (map[string]any, error)
}

RequestHook defines preprocessing and postprocessing hooks for OAuth requests. Implementations can modify request parameters before they are sent and fetch additional metadata after token is obtained.

type SessionState

type SessionState struct {
	SessionID    string        `json:"session_id"`
	Status       SessionStatus `json:"status"`
	Provider     ProviderType  `json:"provider"`
	UserID       string        `json:"user_id"`
	CreatedAt    time.Time     `json:"created_at"`
	ExpiresAt    time.Time     `json:"expires_at"`
	ProviderUUID string        `json:"provider_uuid,omitempty"` // Set when success
	Error        string        `json:"error,omitempty"`         // Set when failed
	ProxyURL     string        `json:"proxy_url,omitempty"`     // Proxy URL used for this session
}

SessionState holds information about an OAuth session

type SessionStatus

type SessionStatus string

SessionStatus represents the status of an OAuth session

const (
	SessionStatusPending SessionStatus = "pending" // Authorization initiated
	SessionStatusSuccess SessionStatus = "success" // Provider created successfully
	SessionStatusFailed  SessionStatus = "failed"  // Authorization failed
)

type StateData

type StateData struct {
	State         string
	UserID        string
	Provider      ProviderType
	ExpiresAt     time.Time
	Timestamp     int64  // Unix timestamp when state was created
	ExpiresAtUnix int64  // Unix timestamp when state expires
	RedirectTo    string // Optional redirect URL after successful auth
	Name          string // Optional custom provider name
	CodeVerifier  string // PKCE code verifier (for PKCE flow)
	RedirectURI   string // Actual redirect_uri used in auth request (must match in token request)
	SessionID     string // Session ID for status tracking
}

StateData holds information about an OAuth state

type StateEncoding

type StateEncoding int

StateEncoding represents the encoding format for OAuth state parameter

const (
	// StateEncodingHex uses hexadecimal encoding (default, 32 chars for 16 bytes)
	StateEncodingHex StateEncoding = iota

	// StateEncodingBase64URL uses base64url encoding without padding (22 chars for 16 bytes)
	StateEncodingBase64URL

	// StateEncodingBase64URL32 uses base64url encoding with 32 bytes (43 chars without padding)
	// Used by OpenAI Codex to match their state format
	StateEncodingBase64URL32
)

type Token

type Token struct {
	// AccessToken is the access token
	AccessToken string `json:"access_token"`

	// RefreshToken is the refresh token (may be empty)
	RefreshToken string `json:"refresh_token"`

	// IDToken is the OpenID Connect ID token (may be empty)
	IDToken string `json:"id_token,omitempty"`

	// TokenType is the type of token (usually "Bearer")
	TokenType string `json:"token_type"`

	// ExpiresIn is the token expiration duration in seconds (from API response)
	ExpiresIn int64 `json:"expires_in"`

	// Expiry is the token expiration time (zero if no expiry)
	Expiry time.Time `json:"-"`

	// Provider is the provider that issued this token
	Provider ProviderType `json:"-"`

	// RedirectTo is the optional URL to redirect to after successful OAuth
	RedirectTo string `json:"-"`

	// Name is the optional custom name for the provider
	Name string `json:"-"`

	// ResourceURL is the optional resource URL endpoint (for some providers like Qwen)
	ResourceURL string `json:"resource_url,omitempty"`

	// Metadata contains additional provider-specific information (email, project_id, api_key, etc)
	Metadata map[string]any `json:"metadata,omitempty"`

	// SessionID is the OAuth session ID for status tracking
	SessionID string `json:"-"`
}

Token represents an OAuth token

func (*Token) Expired

func (t *Token) Expired() bool

Expired returns true if the token is expired

func (*Token) ExpiredIn

func (t *Token) ExpiredIn(within time.Duration) bool

ExpiredIn returns true if the token will expire within the given duration

func (*Token) Valid

func (t *Token) Valid() bool

Valid returns true if the token is valid and not expired

type TokenRequestFormat

type TokenRequestFormat int

TokenRequestFormat represents the format of token request body

const (
	// TokenRequestFormatForm uses application/x-www-form-urlencoded (default OAuth standard)
	TokenRequestFormatForm TokenRequestFormat = iota

	// TokenRequestFormatJSON uses application/json format
	TokenRequestFormatJSON
)

type TokenStorage

type TokenStorage interface {
	// SaveToken saves a token for the given user and provider
	SaveToken(userID string, provider ProviderType, token *Token) error

	// GetToken retrieves a token for the given user and provider
	GetToken(userID string, provider ProviderType) (*Token, error)

	// DeleteToken removes a token for the given user and provider
	DeleteToken(userID string, provider ProviderType) error

	// ListProviders returns all providers that have tokens for the user
	ListProviders(userID string) ([]ProviderType, error)
}

TokenStorage defines the interface for storing and retrieving OAuth tokens

type TokenWithMetadata

type TokenWithMetadata struct {
	Token     *Token
	UserID    string
	Provider  ProviderType
	CreatedAt time.Time
	UpdatedAt time.Time
}

TokenWithMetadata represents a token with additional metadata

Directories

Path Synopsis
Package main provides an example OAuth client that demonstrates how to use the oauth package for performing OAuth 2.0 authorization flows.
Package main provides an example OAuth client that demonstrates how to use the oauth package for performing OAuth 2.0 authorization flows.

Jump to

Keyboard shortcuts

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