auth

package
v0.2.3 Latest Latest
Warning

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

Go to latest
Published: Jan 30, 2026 License: MIT Imports: 18 Imported by: 0

Documentation

Overview

Package auth provides OAuth 2.0 authentication for YouTube APIs.

Authorization Code Flow

The standard OAuth flow for server-side applications:

authClient := auth.NewAuthClient(auth.Config{
	ClientID:     "your-client-id",
	ClientSecret: "your-client-secret",
	RedirectURL:  "http://localhost:8080/callback",
	Scopes:       []string{auth.ScopeLiveChat, auth.ScopeLiveChatModerate},
})

// Generate authorization URL
url := authClient.AuthorizationURL("state-token")

// Exchange code for token
token, err := authClient.Exchange(ctx, code)

Device Code Flow

For devices with limited input capabilities (TVs, consoles, CLI apps):

deviceClient := auth.NewDeviceClient(auth.DeviceConfig{
	ClientID: "your-client-id",
	Scopes:   []string{auth.ScopeLiveChat},
})

// Request device code
authResp, err := deviceClient.RequestDeviceCode(ctx)
fmt.Printf("Go to %s and enter code: %s\n",
	authResp.VerificationURL, authResp.UserCode)

// Poll for authorization
token, err := deviceClient.PollForToken(ctx, authResp)

Service Account Authentication

For server-to-server communication without user interaction:

// From JSON credentials file
jsonData, _ := os.ReadFile("service-account.json")
client, err := auth.NewServiceAccountClientFromJSON(jsonData,
	[]string{auth.ScopeReadOnly})

// Or from config
client, err := auth.NewServiceAccountClient(auth.ServiceAccountConfig{
	Email:      "service@project.iam.gserviceaccount.com",
	PrivateKey: pemKey,
	Scopes:     []string{auth.ScopeReadOnly},
})

// Get access token (auto-refreshes)
token, err := client.AccessToken(ctx)

Token Management

Tokens are automatically refreshed when expired:

// Token includes access token, refresh token, and expiry
token := authClient.Token()

// Check if valid
if token.Valid() {
	// Use token
}

Scopes

Common YouTube API scopes:

  • ScopeLiveChat: Read live chat messages
  • ScopeLiveChatModerate: Moderate live chat (ban, delete, etc.)
  • ScopeReadOnly: Read-only access to YouTube data
  • ScopeUpload: Upload videos
  • ScopePartner: YouTube Analytics access

Index

Constants

View Source
const (
	DefaultAuthURL  = "https://accounts.google.com/o/oauth2/v2/auth"
	DefaultTokenURL = "https://oauth2.googleapis.com/token"
)

Google OAuth 2.0 endpoints.

View Source
const (
	// ScopeLiveChat grants read access to live chat messages.
	ScopeLiveChat = "https://www.googleapis.com/auth/youtube"

	// ScopeLiveChatModerate grants moderator access to live chat.
	ScopeLiveChatModerate = "https://www.googleapis.com/auth/youtube.force-ssl"

	// ScopeReadOnly grants read-only access to YouTube account.
	ScopeReadOnly = "https://www.googleapis.com/auth/youtube.readonly"

	// ScopeUpload grants access to upload videos and manage playlists.
	ScopeUpload = "https://www.googleapis.com/auth/youtube.upload"

	// ScopePartner grants access to YouTube Analytics.
	ScopePartner = "https://www.googleapis.com/auth/youtubepartner"

	// ScopePartnerChannelAudit grants access to YouTube Analytics monetary reports.
	ScopePartnerChannelAudit = "https://www.googleapis.com/auth/youtubepartner-channel-audit"
)

YouTube API scopes.

View Source
const DefaultDeviceCodeURL = "https://oauth2.googleapis.com/device/code"

Google Device Code endpoint.

Variables

This section is empty.

Functions

This section is empty.

Types

type AuthClient

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

AuthClient handles OAuth 2.0 authentication for YouTube APIs.

func NewAuthClient

func NewAuthClient(config Config, opts ...AuthClientOption) *AuthClient

NewAuthClient creates a new OAuth client.

func (*AuthClient) AccessToken

func (c *AuthClient) AccessToken(ctx context.Context) (string, error)

