auth

package
v1.1.2 Latest Latest
Warning

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

Go to latest
Published: Aug 11, 2026 License: MIT Imports: 28 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddDevice

func AddDevice(ctx context.Context, pool *pgxpool.Pool, userID uuid.UUID, deviceID string, preferences string, pushTokens map[string]string) error

AddDevice registers a device ID associated with a user.

func ChangePassword

func ChangePassword(ctx context.Context, pool *pgxpool.Pool, userID uuid.UUID, oldPassword, newPassword string) error

ChangePassword updates password and is intended to be paired with JWT revocation by the caller.

func CountIdentities

func CountIdentities(ctx context.Context, pool *pgxpool.Pool, userID uuid.UUID) (int, error)

CountIdentities returns how many login methods the user currently has.

func IsCommonPassword

func IsCommonPassword(password string) bool

IsCommonPassword returns true if password is on the deny list (case-insensitive).

func LinkEmail

func LinkEmail(ctx context.Context, pool *pgxpool.Pool, userID uuid.UUID, email, password string) error

LinkEmail sets email+password on an existing account.

func LinkProvider

func LinkProvider(ctx context.Context, pool *pgxpool.Pool, userID uuid.UUID, provider string, providerID string) error

LinkProvider links a social provider ID to an existing user profile.

func Logout

func Logout(ctx context.Context, store SessionStore, tm *TokenManager, accessToken, refreshToken string) error

Logout clears refresh token and optionally blacklists access JWT by jti.

func LogoutAll

func LogoutAll(ctx context.Context, store SessionStore, tm *TokenManager, userID, accessToken string) error

LogoutAll revokes every refresh for the user and blacklists the current access jti.

func RedisRefreshKey

func RedisRefreshKey(token string) string

Format helper kept for redis key introspection in tests.

func SetSocialConfig

func SetSocialConfig(cfg SocialConfig)

SetSocialConfig overrides the package-level social verification config (tests/bootstrap).

func SoftDeleteUser

func SoftDeleteUser(ctx context.Context, pool *pgxpool.Pool, userID uuid.UUID) error

SoftDeleteUser soft deletes a user account by disabling the profile and writing a tombstone.

func UnlinkDevice

func UnlinkDevice(ctx context.Context, pool *pgxpool.Pool, userID uuid.UUID, deviceID string) error

UnlinkDevice removes a device identity with last-identity guard.

func UnlinkProvider

func UnlinkProvider(ctx context.Context, pool *pgxpool.Pool, userID uuid.UUID, provider string) error

UnlinkProvider clears a provider column after enforcing last-identity guard.

func UpdateAccount

func UpdateAccount(ctx context.Context, pool *pgxpool.Pool, userID uuid.UUID, upd AccountUpdate) error

UpdateAccount updates profile fields for a user.

func UpdateAccountsTx

func UpdateAccountsTx(ctx context.Context, tx pgx.Tx, updates []AccountUpdateParams) error

UpdateAccountsTx applies account profile updates inside a transaction.

func ValidateEmailAddress

func ValidateEmailAddress(email string) bool

ValidateEmailAddress checks RFC 5322-ish email via net/mail.

func ValidatePasswordPolicy

func ValidatePasswordPolicy(password string) error

ValidatePasswordPolicy enforces length, complexity, and common-password checks.

func VerifyAppleToken

func VerifyAppleToken(ctx context.Context, token string) (string, error)

VerifyAppleToken verifies an Apple Identity Token (JWT) against Apple JWKS. Tokens prefixed with "mock_" bypass network verification for hermetic tests.

func VerifyFacebookInstantGame

func VerifyFacebookInstantGame(ctx context.Context, signedPlayerInfo string) (string, error)

VerifyFacebookInstantGame verifies a signed player info token. Tokens prefixed with mock_ are accepted for hermetic tests.

func VerifyFacebookToken

func VerifyFacebookToken(ctx context.Context, token string) (string, error)

VerifyFacebookToken verifies a Facebook access token via Graph API debug_token / me.

