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

social

package
v1.9.0 Latest Latest
Warning

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

Go to latest
Published: Nov 2, 2026 License: MIT Imports: 60 Imported by: 0

README

social

Sign in with Google, GitHub, Apple, Microsoft and about thirty others.

The plugin runs the whole OAuth2 dance: the redirect out, the callback, the code exchange, and the profile fetch. What comes back gets linked to a core user account, so a person who signed up with a password can add GitHub later and both routes land on the same identity.

Providers can be configured in code at startup or added at runtime through the admin routes, which is the difference between shipping a release and flipping a switch.

Use it when

  • You want signup in one click, with no password and no email round trip
  • Your users already live in one ecosystem, GitHub for a developer tool, Google for most consumer products
  • You want verified email addresses for free, since the provider already did that work

Skip it when

  • You are building for enterprise buyers. They want sso against their own identity provider, not personal Google accounts
  • You cannot register a stable callback URL. Every provider pins it, and a mismatch fails the flow
  • Account linking rules matter to you and you have not thought them through. Two providers returning the same email is a decision, not an accident

Wiring

authsome.WithPlugin(social.New(social.Config{
    Domain: "https://api.example.com",
    Providers: []social.Provider{
        social.NewGoogleProvider(social.ProviderConfig{
            ClientID:     googleID,
            ClientSecret: googleSecret,
        }),
        social.NewGitHubProvider(social.ProviderConfig{
            ClientID:     githubID,
            ClientSecret: githubSecret,
        }),
    },
}))

Set Domain and the callback URL is derived for you as {Domain}/v1/social/{provider}/callback. Leave it empty and the URL comes off the request Host header, which is fine locally and risky behind a proxy.

Config

Field Type Default What it does
Providers []Provider empty Providers enabled at startup
Domain string request host External base URL used to build callback URLs
SessionTokenTTL time.Duration 1h Lifetime of a session created by social sign-in
SessionRefreshTTL time.Duration 30d Lifetime of that session's refresh token

Settings

Key Default
social.providers []
social.session_token_ttl_seconds 3600
social.session_refresh_ttl_seconds 2592000
auth.allowed_frontend_urls empty

auth.allowed_frontend_urls is the redirect allowlist. Fill it in. An open redirect on an OAuth callback is how tokens get stolen.

Endpoints

Method Path Purpose
POST /v1/social/:provider Start the OAuth flow
GET /v1/social/:provider/callback Handle the provider callback and mint a session
GET /v1/social/providers List providers available to the caller
GET /v1/admin/social/providers/catalog Every provider the plugin supports
GET /v1/admin/social/providers List configured providers
PUT /v1/admin/social/providers/:provider Configure a provider at runtime
DELETE /v1/admin/social/providers/:provider Remove a provider

Lifecycle hooks

None on the sign-in path. It registers as an AuthMethodContributor and an AuthMethodUnlinker, so a user can see and disconnect a linked provider, plus a MigrationProvider for the connection table.

Providers

Amazon, Apple, Bitbucket, Discord, Dropbox, Facebook, GitHub, GitLab, Google, Instagram, LINE, LinkedIn, Microsoft, Patreon, Pinterest, Slack, Spotify, Strava, Twitch, Twitter, Yahoo, Zoom.

sso is the enterprise equivalent, scoped per organisation. oauth2provider is the mirror image: it makes you the provider other people sign in with.

Documentation

Overview

contract.go: Wires the social plugin into the forge-dashboard contract surface via plugin.ContractContributor.

Package social provides OAuth2-based social login authentication for AuthSome.

The social plugin enables users to sign in with third-party OAuth2 providers such as Google, GitHub, Apple, and Microsoft. It manages the full OAuth2 flow including authorization redirect, callback handling, token exchange, and user profile fetching. Social connections are stored per-user and linked to the core user account.

Usage:

eng, _ := authsome.NewEngine(
    authsome.WithStore(store),
    authsome.WithPlugin(social.New(social.Config{
        Providers: []social.Provider{
            social.Google("client-id", "client-secret", "https://example.com/callback"),
        },
    })),
)

Package social provides OAuth2 social authentication for AuthSome.

The social plugin handles OAuth2 sign-in flows for external providers like Google and GitHub. It manages OAuth connections that link external provider accounts to AuthSome users.

Usage:

p := social.New(social.Config{
    Providers: []social.Provider{
        social.NewGoogleProvider(social.ProviderConfig{
            ClientID:     "your-client-id",
            ClientSecret: "your-secret",
            RedirectURL:  "https://app.com/api/auth/social/google/callback",
        }),
        social.NewGitHubProvider(social.ProviderConfig{
            ClientID:     "your-client-id",
            ClientSecret: "your-secret",
            RedirectURL:  "https://app.com/api/auth/social/github/callback",
        }),
    },
})

