Help us shape the future of Go! Take the 2026 Go Developer Survey

oauth

package
v1.11.3 Latest Latest
Warning

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

Go to latest
Published: Oct 21, 2026 License: Apache-2.0 Imports: 17 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GenerateState

func GenerateState() string

GenerateState generates a random state parameter

Types

type Client

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

Client represents an OAuth client

func NewClient

func NewClient(config *Config) *Client

NewClient creates a new OAuth client

func (*Client) AuthorizeURL

func (c *Client) AuthorizeURL(state string) string

AuthorizeURL generates the authorization URL for the browser PKCE flow.

func (*Client) DeviceCode

func (c *Client) DeviceCode(ctx context.Context) (*DeviceCodeResponse, error)

DeviceCode initiates OpenAI's device auth flow. Calls the OpenAI-specific /api/accounts/deviceauth/usercode endpoint with a JSON body — NOT the standard RFC 8628 Auth0 device_code endpoint.

func (*Client) ExchangeCode

func (c *Client) ExchangeCode(ctx context.Context, code, codeVerifier string) (*TokenResponse, error)

ExchangeCode exchanges an authorization code for tokens (browser flow). codeVerifier should be provided for PKCE flows; pass empty string otherwise.

func (*Client) ExchangeDeviceToken

func (c *Client) ExchangeDeviceToken(ctx context.Context, deviceCode string, userCode string) (*TokenResponse, error)

ExchangeDeviceToken polls OpenAI's device token endpoint. On pending: returns an "authorization_pending" error (caller should retry). On success: performs the PKCE token exchange and returns full tokens. Both deviceCode (device_auth_id) and userCode are required for the poll body.

func (*Client) PollToken

func (c *Client) PollToken(ctx context.Context, deviceCode, userCode string, interval int) (*TokenResponse, error)

PollToken polls for a token until the user completes auth (blocks; for CLI use).

func (*Client) RefreshToken

func (c *Client) RefreshToken(ctx context.Context, refreshToken string) (*TokenResponse, error)

RefreshToken refreshes an OAuth token

type Config

type Config struct {
	BaseURL        string   // Base URL for OAuth provider (auth server root)
	ClientID       string   // OAuth client ID
	ClientSecret   string   // OAuth client secret (optional)
	AuthURL        string   // Authorization endpoint (browser PKCE flow)
	TokenURL       string   // Token endpoint
	DeviceAuthURL  string   // Device usercode endpoint (OpenAI custom API)
	DeviceTokenURL string   // Device token poll endpoint (OpenAI custom API)
	Scopes         []string // OAuth scopes
	RedirectURI    string   // Redirect URI
	HTTPClient     *http.Client
}

Config represents OAuth client configuration

func DefaultOpenAIConfig

func DefaultOpenAIConfig() *Config

DefaultOpenAIConfig returns OAuth config for ChatGPT authentication. Uses the same device auth flow as Codex CLI (github.com/openai/codex). Issuer: https://auth.openai.com

type DeviceCodeResponse

type DeviceCodeResponse struct {
	DeviceCode              string // maps to device_auth_id in OpenAI's API
	UserCode                string
	VerificationURI         string
	VerificationURIComplete string
	ExpiresIn               int
	Interval                int
}

DeviceCodeResponse represents the normalised device code response.

type Handler

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

Handler handles the complete OAuth device flow

func NewHandler

func NewHandler(client *Client) *Handler

NewHandler creates a new OAuth handler

func (*Handler) Start

func (h *Handler) Start() (userCode, verificationURL string, err error)

Start starts the OAuth flow

func (*Handler) Stop

func (h *Handler) Stop()

Stop stops the OAuth handler

func (*Handler) WaitComplete

func (h *Handler) WaitComplete() (*Token, error)

WaitComplete waits for the user to complete authentication

type OAuthManager

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

OAuthManager manages OAuth tokens with auto-refresh

func NewOAuthManager

func NewOAuthManager(s store.Store, provider string, cfg *Config) *OAuthManager

NewOAuthManager creates a new OAuth manager

func (*OAuthManager) Complete

func (m *OAuthManager) Complete(ctx context.Context, token *Token) error

Complete stores the token after OAuth completion

func (*OAuthManager) GetToken

func (m *OAuthManager) GetToken(ctx context.Context) (string, error)

GetToken returns a valid token, refreshing if necessary. Uses a write lock throughout so refresh() can safely mutate m.token / m.refreshAt.

func (*OAuthManager) LoadCredentials

func (m *OAuthManager) LoadCredentials(ctx context.Context) (*authTypes.Credentials, error)