AccessToken returns a valid access token, refreshing if necessary.

func (*AuthClient) AuthorizationURL

func (c *AuthClient) AuthorizationURL(state string, opts ...AuthURLOption) string

AuthorizationURL returns the URL to redirect the user to for authorization.

func (*AuthClient) Exchange

func (c *AuthClient) Exchange(ctx context.Context, code string) (*Token, error)

Exchange exchanges an authorization code for a token.

func (*AuthClient) Refresh

func (c *AuthClient) Refresh(ctx context.Context) (*Token, error)

Refresh refreshes the access token using the refresh token.

func (*AuthClient) SetToken

func (c *AuthClient) SetToken(token *Token)

SetToken sets the token.

func (*AuthClient) StartAutoRefresh

func (c *AuthClient) StartAutoRefresh(ctx context.Context) error

StartAutoRefresh starts a goroutine that automatically refreshes the token.

func (*AuthClient) StopAutoRefresh

func (c *AuthClient) StopAutoRefresh()

StopAutoRefresh stops the auto-refresh goroutine.

func (*AuthClient) Token

func (c *AuthClient) Token() *Token

Token returns the current token (thread-safe clone).

type AuthClientOption

type AuthClientOption func(*AuthClient)

AuthClientOption configures an AuthClient.

func WithHTTPClient

func WithHTTPClient(hc *http.Client) AuthClientOption

WithHTTPClient sets a custom HTTP client.

func WithOnRefreshError

func WithOnRefreshError(fn func(error)) AuthClientOption

WithOnRefreshError sets a callback for refresh errors.

func WithOnTokenRefresh

func WithOnTokenRefresh(fn func(*Token)) AuthClientOption

WithOnTokenRefresh sets a callback for successful token refreshes.

func WithRefreshEarly

func WithRefreshEarly(d time.Duration) AuthClientOption

WithRefreshEarly sets how early to refresh tokens before expiry.

func WithToken

func WithToken(token *Token) AuthClientOption

WithToken sets an initial token.

type AuthError

type AuthError struct {
	Code    string // e.g., "invalid_grant", "expired_token"
	Message string
}

AuthError represents an OAuth authentication error.

func (*AuthError) Error

func (e *AuthError) Error() string

Error implements the error interface.

func (*AuthError) IsExpiredToken

func (e *AuthError) IsExpiredToken() bool

IsExpiredToken returns true if this is an expired token error.

func (*AuthError) IsInvalidGrant

func (e *AuthError) IsInvalidGrant() bool

IsInvalidGrant returns true if this is an invalid grant error.

type AuthURLOption

type AuthURLOption func(url.Values)

AuthURLOption configures the authorization URL.

func WithLoginHint

func WithLoginHint(hint string) AuthURLOption

WithLoginHint sets a hint for which account to use.

func WithPrompt

func WithPrompt(prompt string) AuthURLOption

WithPrompt sets the prompt parameter (e.g., "consent", "select_account").

type Config

type Config struct {
	// ClientID is the OAuth client ID.
	ClientID string

	// ClientSecret is the OAuth client secret.
	ClientSecret string

	// RedirectURL is the callback URL for the OAuth flow.
	RedirectURL string

	// Scopes are the requested OAuth scopes.
	Scopes []string

	// AuthURL is the authorization endpoint (defaults to Google's).
	AuthURL string

	// TokenURL is the token endpoint (defaults to Google's).
	TokenURL string
}

Config holds OAuth 2.0 configuration.

type DeviceAuthError added in v0.1.0

type DeviceAuthError struct {
	Code    string // e.g., "authorization_pending", "slow_down", "access_denied", "expired_token"
	Message string
}

DeviceAuthError represents a device authorization error.

func (*DeviceAuthError) Error added in v0.1.0

func (e *DeviceAuthError) Error() string

Error implements the error interface.

func (*DeviceAuthError) IsAccessDenied added in v0.1.0

func (e *DeviceAuthError) IsAccessDenied() bool

IsAccessDenied returns true if the user denied access.

func (*DeviceAuthError) IsAuthorizationPending added in v0.1.0

func (e *DeviceAuthError) IsAuthorizationPending() bool

IsAuthorizationPending returns true if the user hasn't authorized yet.

func (*DeviceAuthError) IsExpired added in v0.1.0