Index

Constants

This section is empty.

Variables

View Source
var (
	// SettingSessionTokenTTLSeconds controls the session token lifetime for social sign-in.
	SettingSessionTokenTTLSeconds = settings.Define("social.session_token_ttl_seconds", 3600,
		settings.WithDisplayName("Session Token TTL (seconds)"),
		settings.WithDescription("Lifetime of sessions created via social sign-in in seconds"),
		settings.WithCategory("Social OAuth"),
		settings.WithScopes(settings.ScopeGlobal, settings.ScopeApp),
		settings.WithInputType(formconfig.FieldNumber),
		settings.WithUIValidation(formconfig.Validation{Required: true, Min: intPtr(300), Max: intPtr(86400)}),
		settings.WithHelpText("How long sessions created via social login remain valid. Default: 3600 (1 hour)"),
		settings.WithOrder(10),
	)

	// SettingSessionRefreshTTLSeconds controls the refresh token lifetime for social sessions.
	SettingSessionRefreshTTLSeconds = settings.Define("social.session_refresh_ttl_seconds", 2592000,
		settings.WithDisplayName("Refresh Token TTL (seconds)"),
		settings.WithDescription("Lifetime of refresh tokens for social sign-in sessions in seconds"),
		settings.WithCategory("Social OAuth"),
		settings.WithScopes(settings.ScopeGlobal, settings.ScopeApp),
		settings.WithInputType(formconfig.FieldNumber),
		settings.WithUIValidation(formconfig.Validation{Required: true, Min: intPtr(3600), Max: intPtr(7776000)}),
		settings.WithHelpText("How long refresh tokens remain valid. Default: 2592000 (30 days)"),
		settings.WithOrder(20),
	)
)
View Source
var ErrConnectionExists = errors.New("social: oauth connection already exists for this provider user")

ErrConnectionExists is returned when an app already holds a connection for the provider user, the memory store's counterpart of the unique index.

View Source
var ErrConnectionNotFound = errors.New("social: oauth connection not found")

ErrConnectionNotFound is returned when an OAuth connection is not found.

View Source
var PostgresMigrations = migrate.NewGroup("authsome-social", migrate.DependsOn("authsome"))

PostgresMigrations is the postgres migration group for the social plugin.

View Source
var SettingAllowedFrontendURLs = settings.Define("auth.allowed_frontend_urls", "",
	settings.WithDisplayName("Allowed Frontend URLs"),
	settings.WithDescription("Comma-separated origins (scheme://host[:port]) that may be used as frontend_url or redirect_url targets."),
	settings.WithCategory("Authentication"),
	settings.WithScopes(settings.ScopeGlobal, settings.ScopeApp),
	settings.WithInputType(formconfig.FieldText),
	settings.WithPlaceholder("https://app.example,https://staging.app.example"),
)

SettingAllowedFrontendURLs is the per-app CSV of origin hosts the social plugin trusts as redirect/frontend authorities. Empty means absolute redirects are rejected outright.

Match policy (see isAllowedOrigin):