LoadCredentials loads OAuth credentials from the auth store

func (*OAuthManager) Login

func (m *OAuthManager) Login(ctx context.Context) (userCode, url string, err error)

Login starts OAuth authentication and returns the verification URL

func (*OAuthManager) Stop

func (m *OAuthManager) Stop()

Stop stops the auto-refresh loop

func (*OAuthManager) StoreCredentials

func (m *OAuthManager) StoreCredentials(ctx context.Context, creds *authTypes.Credentials) error

StoreCredentials stores OAuth credentials in the auth store

type ProviderConfig

type ProviderConfig struct {
	BaseURL       string
	ClientID      string
	AuthURL       string
	TokenURL      string
	DeviceCodeURL string
	Scopes        []string
}

ProviderConfig holds OAuth provider configuration

func DefaultGoogleProvider

func DefaultGoogleProvider() *ProviderConfig

DefaultGoogleProvider returns default Google OAuth config

func DefaultOpenAIProvider

func DefaultOpenAIProvider() *ProviderConfig

DefaultOpenAIProvider returns the Auth0-based OAuth config for ChatGPT.

type Server

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

Server handles OAuth callbacks

func NewServer

func NewServer(config *ServerConfig) *Server

NewServer creates a new OAuth callback server

func (*Server) Start

func (s *Server) Start(ctx context.Context) (string, error)

Start starts the callback server

func (*Server) Stop

func (s *Server) Stop(ctx context.Context) error

Stop stops the callback server

func (*Server) WaitForCallback

func (s *Server) WaitForCallback(ctx context.Context) (*TokenResponse, error)

WaitForCallback waits for the OAuth callback

type ServerConfig

type ServerConfig struct {
	Port       int           // Port to listen on (0 for random)
	Timeout    time.Duration // Timeout for the auth process
	HTTPClient *http.Client
}

ServerConfig represents server configuration

func DefaultServerConfig

func DefaultServerConfig() *ServerConfig

DefaultServerConfig returns a default server configuration

type SimpleAuthenticator

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

SimpleAuthenticator handles the Auth0 device code flow for ChatGPT/OpenAI. Usage:

userCode, url, err := a.StartDeviceFlow(ctx)
// show userCode and url to the user, then:
token, err := a.WaitDeviceFlow(ctx)

func NewSimpleAuthenticator

func NewSimpleAuthenticator(clientID string) *SimpleAuthenticator

NewSimpleAuthenticator creates a new authenticator for the given OAuth client ID.

func (*SimpleAuthenticator) StartDeviceFlow

func (a *SimpleAuthenticator) StartDeviceFlow(ctx context.Context) (userCode, verificationURL string, err error)

StartDeviceFlow requests a device code from Auth0 and returns the user-facing code and verification URL. Call WaitDeviceFlow afterwards to poll for the token.

func (*SimpleAuthenticator) WaitDeviceFlow

func (a *SimpleAuthenticator) WaitDeviceFlow(ctx context.Context) (*Token, error)

WaitDeviceFlow polls Auth0 until the user completes authentication. It blocks until the token is received or ctx is cancelled.

type Token

type Token struct {
	AccessToken  string    `json:"access_token"`
	RefreshToken string    `json:"refresh_token,omitempty"`
	IDToken      string    `json:"id_token,omitempty"`
	TokenType    TokenType `json:"token_type"`
	ExpiresAt    time.Time `json:"expires_at"`
	Scope        string    `json:"scope,omitempty"`
}

Token represents an OAuth token

func (*Token) IsExpired

func (t *Token) IsExpired() bool

IsExpired returns true if the token is expired

func (*Token) NeedsRefresh

func (t *Token) NeedsRefresh() bool

NeedsRefresh returns true if the token should be refreshed

type TokenResponse

type TokenResponse struct {
	AccessToken  string `json:"access_token"`
	TokenType    string `json:"token_type"`
	ExpiresIn    int    `json:"expires_in"`
	RefreshToken string `json:"refresh_token,omitempty"`
	IDToken      string `json:"id_token,omitempty"`
	Scope        string `json:"scope,omitempty"`
}

TokenResponse represents a token response

func (*TokenResponse) ToToken

func (r *TokenResponse) ToToken() *Token

ToToken converts to auth.Token format

type TokenType

type TokenType string

TokenType represents the type of token

const (
	TokenTypeAccess  TokenType = "access_token"
	TokenTypeRefresh TokenType = "refresh_token"
)

Jump to

Keyboard shortcuts

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