oauth2

package
v0.0.0-...-0dc11ae Latest Latest
Warning

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

Go to latest
Published: May 27, 2023 License: Apache-2.0 Imports: 9 Imported by: 0

README

oauth2

OAuth2 module of disgo

Getting Started

OAuth2 can be used to authenticate users with Discord on your website. For this to work, you need to create an application on the Discord Developer Portal and get the client ID and secret. Next you need to put in your redirect URL.

Usage

See here for an example.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrStateNotFound is returned when the state is not found in the SessionController.
	ErrStateNotFound = errors.New("state could not be found")

	// ErrSessionExpired is returned when the Session has expired.
	ErrSessionExpired = errors.New("access token expired. refresh the session")

	// ErrMissingOAuth2Scope is returned when a specific OAuth2 scope is missing.
	ErrMissingOAuth2Scope = func(scope discord.OAuth2Scope) error {
		return fmt.Errorf("missing '%s' scope", scope)
	}
)

Functions

This section is empty.

Types

type Client

type Client interface {
	// ID returns the configured client ID.
	ID() snowflake.ID
	// Secret returns the configured client secret.
	Secret() string
	// Rest returns the underlying rest.OAuth2.
	Rest() rest.OAuth2

	// StateController returns the configured StateController.
	StateController() StateController

	// GenerateAuthorizationURL generates an authorization URL with the given redirect URI, permissions, guildID, disableGuildSelect & scopes. State is automatically generated.
	GenerateAuthorizationURL(redirectURI string, permissions discord.Permissions, guildID snowflake.ID, disableGuildSelect bool, scopes ...discord.OAuth2Scope) string
	// GenerateAuthorizationURLState generates an authorization URL with the given redirect URI, permissions, guildID, disableGuildSelect & scopes. State is automatically generated & returned.
	GenerateAuthorizationURLState(redirectURI string, permissions discord.Permissions, guildID snowflake.ID, disableGuildSelect bool, scopes ...discord.OAuth2Scope) (string, string)

	// StartSession starts a new Session with the given authorization code & state.
	StartSession(code string, state string, opts ...rest.RequestOpt) (Session, *discord.IncomingWebhook, error)
	// RefreshSession refreshes the given Session with the refresh token.
	RefreshSession(session Session, opts ...rest.RequestOpt) (Session, error)
	// VerifySession verifies the given Session & refreshes it if needed.
	VerifySession(session Session, opts ...rest.RequestOpt) (Session, error)

	// GetUser returns the discord.OAuth2User associated with the given Session. Fields filled in the struct depend on the Session.Scopes.
	GetUser(session Session, opts ...rest.RequestOpt) (*discord.OAuth2User, error)
	// GetMember returns the discord.Member associated with the given Session in a specific guild.
	GetMember(session Session, guildID snowflake.ID, opts ...rest.RequestOpt) (*discord.Member, error)
	// GetGuilds returns the discord.OAuth2Guild(s) the user is a member of. This requires the discord.OAuth2ScopeGuilds scope in the Session.
	GetGuilds(session Session, opts ...rest.RequestOpt) ([]discord.OAuth2Guild, error)
	// GetConnections returns the discord.Connection(s) the user has connected. This requires the discord.OAuth2ScopeConnections scope in the Session.
	GetConnections(session Session, opts ...rest.RequestOpt) ([]discord.Connection, error)
	// GetApplicationRoleConnection returns the discord.ApplicationRoleConnection for the given application. This requires the discord.OAuth2ScopeRoleConnectionsWrite scope in the Session.
	GetApplicationRoleConnection(session Session, applicationID snowflake.ID, opts ...rest.RequestOpt) (*discord.ApplicationRoleConnection, error)
	// UpdateApplicationRoleConnection updates the discord.ApplicationRoleConnection for the given application. This requires the discord.OAuth2ScopeRoleConnectionsWrite scope in the Session.
	UpdateApplicationRoleConnection(session Session, applicationID snowflake.ID, update discord.ApplicationRoleConnectionUpdate, opts ...rest.RequestOpt) (*discord.ApplicationRoleConnection, error)
}

Client is a high level wrapper around Discord's OAuth2 API.

func New

func New(id snowflake.ID, secret string, opts ...ConfigOpt) Client