func (e *DeviceAuthError) IsExpired() bool

IsExpired returns true if the device code has expired.

func (*DeviceAuthError) IsSlowDown added in v0.1.0

func (e *DeviceAuthError) IsSlowDown() bool

IsSlowDown returns true if polling should slow down.

type DeviceAuthResponse added in v0.1.0

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

	// UserCode is the code the user enters at the verification URL.
	UserCode string `json:"user_code"`

	// VerificationURL is where the user should go to enter the code.
	VerificationURL string `json:"verification_uri"`

	// VerificationURLComplete is a URL that includes the user code (optional).
	VerificationURLComplete string `json:"verification_uri_complete,omitempty"`

	// ExpiresIn is how long the codes are valid for in seconds.
	ExpiresIn int `json:"expires_in"`

	// Interval is the minimum polling interval in seconds.
	Interval int `json:"interval"`
	// contains filtered or unexported fields
}

DeviceAuthResponse contains the response from the device authorization request.

func (*DeviceAuthResponse) Expired added in v0.1.0

func (d *DeviceAuthResponse) Expired() bool

Expired returns true if the device authorization has expired.

type DeviceClient added in v0.1.0

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

DeviceClient handles OAuth 2.0 Device Code Flow for limited-input devices.

func NewDeviceClient added in v0.1.0

func NewDeviceClient(config DeviceConfig, opts ...DeviceClientOption) *DeviceClient

NewDeviceClient creates a new Device Code Flow client.

func (*DeviceClient) PollForToken added in v0.1.0

func (c *DeviceClient) PollForToken(ctx context.Context, authResp *DeviceAuthResponse) (*Token, error)

PollForToken polls the token endpoint until the user authorizes or the code expires. This is a blocking call that handles the polling loop internally.

func (*DeviceClient) PollForTokenAsync added in v0.1.0

func (c *DeviceClient) PollForTokenAsync(ctx context.Context, authResp *DeviceAuthResponse) (<-chan *Token, <-chan error, context.CancelFunc)

PollForTokenAsync starts polling in a goroutine and returns channels for the result. The token channel receives the token when authorized. The error channel receives any error that occurs. The cancel function stops the polling.

func (*DeviceClient) RequestDeviceCode added in v0.1.0

func (c *DeviceClient) RequestDeviceCode(ctx context.Context) (*DeviceAuthResponse, error)

RequestDeviceCode initiates the device authorization flow. Returns the device authorization response containing the user code and verification URL.

type DeviceClientOption added in v0.1.0

type DeviceClientOption func(*DeviceClient)

DeviceClientOption configures a DeviceClient.

func WithDeviceHTTPClient added in v0.1.0

func WithDeviceHTTPClient(hc *http.Client) DeviceClientOption

WithDeviceHTTPClient sets a custom HTTP client.

type DeviceConfig added in v0.1.0

type DeviceConfig struct {
	// ClientID is the OAuth client ID.
	ClientID string

	// Scopes are the requested OAuth scopes.
	Scopes []string

	// DeviceCodeURL is the device authorization endpoint (defaults to Google's).
	DeviceCodeURL string

	// TokenURL is the token endpoint (defaults to Google's).
	TokenURL string
}

DeviceConfig holds configuration for Device Code Flow.

type ServiceAccountClient added in v0.1.0

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

ServiceAccountClient handles authentication using service account credentials.

func NewServiceAccountClient added in v0.1.0

func NewServiceAccountClient(config ServiceAccountConfig, opts ...ServiceAccountOption) (*ServiceAccountClient, error)

NewServiceAccountClient creates a new service account client.

func NewServiceAccountClientFromJSON added in v0.1.0

func NewServiceAccountClientFromJSON(jsonData []byte, scopes []string, opts ...ServiceAccountOption) (*ServiceAccountClient, error)

NewServiceAccountClientFromJSON creates a client from Google's JSON credentials file.

func (*ServiceAccountClient) AccessToken added in v0.1.0

func (c *ServiceAccountClient) AccessToken(ctx context.Context) (string, error)

AccessToken returns a valid access token, fetching a new one if necessary.

func (*ServiceAccountClient) FetchToken added in v0.1.0