View Source
var SettingSocialProviders = settings.Define("social.providers", []ProviderSetting{},
	settings.WithDisplayName("Social Providers"),
	settings.WithDescription("Social OAuth providers configured via dashboard"),
	settings.WithCategory("Social OAuth"),
	settings.WithScopes(settings.ScopeGlobal, settings.ScopeApp),
	settings.WithSensitive(),
	settings.WithOrder(30),
	settings.WithObjectFields(
		settings.ObjectFieldDef{
			Key:         "name",
			DisplayName: "Provider",
			InputType:   formconfig.FieldSelect,
			Required:    true,
			Options: []formconfig.SelectOption{
				{Label: "Google", Value: "google"},
				{Label: "GitHub", Value: "github"},
				{Label: "Apple", Value: "apple"},
				{Label: "Microsoft", Value: "microsoft"},
				{Label: "Facebook", Value: "facebook"},
				{Label: "LinkedIn", Value: "linkedin"},
				{Label: "Discord", Value: "discord"},
				{Label: "Slack", Value: "slack"},
				{Label: "Twitter", Value: "twitter"},
				{Label: "Spotify", Value: "spotify"},
				{Label: "Twitch", Value: "twitch"},
				{Label: "GitLab", Value: "gitlab"},
				{Label: "Bitbucket", Value: "bitbucket"},
				{Label: "Dropbox", Value: "dropbox"},
				{Label: "Yahoo", Value: "yahoo"},
				{Label: "Amazon", Value: "amazon"},
				{Label: "Zoom", Value: "zoom"},
				{Label: "Pinterest", Value: "pinterest"},
				{Label: "Strava", Value: "strava"},
				{Label: "Patreon", Value: "patreon"},
				{Label: "Instagram", Value: "instagram"},
				{Label: "Line", Value: "line"},
			},
		},
		settings.ObjectFieldDef{
			Key:         "client_id",
			DisplayName: "Client ID",
			InputType:   formconfig.FieldText,
			Required:    true,
			Placeholder: "OAuth client ID",
		},
		settings.ObjectFieldDef{
			Key:         "client_secret",
			DisplayName: "Client Secret",
			InputType:   formconfig.FieldText,
			Required:    true,
			Sensitive:   true,
			Placeholder: "OAuth client secret",
		},
		settings.ObjectFieldDef{
			Key:         "redirect_url",
			DisplayName: "Redirect URL",
			InputType:   formconfig.FieldURL,
			Placeholder: "https://example.com/auth/callback",
			HelpText:    "The OAuth callback URL registered with the provider",
		},
		settings.ObjectFieldDef{
			Key:         "scopes",
			DisplayName: "Scopes",
			InputType:   formconfig.FieldTextarea,
			Placeholder: "openid\nprofile\nemail",
			HelpText:    "One scope per line",
		},
		settings.ObjectFieldDef{
			Key:         "enabled",
			DisplayName: "Enabled",
			InputType:   formconfig.FieldSwitch,
		},
	),
)

SettingSocialProviders stores dashboard-configured social providers.

View Source
var SqliteMigrations = migrate.NewGroup("authsome-social", migrate.DependsOn("authsome"))

SqliteMigrations is the SQLite migration group for the social plugin.

Functions

This section is empty.

Types

type AdminCatalogProvider added in v1.9.0

type AdminCatalogProvider struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

AdminCatalogProvider is one entry in the supported-provider catalog.

type AdminCatalogResponse added in v1.9.0

type AdminCatalogResponse struct {
	Providers []AdminCatalogProvider `json:"providers"`
}

AdminCatalogResponse is the response for GET /v1/admin/social/providers/catalog.

type AdminDeleteProviderRequest added in v1.9.0

type AdminDeleteProviderRequest struct {
	Provider string `path:"provider" description:"Provider ID"`
	AppID    string `query:"app_id"  description:"App identifier; omit for global scope"`
}

AdminDeleteProviderRequest binds the path + query for DELETE.

type AdminDeleteProviderResponse added in v1.9.0

type AdminDeleteProviderResponse struct {
	Status string `json:"status"`
}

AdminDeleteProviderResponse mirrors the StatusResponse shape.

type AdminListProvidersRequest added in v1.9.0

type AdminListProvidersRequest struct {
	AppID string `query:"app_id" description:"App identifier; omit for global scope"`
}

AdminListProvidersRequest binds the query for GET /v1/admin/social/providers.

type AdminListProvidersResponse added in v1.9.0

type AdminListProvidersResponse struct {
	Providers []AdminProvider `json:"providers"`
}

AdminListProvidersResponse is the listing response.

type AdminProvider added in v1.9.0

type AdminProvider struct {
	Name         string   `json:"name"`
	ClientID     string   `json:"client_id"`
	ClientSecret string   `json:"client_secret,omitempty"`
	RedirectURL  string   `json:"redirect_url,omitempty"`
	Scopes       []string `json:"scopes,omitempty"`
	Enabled      bool     `json:"enabled"`
	HasSecret    bool     `json:"has_secret"`
}

AdminProvider is the read-side shape for a configured provider. ClientSecret is masked (returns the literal "***" when set, empty when unset) so the admin UI can render "secret is configured" without echoing the value back.

type AdminProviderResponse added in v1.9.0

type AdminProviderResponse struct {
	Provider AdminProvider `json:"provider"`
}

AdminProviderResponse is the response after upsert.

type AdminUpsertProviderRequest added in v1.9.0

type AdminUpsertProviderRequest struct {
	Provider string `path:"provider" description:"Provider ID (google, github, ...)"`
	AppID    string `query:"app_id" description:"App identifier; omit for global scope"`

	ClientID     string   `json:"client_id"      description:"OAuth client ID"`
	ClientSecret string   `json:"client_secret"  description:"OAuth client secret. Pass empty string to leave the existing value unchanged."`
	RedirectURL  string   `json:"redirect_url,omitempty"`
	Scopes       []string `json:"scopes,omitempty"`
	Enabled      *bool    `json:"enabled,omitempty"`
}