func VerifyGameCenterSignature

func VerifyGameCenterSignature(ctx context.Context, cred GameCenterCredentials) (string, error)

VerifyGameCenterSignature verifies Game Center player identity. Mock mode: PublicKeyURL "mock" returns PlayerID without crypto verification.

func VerifyGoogleToken

func VerifyGoogleToken(ctx context.Context, token string) (string, error)

VerifyGoogleToken verifies a Google ID token via Google's tokeninfo endpoint (or mock_ bypass). Optionally checks aud against GOOGLE_CLIENT_IDS.

func VerifySteamTicket

func VerifySteamTicket(ctx context.Context, ticket string) (string, error)

VerifySteamTicket authenticates a Steam session ticket via Steam Web API. Tokens prefixed with mock_ are accepted as steam IDs for tests.

Types

type AccountUpdate

type AccountUpdate struct {
	Username    *string
	DisplayName *string
	AvatarURL   *string
	LangTag     *string
	Location    *string
	Timezone    *string
	Metadata    *string
}

AccountUpdate holds mutable account profile fields.

type AccountUpdateParams

type AccountUpdateParams struct {
	UserID      string
	Username    *string
	DisplayName *string
	AvatarURL   *string
	LangTag     *string
	Location    *string
	Timezone    *string
	Metadata    *string
}

AccountUpdateParams is a single account mutation for MultiUpdate.

type AuthOptions

type AuthOptions struct {
	Create   bool
	Username string
	Vars     map[string]string
}

AuthOptions controls create-or-login semantics shared by authenticate endpoints.

type Claims

type Claims struct {
	UserID   string            `json:"sub"`
	Username string            `json:"usn"`
	Vars     map[string]string `json:"vrs,omitempty"`
	jwt.RegisteredClaims
}

Claims defines the custom JWT claims structure.

type GameCenterCredentials

type GameCenterCredentials struct {
	PlayerID     string
	BundleID     string
	Timestamp    int64
	Salt         string
	Signature    string
	PublicKeyURL string
}

GameCenterCredentials holds Apple Game Center identity verification fields.

type LoginLockout

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

LoginLockout tracks failed authentication attempts per account and IP.

func NewLoginLockout

func NewLoginLockout() *LoginLockout

NewLoginLockout creates an in-memory lockout tracker.

func (*LoginLockout) Check

func (l *LoginLockout) Check(identityKey, ip string) error

Check returns an error if the identity or IP is currently locked out.

func (*LoginLockout) ClearSuccess

func (l *LoginLockout) ClearSuccess(identityKey, ip string)

ClearSuccess resets counters after a successful authentication.

func (*LoginLockout) RecordFailure

func (l *LoginLockout) RecordFailure(identityKey, ip string)

RecordFailure increments fail counters; locks when thresholds are exceeded.

type MemorySessionStore

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

MemorySessionStore is the in-process implementation (tests / no Redis).

func NewMemorySessionStore

func NewMemorySessionStore() *MemorySessionStore

func (*MemorySessionStore) BlacklistAccessJTI

func (m *MemorySessionStore) BlacklistAccessJTI(ctx context.Context, jti string, until time.Time) error

func (*MemorySessionStore) IsAccessJTIBlacklisted

func (m *MemorySessionStore) IsAccessJTIBlacklisted(ctx context.Context, jti string) (bool, error)

func (*MemorySessionStore) IsUserRevoked

func (m *MemorySessionStore) IsUserRevoked(ctx context.Context, userID string) (bool, error)

func (*MemorySessionStore) RegisterSession

func (m *MemorySessionStore) RegisterSession(ctx context.Context, userID, token, parentToken string) error

func (*MemorySessionStore) RevokeAllSessions

func (m *MemorySessionStore) RevokeAllSessions(ctx context.Context, userID string) error

func (*MemorySessionStore) RevokeRefreshToken

func (m *MemorySessionStore) RevokeRefreshToken(ctx context.Context, token string) error

func (*MemorySessionStore) ValidateAndRotateSession