func (c *ServiceAccountClient) FetchToken(ctx context.Context) (*Token, error)

FetchToken fetches a new access token using the service account credentials.

func (*ServiceAccountClient) StartAutoRefresh added in v0.1.0

func (c *ServiceAccountClient) StartAutoRefresh(ctx context.Context) error

StartAutoRefresh starts a goroutine that automatically refreshes the token.

func (*ServiceAccountClient) StopAutoRefresh added in v0.1.0

func (c *ServiceAccountClient) StopAutoRefresh()

StopAutoRefresh stops the auto-refresh goroutine.

func (*ServiceAccountClient) Token added in v0.1.0

func (c *ServiceAccountClient) Token() *Token

Token returns the current token (thread-safe clone).

type ServiceAccountConfig added in v0.1.0

type ServiceAccountConfig struct {
	// Email is the service account email address.
	Email string `json:"client_email"`

	// PrivateKey is the PEM-encoded RSA private key.
	PrivateKey string `json:"private_key"`

	// PrivateKeyID is the private key ID (optional).
	PrivateKeyID string `json:"private_key_id,omitempty"`

	// Scopes are the requested OAuth scopes.
	Scopes []string `json:"-"`

	// TokenURL is the token endpoint (defaults to Google's).
	TokenURL string `json:"token_uri,omitempty"`

	// Subject is the email of the user to impersonate (domain-wide delegation).
	Subject string `json:"-"`
}

ServiceAccountConfig holds configuration for service account authentication.

type ServiceAccountOption added in v0.1.0

type ServiceAccountOption func(*ServiceAccountClient)

ServiceAccountOption configures a ServiceAccountClient.

func WithServiceAccountHTTPClient added in v0.1.0

func WithServiceAccountHTTPClient(hc *http.Client) ServiceAccountOption

WithServiceAccountHTTPClient sets a custom HTTP client.

func WithServiceAccountOnRefreshError added in v0.1.0

func WithServiceAccountOnRefreshError(fn func(error)) ServiceAccountOption

WithServiceAccountOnRefreshError sets a callback for refresh errors.

func WithServiceAccountOnTokenRefresh added in v0.1.0

func WithServiceAccountOnTokenRefresh(fn func(*Token)) ServiceAccountOption

WithServiceAccountOnTokenRefresh sets a callback for successful token refreshes.

func WithServiceAccountRefreshEarly added in v0.1.0

func WithServiceAccountRefreshEarly(d time.Duration) ServiceAccountOption

WithServiceAccountRefreshEarly sets how early to refresh tokens before expiry.

func WithSubject added in v0.1.0

func WithSubject(email string) ServiceAccountOption

WithSubject sets the email of the user to impersonate (domain-wide delegation).

type Token

type Token struct {

	// AccessToken is the token used to authenticate API requests.
	AccessToken string `json:"access_token"`

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

	// RefreshToken is used to obtain a new access token.
	RefreshToken string `json:"refresh_token,omitempty"`

	// Expiry is the time when the access token expires.
	Expiry time.Time `json:"expiry,omitempty"`

	// Scopes are the granted OAuth scopes.
	Scopes []string `json:"scopes,omitempty"`
	// contains filtered or unexported fields
}

Token represents an OAuth 2.0 token.

func (*Token) Clone

func (t *Token) Clone() *Token

Clone returns a deep copy of the token.

func (*Token) Expired

func (t *Token) Expired() bool

Expired reports whether the token has expired.

func (*Token) ExpiresIn

func (t *Token) ExpiresIn() time.Duration

ExpiresIn returns the duration until the token expires. Returns 0 if the token has no expiry or is already expired.

func (*Token) GetAccessToken

func (t *Token) GetAccessToken() string

GetAccessToken returns the current access token.

func (*Token) GetRefreshToken

func (t *Token) GetRefreshToken() string

GetRefreshToken returns the refresh token.

func (*Token) MarshalJSON

func (t *Token) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (*Token) SetAccessToken

func (t *Token) SetAccessToken(accessToken string, expiry time.Time)

SetAccessToken updates the access token and expiry.

func (*Token) UnmarshalJSON

func (t *Token) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

func (*Token) Valid

func (t *Token) Valid() bool

Valid reports whether t is non-nil, has an AccessToken, and is not expired.