AdminUpsertProviderRequest binds the path + body for PUT.

type CallbackRequest added in v0.0.7

type CallbackRequest struct {
	Provider string `path:"provider"`
	State    string `query:"state,omitempty"`
	Code     string `query:"code,omitempty"`
	Error    string `query:"error,omitempty"`
}

CallbackRequest contains the path and query parameters for the OAuth callback.

type CallbackResponse

type CallbackResponse struct {
	User         any    `json:"user"`
	SessionToken string `json:"session_token"`
	RefreshToken string `json:"refresh_token"`
	ExpiresAt    any    `json:"expires_at"`
	Provider     string `json:"provider"`
	IsNewUser    bool   `json:"is_new_user"`
	RedirectURL  string `json:"redirect_url,omitempty"`
	FrontendURL  string `json:"frontend_url,omitempty"`
}

CallbackResponse is returned on successful OAuth authentication.

RedirectURL and FrontendURL echo the values stashed in the OAuth state during handleStart so non-browser callers (mobile apps, native flows) can route the user without having to track them separately.

type Config

type Config struct {
	// Providers is the list of enabled OAuth providers.
	Providers []Provider

	// Domain is the external base URL of the server (e.g. "https://api.example.com").
	// When a provider does not specify a RedirectURL, the callback URL is
	// auto-generated as {Domain}/v1/social/{provider}/callback.
	// If empty, the callback URL is derived from the incoming request's Host header.
	Domain string

	// SessionTokenTTL is the lifetime of sessions created via social sign-in (default: 1 hour).
	SessionTokenTTL time.Duration

	// SessionRefreshTTL is the lifetime of refresh tokens (default: 30 days).
	SessionRefreshTTL time.Duration
}

Config configures the social OAuth plugin.

type EncryptedStore added in v1.9.0

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

EncryptedStore wraps a Store, transparently encrypting AccessToken / RefreshToken before they reach the underlying storage and decrypting them on the way back out.

The wrapper is safe to use over a store that already contains legacy plaintext rows — bridge.AESGCMEncryptor's Decrypt returns plaintext unchanged when no envelope prefix is present.

func NewEncryptedStore added in v1.9.0

func NewEncryptedStore(inner Store, enc bridge.Encryptor) *EncryptedStore

NewEncryptedStore wraps inner with token encryption. If enc is nil, a bridge.NoopEncryptor is used (no encryption). Pass an AES-GCM encryptor in production.

func (*EncryptedStore) CreateOAuthConnection added in v1.9.0

func (s *EncryptedStore) CreateOAuthConnection(ctx context.Context, c *OAuthConnection) error

CreateOAuthConnection encrypts tokens then delegates to the inner store. The caller's *OAuthConnection is left untouched.

func (*EncryptedStore) DeleteOAuthConnection added in v1.9.0

func (s *EncryptedStore) DeleteOAuthConnection(ctx context.Context, connID id.OAuthConnectionID) error

DeleteOAuthConnection delegates without modification.

func (*EncryptedStore) GetOAuthConnection added in v1.9.0

func (s *EncryptedStore) GetOAuthConnection(ctx context.Context, appID id.AppID, provider, providerUserID string) (*OAuthConnection, error)

GetOAuthConnection decrypts tokens before returning the connection.

func (*EncryptedStore) GetOAuthConnectionsByUserID added in v1.9.0

func (s *EncryptedStore) GetOAuthConnectionsByUserID(ctx context.Context, userID id.UserID) ([]*OAuthConnection, error)

GetOAuthConnectionsByUserID decrypts tokens for each connection.

func (*EncryptedStore) UpdateOAuthConnection added in v1.9.0

func (s *EncryptedStore) UpdateOAuthConnection(ctx context.Context, c *OAuthConnection) error

UpdateOAuthConnection encrypts tokens then delegates to the inner store. The caller's *OAuthConnection is left untouched.

type MemoryStore added in v1.9.0

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

MemoryStore is an in-memory Store for testing.

func NewMemoryStore added in v1.9.0

func NewMemoryStore() *MemoryStore

NewMemoryStore creates a new in-memory OAuth connection store.

func (*MemoryStore) CreateOAuthConnection added in v1.9.0

func (s *MemoryStore) CreateOAuthConnection(_ context.Context, c *OAuthConnection) error

CreateOAuthConnection stores a new OAuth connection.

func (*MemoryStore) DeleteOAuthConnection added in v1.9.0

func (s *MemoryStore) DeleteOAuthConnection(_ context.Context, connID id.OAuthConnectionID) error