func (m *MemorySessionStore) ValidateAndRotateSession(ctx context.Context, token string) (string, bool, error)

type RedisSessionStore

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

RedisSessionStore persists refresh tokens and JWT deny list in Redis.

func NewRedisSessionStore

func NewRedisSessionStore(rdb *redis.Client, ttl time.Duration) *RedisSessionStore

NewRedisSessionStore creates a Redis-backed store. Falls back operations return error if rdb nil.

func (*RedisSessionStore) BlacklistAccessJTI

func (r *RedisSessionStore) BlacklistAccessJTI(ctx context.Context, jti string, until time.Time) error

func (*RedisSessionStore) IsAccessJTIBlacklisted

func (r *RedisSessionStore) IsAccessJTIBlacklisted(ctx context.Context, jti string) (bool, error)

func (*RedisSessionStore) IsUserRevoked

func (r *RedisSessionStore) IsUserRevoked(ctx context.Context, userID string) (bool, error)

func (*RedisSessionStore) RegisterSession

func (r *RedisSessionStore) RegisterSession(ctx context.Context, userID, token, parentToken string) error

func (*RedisSessionStore) RevokeAllSessions

func (r *RedisSessionStore) RevokeAllSessions(ctx context.Context, userID string) error

func (*RedisSessionStore) RevokeRefreshToken

func (r *RedisSessionStore) RevokeRefreshToken(ctx context.Context, token string) error

func (*RedisSessionStore) ValidateAndRotateSession

func (r *RedisSessionStore) ValidateAndRotateSession(ctx context.Context, token string) (string, bool, error)

type SessionRegistry

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

SessionRegistry wraps SessionStore with the historical sync API used by handlers/tests.

func NewSessionRegistry

func NewSessionRegistry() *SessionRegistry

NewSessionRegistry returns a memory-backed store compatible with historical API.

func NewSessionRegistryWithStore

func NewSessionRegistryWithStore(store SessionStore) *SessionRegistry

NewSessionRegistryWithStore builds a registry over an arbitrary store.

func (*SessionRegistry) RegisterSession

func (sr *SessionRegistry) RegisterSession(userID, token string, parentToken string)

func (*SessionRegistry) RevokeAllSessions

func (sr *SessionRegistry) RevokeAllSessions(userID string)

func (*SessionRegistry) Store

func (sr *SessionRegistry) Store() SessionStore

func (*SessionRegistry) ValidateAndRotateSession

func (sr *SessionRegistry) ValidateAndRotateSession(token string) (string, bool, error)

type SessionStore

type SessionStore interface {
	RegisterSession(ctx context.Context, userID, token, parentToken string) error
	ValidateAndRotateSession(ctx context.Context, token string) (userID string, theftDetected bool, err error)
	RevokeAllSessions(ctx context.Context, userID string) error
	RevokeRefreshToken(ctx context.Context, token string) error
	BlacklistAccessJTI(ctx context.Context, jti string, until time.Time) error
	IsAccessJTIBlacklisted(ctx context.Context, jti string) (bool, error)
	IsUserRevoked(ctx context.Context, userID string) (bool, error)
}

SessionStore abstracts refresh-token + JWT denial storage.

func NewSessionStoreFromRedis

func NewSessionStoreFromRedis(rdb *redis.Client) SessionStore

NewSessionStoreFromRedis picks Redis when available, else memory.

type SocialConfig

type SocialConfig struct {
	AppleClientIDs    []string // allowed aud / bundle IDs
	GoogleClientIDs   []string
	FacebookAppID     string
	FacebookAppSecret string
	SteamAppID        string
	SteamPublisherKey string
	HTTPClient        *http.Client
}

SocialConfig holds provider verification settings (env-overridable).

func DefaultSocialConfig

func DefaultSocialConfig() SocialConfig

DefaultSocialConfig loads from environment variables.

type TokenManager

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

TokenManager handles JWT signing, verification, and key management.

func NewTokenManager

func NewTokenManager(secretKey []byte, expiry time.Duration) (*TokenManager, error)

