oauth

package
v0.1.18 Latest Latest
Warning

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

Go to latest
Published: Jul 17, 2025 License: Apache-2.0 Imports: 18 Imported by: 1

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrProviderNotSupported = fmt.Errorf("OAuth provider not supported")
	ErrProviderNotEnabled   = fmt.Errorf("OAuth provider not enabled")
	ErrInvalidConfiguration = fmt.Errorf("invalid OAuth configuration")
	ErrInvalidState         = fmt.Errorf("invalid OAuth state parameter")
	ErrStateExpired         = fmt.Errorf("OAuth state parameter expired")
	ErrCodeExchangeFailed   = fmt.Errorf("OAuth code exchange failed")
	ErrTokenRefreshFailed   = fmt.Errorf("OAuth token refresh failed")
	ErrProfileFetchFailed   = fmt.Errorf("failed to fetch user profile")
	ErrInvalidToken         = fmt.Errorf("invalid OAuth token")
	ErrTokenRevokeFailed    = fmt.Errorf("OAuth token revocation failed")
	ErrMissingRequiredScope = fmt.Errorf("missing required OAuth scope")
)

OAuth specific errors

Functions

func CompareConfigs added in v0.1.9

func CompareConfigs(a, b *Config) bool

CompareConfigs compares two OAuth configurations

func GetEnabledProviders added in v0.1.9

func GetEnabledProviders(config *Config) []string

GetEnabledProviders returns list of enabled providers

func GetSupportedProviders added in v0.1.9

func GetSupportedProviders() []string

GetSupportedProviders returns list of supported providers

func GetTokenFromContext added in v0.1.9

func GetTokenFromContext(ctx context.Context) string

GetTokenFromContext extracts OAuth token from context

func IsProviderEnabled added in v0.1.9

func IsProviderEnabled(config *Config, provider string) bool

IsProviderEnabled checks if provider is enabled in config

func MergeParams added in v0.1.9

func MergeParams(params ...map[string]string) map[string]string

MergeParams merges multiple parameter maps

func Middleware added in v0.1.9

func Middleware(client ClientInterface, opts *MiddlewareOptions) func(http.Handler) http.Handler

Middleware creates OAuth validation middleware

func NormalizeProviderName added in v0.1.9

func NormalizeProviderName(provider string) string

NormalizeProviderName normalizes provider name to lowercase

func ValidateConfig added in v0.1.9

func ValidateConfig(config *Config) error

ValidateConfig validates OAuth configuration

func ValidateProvider added in v0.1.9

func ValidateProvider(provider string) bool

ValidateProvider checks if provider is supported

func ValidateRequiredScopes added in v0.1.9

func ValidateRequiredScopes(provider string, requestedScopes []string) error

ValidateRequiredScopes checks if required scopes are present

Types

type Client added in v0.1.9

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

Client implements OAuth client functionality

func NewClient added in v0.1.9

func NewClient(config *Config) *Client

NewClient creates a new OAuth client

func (*Client) ExchangeCodeForToken added in v0.1.9

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

ExchangeCodeForToken exchanges authorization code for access token

func (*Client) GetAuthURL added in v0.1.9

func (c *Client) GetAuthURL(provider Provider, state string, additionalParams map[string]string) (string, error)

GetAuthURL generates OAuth authorization URL

func (*Client) GetUserProfile added in v0.1.9

func (c *Client) GetUserProfile(ctx context.Context, provider Provider, accessToken string) (*Profile, error)

GetUserProfile gets user profile from OAuth provider

func (*Client) RefreshAccessToken added in v0.1.9

func (c *Client) RefreshAccessToken(ctx context.Context, provider Provider, refreshToken string) (*TokenResponse, error)

RefreshAccessToken refreshes access token using refresh token

func (*Client) RevokeToken added in v0.1.9

func (c *Client) RevokeToken(ctx context.Context, provider Provider, token string) error

RevokeToken revokes an access token

func (*Client) ValidateToken added in v0.1.9

func (c *Client) ValidateToken(ctx context.Context, provider Provider, token string) (*TokenInfo, error)

ValidateToken validates an access token

type ClientInterface added in v0.1.9