DeleteOAuthConnection removes a connection by ID.

func (*MemoryStore) GetOAuthConnection added in v1.9.0

func (s *MemoryStore) GetOAuthConnection(_ context.Context, appID id.AppID, provider, providerUserID string) (*OAuthConnection, error)

GetOAuthConnection finds a connection by provider and provider user ID.

func (*MemoryStore) GetOAuthConnectionsByUserID added in v1.9.0

func (s *MemoryStore) GetOAuthConnectionsByUserID(_ context.Context, userID id.UserID) ([]*OAuthConnection, error)

GetOAuthConnectionsByUserID returns all connections for a user.

func (*MemoryStore) UpdateOAuthConnection added in v1.9.0

func (s *MemoryStore) UpdateOAuthConnection(_ context.Context, c *OAuthConnection) error

UpdateOAuthConnection replaces an existing connection by ID.

type MongoStore added in v1.9.0

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

MongoStore implements social.Store using the Grove MongoDB driver.

func NewMongoStore added in v1.9.0

func NewMongoStore(db *grove.DB) *MongoStore

NewMongoStore creates a new MongoDB-backed social/OAuth store.

func (*MongoStore) CreateOAuthConnection added in v1.9.0

func (s *MongoStore) CreateOAuthConnection(ctx context.Context, c *OAuthConnection) error

func (*MongoStore) DeleteOAuthConnection added in v1.9.0

func (s *MongoStore) DeleteOAuthConnection(ctx context.Context, connID id.OAuthConnectionID) error

func (*MongoStore) GetOAuthConnection added in v1.9.0

func (s *MongoStore) GetOAuthConnection(ctx context.Context, appID id.AppID, provider, providerUserID string) (*OAuthConnection, error)

func (*MongoStore) GetOAuthConnectionsByUserID added in v1.9.0

func (s *MongoStore) GetOAuthConnectionsByUserID(ctx context.Context, userID id.UserID) ([]*OAuthConnection, error)

func (*MongoStore) UpdateOAuthConnection added in v1.9.0

func (s *MongoStore) UpdateOAuthConnection(ctx context.Context, c *OAuthConnection) error

type OAuthConnection added in v1.9.0

type OAuthConnection struct {
	ID             id.OAuthConnectionID `json:"id"`
	AppID          id.AppID             `json:"app_id"`
	UserID         id.UserID            `json:"user_id"`
	Provider       string               `json:"provider"`
	ProviderUserID string               `json:"provider_user_id"`
	Email          string               `json:"email"`
	AccessToken    string               `json:"-"`
	RefreshToken   string               `json:"-"`
	ExpiresAt      time.Time            `json:"expires_at,omitempty"`
	Metadata       map[string]string    `json:"metadata,omitempty"`
	CreatedAt      time.Time            `json:"created_at"`
	UpdatedAt      time.Time            `json:"updated_at"`
}

OAuthConnection links an external provider account to an AuthSome user.

type Plugin

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

Plugin is the social OAuth authentication plugin.

func New added in v1.9.0

func New(cfg ...Config) *Plugin

New creates a new social OAuth plugin.

func (p *Plugin) CanUnlink(ctx context.Context, _ id.UserID, provider string) bool

CanUnlink implements plugin.AuthMethodUnlinker. It returns true if the given provider is one managed by this plugin.

func (*Plugin) DeclareSettings added in v1.9.0

func (p *Plugin) DeclareSettings(m *settings.Manager) error

DeclareSettings implements plugin.SettingsProvider.

func (*Plugin) ListUserAuthMethods added in v1.9.0

func (p *Plugin) ListUserAuthMethods(ctx context.Context, userID id.UserID) ([]*plugin.AuthMethod, error)

ListUserAuthMethods implements plugin.AuthMethodContributor. It returns one entry per OAuth connection linked to the user.

func (*Plugin) MigrationGroups added in v1.9.0

func (p *Plugin) MigrationGroups(driverName string) []*migrate.Group

MigrationGroups implements plugin.MigrationProvider.

func (*Plugin) Name added in v1.9.0

func (p *Plugin) Name() string

Name returns the plugin name.

func (*Plugin) OnBeforeUserDelete added in v1.9.0

func (p *Plugin) OnBeforeUserDelete(ctx context.Context, userID id.UserID) error

OnBeforeUserDelete removes a deleted user's provider connections and the provider tokens they carry.

func (*Plugin) OnInit added in v1.9.0

func (p *Plugin) OnInit(_ context.Context, engine plugin.Engine) error

OnInit captures the store reference and bridges from the engine.