NewTokenManager creates a new instance of TokenManager.

func (*TokenManager) Expiry

func (tm *TokenManager) Expiry() time.Duration

Expiry returns the configured access-token lifetime.

func (*TokenManager) GenerateAccessToken

func (tm *TokenManager) GenerateAccessToken(userID, username string, expiresAt int64, vars map[string]string) (string, int64, error)

GenerateAccessToken mints an access JWT with optional custom expiry (unix seconds). If expiresAt is 0, the configured TokenManager expiry is used.

func (*TokenManager) GenerateSession

func (tm *TokenManager) GenerateSession(userID string, username string) (string, string, error)

GenerateSession generates a JWT access token (with jti) and opaque refresh token.

func (*TokenManager) GenerateSessionWithVars

func (tm *TokenManager) GenerateSessionWithVars(userID, username string, vars map[string]string) (string, string, error)

GenerateSessionWithVars embeds optional session vars into the access JWT.

func (*TokenManager) VerifyToken

func (tm *TokenManager) VerifyToken(tokenStr string) (*Claims, error)

VerifyToken parses and validates a JWT access token.

func (*TokenManager) VerifyTokenIgnoreExpiry

func (tm *TokenManager) VerifyTokenIgnoreExpiry(tokenStr string) (*Claims, error)

VerifyTokenIgnoreExpiry validates signature/claims but ignores expiry (logout/blacklist).

type User

type User struct {
	ID           uuid.UUID
	Username     string
	DisplayName  string
	AvatarURL    string
	LangTag      string
	Location     string
	Timezone     string
	Metadata     string
	Email        *string
	CustomID     *string
	AppleID      *string
	GoogleID     *string
	FacebookID   *string
	GamecenterID *string
	SteamID      *string
	FacebookIGID *string
	DisableTime  time.Time
	CreateTime   time.Time
	UpdateTime   time.Time
	Devices      []string
}

User represents a user profile retrieved from database.

func AuthenticateCustom

func AuthenticateCustom(ctx context.Context, pool *pgxpool.Pool, customID string) (*User, error)

AuthenticateCustom authenticates a custom ID, creating a user if they do not exist.

func AuthenticateCustomWithOpts

func AuthenticateCustomWithOpts(ctx context.Context, pool *pgxpool.Pool, customID string, opts AuthOptions) (*User, bool, error)

AuthenticateCustomWithOpts supports create=false and optional username.

func AuthenticateDevice

func AuthenticateDevice(ctx context.Context, pool *pgxpool.Pool, deviceID string, opts AuthOptions) (*User, bool, error)

AuthenticateDevice finds or creates a user via user_device.

func AuthenticateEmail

func AuthenticateEmail(ctx context.Context, pool *pgxpool.Pool, email, password string) (*User, error)

AuthenticateEmail verifies a user email and password.

func AuthenticateSocial

func AuthenticateSocial(ctx context.Context, pool *pgxpool.Pool, provider string, providerID string) (*User, error)

AuthenticateSocial authenticates a social provider ID, creating a user if they do not exist.

func AuthenticateSocialWithOpts

func AuthenticateSocialWithOpts(ctx context.Context, pool *pgxpool.Pool, provider, providerID string, opts AuthOptions) (*User, bool, error)

AuthenticateSocialWithOpts supports create=false and optional username.

func GetAccount

func GetAccount(ctx context.Context, pool *pgxpool.Pool, userID uuid.UUID) (*User, error)

GetAccount loads the full account profile including linked devices.

func GetUsersPublic

func GetUsersPublic(ctx context.Context, pool *pgxpool.Pool, ids, usernames, facebookIDs []string) ([]*User, error)

GetUsersPublic returns public profile fields for users matching ids, usernames, or facebook IDs. Disabled accounts are omitted. Metadata is returned as stored JSON text.

func RegisterEmail

func RegisterEmail(ctx context.Context, pool *pgxpool.Pool, username, email, password, displayName string) (*User, error)

RegisterEmail creates a new user account with an email and password.

Jump to

Keyboard shortcuts

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