type ClientInterface interface {
	GetAuthURL(provider Provider, state string, additionalParams map[string]string) (string, error)
	ExchangeCodeForToken(ctx context.Context, provider Provider, code string, codeVerifier ...string) (*TokenResponse, error)
	RefreshAccessToken(ctx context.Context, provider Provider, refreshToken string) (*TokenResponse, error)
	GetUserProfile(ctx context.Context, provider Provider, accessToken string) (*Profile, error)
	ValidateToken(ctx context.Context, provider Provider, token string) (*TokenInfo, error)
	RevokeToken(ctx context.Context, provider Provider, token string) error
}

ClientInterface defines OAuth client interface

type Config added in v0.1.9

type Config struct {
	Providers    map[string]*ProviderConfig `json:"providers" yaml:"providers"`
	DefaultScope []string                   `json:"default_scope" yaml:"default_scope"`
	EnablePKCE   bool                       `json:"enable_pkce" yaml:"enable_pkce"`
	StateSecret  string                     `json:"state_secret" yaml:"state_secret"`
}

Config represents OAuth configuration

func CloneConfig added in v0.1.9

func CloneConfig(config *Config) *Config

CloneConfig creates a deep copy of OAuth config

func GetConfig added in v0.1.9

func GetConfig(v *viper.Viper) *Config

GetConfig loads OAuth configuration from viper

type Error added in v0.1.9

type Error struct {
	Provider string
	Code     string
	Message  string
	Err      error
}

Error represents an OAuth specific error

func NewOAuthError added in v0.1.9

func NewOAuthError(provider, code, message string, err error) *Error

NewOAuthError creates a new OAuth error

func (*Error) Error added in v0.1.9

func (e *Error) Error() string

Error implements the error interface

func (*Error) Unwrap added in v0.1.9

func (e *Error) Unwrap() error

Unwrap returns the underlying error

type MiddlewareOptions added in v0.1.9

type MiddlewareOptions struct {
	TokenLookup    string                                             // "header:Authorization,query:token,cookie:oauth_token"
	AuthScheme     string                                             // "Bearer" or "Token"
	SkipPaths      []string                                           // Paths to skip OAuth validation
	ErrorHandler   func(http.ResponseWriter, *http.Request)           // Custom error handler
	SuccessHandler func(http.ResponseWriter, *http.Request, *Profile) // Success handler
}

MiddlewareOptions represents middleware configuration options

type PKCEData added in v0.1.9

type PKCEData struct {
	CodeVerifier  string `json:"code_verifier"`
	CodeChallenge string `json:"code_challenge"`
	Method        string `json:"method"` // "S256" or "plain"
}

PKCEData represents PKCE challenge data

type Profile

type Profile struct {
	ID       string `json:"id"`
	Email    string `json:"email"`
	Name     string `json:"name"`
	Avatar   string `json:"avatar"`
	Username string `json:"username"`
	Provider string `json:"provider"`
	Verified bool   `json:"verified"`
	Locale   string `json:"locale,omitempty"`
}

Profile represents user profile from OAuth provider

func GetProfileFromContext added in v0.1.9

func GetProfileFromContext(ctx context.Context) *Profile

GetProfileFromContext extracts user profile from context

type Provider added in v0.1.9

type Provider string

Provider represents OAuth provider type

const (
	ProviderGoogle    Provider = "google"
	ProviderGitHub    Provider = "github"
	ProviderFacebook  Provider = "facebook"
	ProviderMicrosoft Provider = "microsoft"
	ProviderApple     Provider = "apple"
	ProviderTwitter   Provider = "twitter"
	ProviderLinkedIn  Provider = "linkedin"
	ProviderTikTok    Provider = "tiktok"
	ProviderWeChat    Provider = "wechat"
	ProviderAlipay    Provider = "alipay"
	ProviderBaidu     Provider = "baidu"
	ProviderWeibo     Provider = "weibo"
	ProviderQQ        Provider = "qq"
)

type ProviderConfig