func (*Plugin) Providers added in v1.9.0

func (p *Plugin) Providers() []string

Providers returns the list of all active provider names (code + DB).

func (*Plugin) RegisterContract added in v1.9.0

func (p *Plugin) RegisterContract(
	d *dispatcher.Dispatcher,
	reg contract.Registry,
	wreg contract.WardenRegistry,
	engine plugin.Engine,
) error

func (*Plugin) RegisterRoutes

func (p *Plugin) RegisterRoutes(router forge.Router) error

RegisterRoutes registers social OAuth HTTP endpoints on a forge.Router.

Both endpoints get the same per-IP rate limit as the JSON sign-in endpoint (default 5/window). Without this, an attacker can amplify requests against the upstream OAuth provider — the start endpoint generates state cookies and ceremony entries, the callback exchanges tokens and hits the provider's siteverify-equivalent endpoint.

func (*Plugin) SetAppID added in v1.9.0

func (p *Plugin) SetAppID(appID string)

SetAppID sets the default app ID.

func (*Plugin) SetOAuthStore added in v1.9.0

func (p *Plugin) SetOAuthStore(s Store)

SetOAuthStore sets the OAuth connection store.

func (*Plugin) SetStore added in v1.9.0

func (p *Plugin) SetStore(s store.Store)

SetStore sets the core store for testing.

func (*Plugin) UnlinkAuthMethod added in v1.9.0

func (p *Plugin) UnlinkAuthMethod(ctx context.Context, userID id.UserID, provider string) error

UnlinkAuthMethod implements plugin.AuthMethodUnlinker. It removes the OAuth connection for the given provider from the user's account.

type PostgresStore added in v1.9.0

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

PostgresStore implements social.Store using the Grove ORM with PostgreSQL.

func NewPostgresStore added in v1.9.0

func NewPostgresStore(db *grove.DB) *PostgresStore

NewPostgresStore creates a new PostgreSQL-backed social/OAuth store.

func (*PostgresStore) CreateOAuthConnection added in v1.9.0

func (s *PostgresStore) CreateOAuthConnection(ctx context.Context, c *OAuthConnection) error

func (*PostgresStore) DeleteOAuthConnection added in v1.9.0

func (s *PostgresStore) DeleteOAuthConnection(ctx context.Context, connID id.OAuthConnectionID) error

func (*PostgresStore) GetOAuthConnection added in v1.9.0

func (s *PostgresStore) GetOAuthConnection(ctx context.Context, appID id.AppID, provider, providerUserID string) (*OAuthConnection, error)

func (*PostgresStore) GetOAuthConnectionsByUserID added in v1.9.0

func (s *PostgresStore) GetOAuthConnectionsByUserID(ctx context.Context, userID id.UserID) ([]*OAuthConnection, error)

func (*PostgresStore) UpdateOAuthConnection added in v1.9.0

func (s *PostgresStore) UpdateOAuthConnection(ctx context.Context, c *OAuthConnection) error

type Provider added in v1.9.0

type Provider interface {
	// Name returns the provider's unique identifier (e.g., "google", "github").
	Name() string

	// OAuth2Config returns the OAuth2 configuration for this provider.
	OAuth2Config() *oauth2.Config

	// FetchUser uses an OAuth2 token to retrieve the user's profile
	// from the provider's API.
	FetchUser(ctx context.Context, token *oauth2.Token) (*ProviderUser, error)
}

Provider represents an OAuth2 social authentication provider.

func NewAmazonProvider added in v1.9.0

func NewAmazonProvider(cfg ProviderConfig) Provider

NewAmazonProvider creates a new Amazon OAuth2 provider.

func NewAppleProvider added in v1.9.0

func NewAppleProvider(cfg ProviderConfig) Provider

NewAppleProvider creates an Apple Sign In OAuth2 provider. Apple returns user info in the ID token (JWT) rather than via a separate userinfo endpoint. The provider decodes the ID token claims directly.

func NewBitbucketProvider added in v1.9.0

func NewBitbucketProvider(cfg ProviderConfig) Provider

NewBitbucketProvider creates a new Bitbucket OAuth2 provider.

func NewDiscordProvider added in v1.9.0

func NewDiscordProvider(cfg ProviderConfig) Provider

NewDiscordProvider creates a new Discord OAuth2 provider.

func NewDropboxProvider added in v1.9.0

func NewDropboxProvider(cfg ProviderConfig) Provider

NewDropboxProvider creates a new Dropbox OAuth2 provider.

func NewFacebookProvider added in v1.9.0

func NewFacebookProvider(cfg ProviderConfig) Provider