New returns a new OAuth2 client with the given ID, secret and ConfigOpt(s).

type Config

type Config struct {
	Logger                    log.Logger
	RestClient                rest.Client
	RestClientConfigOpts      []rest.ConfigOpt
	OAuth2                    rest.OAuth2
	StateController           StateController
	StateControllerConfigOpts []StateControllerConfigOpt
}

Config is the configuration for the OAuth2 client

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig is the configuration which is used by default

func (*Config) Apply

func (c *Config) Apply(opts []ConfigOpt)

Apply applies the given ConfigOpt(s) to the Config

type ConfigOpt

type ConfigOpt func(config *Config)

ConfigOpt can be used to supply optional parameters to New

func WithLogger

func WithLogger(logger log.Logger) ConfigOpt

WithLogger applies a custom logger to the OAuth2 client

func WithOAuth2

func WithOAuth2(oauth2 rest.OAuth2) ConfigOpt

WithOAuth2 applies a custom rest.OAuth2 to the OAuth2 client

func WithRestClient

func WithRestClient(restClient rest.Client) ConfigOpt

WithRestClient applies a custom rest.Client to the OAuth2 client

func WithRestClientConfigOpts

func WithRestClientConfigOpts(opts ...rest.ConfigOpt) ConfigOpt

WithRestClientConfigOpts applies rest.ConfigOpt for the rest.Client to the OAuth2 client

func WithStateController

func WithStateController(stateController StateController) ConfigOpt

WithStateController applies a custom StateController to the OAuth2 client

func WithStateControllerOpts

func WithStateControllerOpts(opts ...StateControllerConfigOpt) ConfigOpt

WithStateControllerOpts applies all StateControllerConfigOpt(s) to the StateController

type Session

type Session struct {
	// AccessToken allows requesting user information
	AccessToken string `json:"access_token"`

	// RefreshToken allows refreshing the AccessToken
	RefreshToken string `json:"refresh_token"`

	// Scopes returns the discord.OAuth2Scope(s) of the Session
	Scopes []discord.OAuth2Scope `json:"scopes"`

	// TokenType returns the discord.TokenType of the AccessToken
	TokenType discord.TokenType `json:"token_type"`

	// Expiration returns the time.Time when the AccessToken expires and needs to be refreshed
	Expiration time.Time `json:"expiration"`
}

Session represents a discord access token response (https://discord.com/developers/docs/topics/oauth2#authorization-code-grant-access-token-response)

func (Session) Expired

func (s Session) Expired() bool

type StateController

type StateController interface {
	// NewState generates a new random state to be used as a state.
	NewState(redirectURI string) string

	// UseState validates a state and returns the redirect url or nil if it is invalid.
	UseState(state string) string
}

StateController is responsible for generating, storing and validating states.

func NewStateController

func NewStateController(opts ...StateControllerConfigOpt) StateController

NewStateController returns a new empty StateController.

type StateControllerConfig

type StateControllerConfig struct {
	Logger       log.Logger
	States       map[string]string
	NewStateFunc func() string
	MaxTTL       time.Duration
}

StateControllerConfig is the configuration for the StateController

func DefaultStateControllerConfig

func DefaultStateControllerConfig() *StateControllerConfig

DefaultStateControllerConfig is the default configuration for the StateController

func (*StateControllerConfig) Apply

Apply applies the given StateControllerConfigOpt(s) to the StateControllerConfig

type StateControllerConfigOpt

type StateControllerConfigOpt func(config *StateControllerConfig)

StateControllerConfigOpt is used to pass optional parameters to NewStateController

func WithMaxTTL

func WithMaxTTL(maxTTL time.Duration) StateControllerConfigOpt

WithMaxTTL sets the maximum time to live for a state

func WithNewStateFunc

func WithNewStateFunc(newStateFunc func() string) StateControllerConfigOpt

WithNewStateFunc sets the function which is used to generate a new random state

func WithStateControllerLogger

func WithStateControllerLogger(logger log.Logger) StateControllerConfigOpt

WithStateControllerLogger sets the logger for the StateController

func WithStates

func WithStates(states map[string]string) StateControllerConfigOpt

WithStates loads states from an existing map

Jump to

Keyboard shortcuts

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