type ProviderConfig struct {
	ClientID     string            `json:"client_id" yaml:"client_id"`
	ClientSecret string            `json:"client_secret" yaml:"client_secret"`
	RedirectURL  string            `json:"redirect_url" yaml:"redirect_url"`
	Scopes       []string          `json:"scopes" yaml:"scopes"`
	AuthURL      string            `json:"auth_url" yaml:"auth_url"`
	TokenURL     string            `json:"token_url" yaml:"token_url"`
	UserInfoURL  string            `json:"user_info_url" yaml:"user_info_url"`
	RevokeURL    string            `json:"revoke_url" yaml:"revoke_url"`
	Enabled      bool              `json:"enabled" yaml:"enabled"`
	ExtraParams  map[string]string `json:"extra_params" yaml:"extra_params"`
}

ProviderConfig represents OAuth provider configuration

type ProviderInfo added in v0.1.9

type ProviderInfo struct {
	Name               string   `json:"name"`
	DisplayName        string   `json:"display_name"`
	Icon               string   `json:"icon"`
	SupportedScopes    []string `json:"supported_scopes"`
	RequiredScopes     []string `json:"required_scopes"`
	SupportsPKCE       bool     `json:"supports_pkce"`
	SupportsRefresh    bool     `json:"supports_refresh"`
	SupportsRevocation bool     `json:"supports_revocation"`
}

ProviderInfo represents provider capability information

func GetProviderInfo added in v0.1.9

func GetProviderInfo(provider string) *ProviderInfo

GetProviderInfo returns provider capability information

type ProviderSpecificClient added in v0.1.9

type ProviderSpecificClient struct {
	*Client
}

ProviderSpecificClient handles provider-specific OAuth implementations

func NewProviderSpecificClient added in v0.1.9

func NewProviderSpecificClient(config *Config) *ProviderSpecificClient

NewProviderSpecificClient creates a client with provider-specific implementations

func (*ProviderSpecificClient) GenerateAppleClientSecret added in v0.1.9

func (c *ProviderSpecificClient) GenerateAppleClientSecret(keyID, teamID, clientID, privateKeyPEM string) (string, error)

GenerateAppleClientSecret generates Apple client secret JWT

func (*ProviderSpecificClient) HandleAppleAuth added in v0.1.9

func (c *ProviderSpecificClient) HandleAppleAuth(ctx context.Context, code, idToken string) (*Profile, *TokenResponse, error)

HandleAppleAuth handles Apple Sign In specific logic

func (*ProviderSpecificClient) HandleTwitterOAuth2 added in v0.1.9

func (c *ProviderSpecificClient) HandleTwitterOAuth2(ctx context.Context, codeVerifier, code string) (*Profile, *TokenResponse, error)

HandleTwitterOAuth2 handles Twitter OAuth 2.0 with PKCE

type StateData added in v0.1.9

type StateData struct {
	Provider  string    `json:"provider"`
	NextURL   string    `json:"next_url,omitempty"`
	UserID    string    `json:"user_id,omitempty"`
	Action    string    `json:"action,omitempty"` // "login", "register", "link"
	Timestamp int64     `json:"timestamp"`
	Nonce     string    `json:"nonce"`
	PKCE      *PKCEData `json:"pkce,omitempty"`
}

StateData represents OAuth state information

type StateManager added in v0.1.9

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

StateManager manages OAuth state parameters

func NewStateManager added in v0.1.9

func NewStateManager(secret string) *StateManager

NewStateManager creates a new state manager

func (*StateManager) GeneratePKCE added in v0.1.9

func (sm *StateManager) GeneratePKCE() (*PKCEData, error)

GeneratePKCE generates PKCE challenge data

func (*StateManager) GenerateState added in v0.1.9

func (sm *StateManager) GenerateState(data *StateData) (string, error)

GenerateState generates a secure state parameter

func (*StateManager) ParseState added in v0.1.9

func (sm *StateManager) ParseState(state string) (*StateData, error)

ParseState parses and validates state parameter

type TokenInfo added in v0.1.9

type TokenInfo struct {
	Valid     bool      `json:"valid"`
	ExpiresAt time.Time `json:"expires_at"`
	Scope     string    `json:"scope"`
	ClientID  string    `json:"client_id"`
}

TokenInfo represents token validation information

type TokenResponse added in v0.1.9

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

TokenResponse represents OAuth token response

Jump to

Keyboard shortcuts

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