NewFacebookProvider creates a new Facebook OAuth2 provider.

func NewGitHubProvider added in v1.9.0

func NewGitHubProvider(cfg ProviderConfig) Provider

NewGitHubProvider creates a new GitHub OAuth2 provider.

func NewGitLabProvider added in v1.9.0

func NewGitLabProvider(cfg ProviderConfig) Provider

NewGitLabProvider creates a new GitLab OAuth2 provider.

func NewGoogleProvider added in v1.9.0

func NewGoogleProvider(cfg ProviderConfig) Provider

NewGoogleProvider creates a new Google OAuth2 provider.

func NewInstagramProvider added in v1.9.0

func NewInstagramProvider(cfg ProviderConfig) Provider

NewInstagramProvider creates a new Instagram OAuth2 provider.

func NewLineProvider added in v1.9.0

func NewLineProvider(cfg ProviderConfig) Provider

NewLineProvider creates a new LINE OAuth2 provider.

func NewLinkedInProvider added in v1.9.0

func NewLinkedInProvider(cfg ProviderConfig) Provider

NewLinkedInProvider creates a new LinkedIn OAuth2 provider.

func NewMicrosoftProvider added in v1.9.0

func NewMicrosoftProvider(cfg ProviderConfig) Provider

NewMicrosoftProvider creates a Microsoft OAuth2 provider. Uses the Microsoft identity platform (v2.0) with the "common" tenant (supports both personal and work/school accounts).

func NewPatreonProvider added in v1.9.0

func NewPatreonProvider(cfg ProviderConfig) Provider

NewPatreonProvider creates a new Patreon OAuth2 provider.

func NewPinterestProvider added in v1.9.0

func NewPinterestProvider(cfg ProviderConfig) Provider

NewPinterestProvider creates a new Pinterest OAuth2 provider.

func NewSlackProvider added in v1.9.0

func NewSlackProvider(cfg ProviderConfig) Provider

NewSlackProvider creates a new Slack OAuth2 provider.

func NewSpotifyProvider added in v1.9.0

func NewSpotifyProvider(cfg ProviderConfig) Provider

NewSpotifyProvider creates a new Spotify OAuth2 provider.

func NewStravaProvider added in v1.9.0

func NewStravaProvider(cfg ProviderConfig) Provider

NewStravaProvider creates a new Strava OAuth2 provider.

func NewTwitchProvider added in v1.9.0

func NewTwitchProvider(cfg ProviderConfig) Provider

NewTwitchProvider creates a new Twitch OAuth2 provider.

func NewTwitterProvider added in v1.9.0

func NewTwitterProvider(cfg ProviderConfig) Provider

NewTwitterProvider creates a new Twitter/X OAuth2 provider.

func NewYahooProvider added in v1.9.0

func NewYahooProvider(cfg ProviderConfig) Provider

NewYahooProvider creates a new Yahoo OAuth2 provider.

func NewZoomProvider added in v1.9.0

func NewZoomProvider(cfg ProviderConfig) Provider

NewZoomProvider creates a new Zoom OAuth2 provider.

type ProviderConfig added in v1.9.0

type ProviderConfig struct {
	ClientID     string
	ClientSecret string
	RedirectURL  string
	Scopes       []string
}

ProviderConfig holds common OAuth2 configuration for a provider.

type ProviderEmail added in v1.9.0

type ProviderEmail struct {
	Email    string `json:"email"`
	Verified bool   `json:"verified"`
	Primary  bool   `json:"primary"`
}

ProviderEmail is a single email address reported by a social provider, along with whether the provider considers it verified and primary.

type ProviderSetting added in v1.9.0

type ProviderSetting struct {
	Name         string   `json:"name"`
	ClientID     string   `json:"client_id"`
	ClientSecret string   `json:"client_secret"`
	RedirectURL  string   `json:"redirect_url"`
	Scopes       []string `json:"scopes,omitempty"`
	Enabled      bool     `json:"enabled"`
}

ProviderSetting represents a social provider configured via the dashboard.

type ProviderUser added in v1.9.0

type ProviderUser struct {
	ProviderUserID string `json:"provider_user_id"`
	// Email is the provider's primary email (kept for backward compatibility).
	Email string `json:"email"`
	// EmailVerified reports whether the provider considers Email verified.
	// Defaults to false when the provider doesn't expose verification — the
	// matching algorithm treats unknown verification as unverified so an
	// unverified address can never silently link to or hijack an account.
	EmailVerified bool `json:"email_verified"`
	// Emails is the full set of addresses the provider exposes (may be empty,
	// in which case Email/EmailVerified is used as a single entry).
	Emails    []ProviderEmail `json:"emails,omitempty"`
	FirstName string          `json:"first_name"`
	LastName  string          `json:"last_name"`
	AvatarURL string          `json:"avatar_url,omitempty"`
}

ProviderUser is the normalized user profile returned by a social provider.

func (*ProviderUser) AllEmails added in v1.9.0

func (p *ProviderUser) AllEmails() []ProviderEmail

AllEmails returns every address the provider exposes (verified or not), lowercased and de-duplicated, falling back to the primary Email. Used when seeding a brand-new user so their known addresses are recorded.

func (*ProviderUser) VerifiedEmails added in v1.9.0

func (p *ProviderUser) VerifiedEmails() []ProviderEmail

VerifiedEmails returns the provider's verified addresses (lowercased, de-duplicated), falling back to the primary Email when the provider didn't populate Emails. Only verified addresses are returned, so callers can match against existing accounts without risking takeover via an unverified email.

type SqliteStore added in v1.9.0

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

SqliteStore implements social.Store using the Grove ORM with SQLite.

func NewSqliteStore added in v1.9.0

func NewSqliteStore(db *grove.DB) *SqliteStore

NewSqliteStore creates a new SQLite-backed social/OAuth store.

func (*SqliteStore) CreateOAuthConnection added in v1.9.0

func (s *SqliteStore) CreateOAuthConnection(ctx context.Context, c *OAuthConnection) error

func (*SqliteStore) DeleteOAuthConnection added in v1.9.0

func (s *SqliteStore) DeleteOAuthConnection(ctx context.Context, connID id.OAuthConnectionID) error

func (*SqliteStore) GetOAuthConnection added in v1.9.0

func (s *SqliteStore) GetOAuthConnection(ctx context.Context, appID id.AppID, provider, providerUserID string) (*OAuthConnection, error)

func (*SqliteStore) GetOAuthConnectionsByUserID added in v1.9.0

func (s *SqliteStore) GetOAuthConnectionsByUserID(ctx context.Context, userID id.UserID) ([]*OAuthConnection, error)

func (*SqliteStore) UpdateOAuthConnection added in v1.9.0

func (s *SqliteStore) UpdateOAuthConnection(ctx context.Context, c *OAuthConnection) error

type StartRequest added in v1.9.0

type StartRequest struct {
	Provider    string `path:"provider"`
	FrontendURL string `json:"frontend_url,omitempty" query:"frontend_url,omitempty"`
	RedirectURL string `json:"redirect_url,omitempty" query:"redirect_url,omitempty"`
}

StartRequest contains the path parameter for starting OAuth.

FrontendURL is the originating SPA's root (e.g. "https://app.example.com") for split-origin deployments where the auth service runs on a different host than the frontend. It serves two purposes:

  1. Trusted origin for validating RedirectURL when the request's Origin/Referer headers can't be relied on (CORS, server-to-server, popup contexts).
  2. Fallback redirect target when RedirectURL is empty or the auth flow fails before a redirect target can be resolved.

RedirectURL is the post-auth destination — where to send the browser after a successful login/signup. If empty, callers will fall back to FrontendURL.

type StartResponse added in v1.9.0

type StartResponse struct {
	AuthURL string `json:"auth_url"`
}

StartResponse is returned when the OAuth flow is initiated.

type Store added in v1.9.0

type Store interface {
	CreateOAuthConnection(ctx context.Context, c *OAuthConnection) error
	// GetOAuthConnection resolves a provider identity inside one app. The
	// same provider user in two apps is two connections; without the app in
	// the key, a login in one app would land on the other's account.
	GetOAuthConnection(ctx context.Context, appID id.AppID, provider, providerUserID string) (*OAuthConnection, error)
	GetOAuthConnectionsByUserID(ctx context.Context, userID id.UserID) ([]*OAuthConnection, error)
	// UpdateOAuthConnection persists changes to an existing connection
	// (refreshed access/refresh tokens, expiry, email).
	UpdateOAuthConnection(ctx context.Context, c *OAuthConnection) error
	DeleteOAuthConnection(ctx context.Context, connID id.OAuthConnectionID) error
}

Store persists OAuth connections.

Directories

Path Synopsis
Package contract wires the social plugin's deep-link settings page into the forge-dashboard contract registry.
Package contract wires the social plugin's deep-link settings page into the forge-dashboard contract registry.
Package socialtest provides a backend-agnostic conformance suite for the social.Store interface.
Package socialtest provides a backend-agnostic conformance suite for the social.Store interface.

Jump to

Keyboard shortcuts

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