user

package
v1.46.39 Latest Latest
Warning

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

Go to latest
Published: Jul 6, 2026 License: MIT Imports: 13 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package user provides the User model using the new db.DB interface. This modernized implementation supports: - Per-user SQLite databases (data/users/{userID}/data.db) - OAuth2 tokens from hanzo.id (IAM) - Profile and settings management - Wallet integration via Lux blockchain

Index

Constants

View Source
const Kind = "user"

Entity kind for User

Variables

View Source
var (
	ErrOAuthInvalidGrant  = errors.New("oauth: invalid grant")
	ErrOAuthTokenExpired  = errors.New("oauth: token expired")
	ErrOAuthInvalidState  = errors.New("oauth: invalid state")
	ErrOAuthProviderError = errors.New("oauth: provider error")
	ErrOAuthNotConfigured = errors.New("oauth: provider not configured")
)

OAuth2 errors

View Source
var (
	ErrProfileNotFound     = errors.New("profile: not found")
	ErrProfileInvalidField = errors.New("profile: invalid field")
	ErrAvatarTooLarge      = errors.New("profile: avatar too large")
)

Profile errors

View Source
var (
	ErrUserNotFound    = errors.New("user: not found")
	ErrInvalidEmail    = errors.New("user: invalid email")
	ErrInvalidPassword = errors.New("user: invalid password")
	ErrEmailExists     = errors.New("user: email already exists")
	ErrUsernameExists  = errors.New("user: username already exists")
	ErrUnauthorized    = errors.New("user: unauthorized")
	ErrAccountDisabled = errors.New("user: account disabled")
	ErrKYCRequired     = errors.New("user: KYC verification required")
)

Common errors

View Source
var (
	ErrWalletNotFound      = errors.New("wallet: not found")
	ErrWalletAlreadyExists = errors.New("wallet: already exists")
	ErrInsufficientBalance = errors.New("wallet: insufficient balance")
	ErrInvalidAmount       = errors.New("wallet: invalid amount")
	ErrWalletLocked        = errors.New("wallet: locked")
	ErrAddressNotFound     = errors.New("wallet: address not found")
)

Wallet errors

View Source
var (
	ErrSettingsNotFound = errors.New("settings: not found")
)

Settings errors

Functions

func GenerateState

func GenerateState() (string, error)

GenerateState generates a secure random state parameter

func Query

func Query(database db.DB) db.Query

Query is a helper to create queries against the user kind

Types

type APIKey

type APIKey struct {
	ID          string    `json:"id"`
	Name        string    `json:"name"`
	KeyPrefix   string    `json:"keyPrefix"` // First 8 chars for identification
	KeyHash     []byte    `json:"-"`
	Permissions []string  `json:"permissions,omitempty"`
	CreatedAt   time.Time `json:"createdAt"`
	ExpiresAt   time.Time `json:"expiresAt,omitempty"`
	LastUsedAt  time.Time `json:"lastUsedAt,omitempty"`
}

APIKey represents a user API key

type Account

type Account struct {
	Type     AccountType `json:"type"`
	Balances []Balance   `json:"balances"`
	Holds    []Hold      `json:"holds,omitempty"`
}

Account represents a balance account within a wallet

type AccountType

type AccountType string

AccountType represents the type of wallet account

const (
	AccountTypeMain    AccountType = "main"
	AccountTypeRewards AccountType = "rewards"
	AccountTypeEscrow  AccountType = "escrow"
	AccountTypeStaking AccountType = "staking"
)

type Address

type Address struct {
	Line1      string `json:"line1,omitempty"`
	Line2      string `json:"line2,omitempty"`
	City       string `json:"city,omitempty"`
	State      string `json:"state,omitempty"`
	PostalCode string `json:"postalCode,omitempty"`
	Country    string `json:"country,omitempty"`
}

Address represents a physical address

type Badge

type Badge struct {
	ID          string    `json:"id"`
	Name        string    `json:"name"`
	Description string    `json:"description,omitempty"`
	IconURL     string    `json:"iconUrl,omitempty"`
	AwardedAt   time.Time `json:"awardedAt"`
	ExpiresAt   time.Time `json:"expiresAt,omitempty"`
}

Badge represents an achievement or verification badge

type Balance

type Balance struct {
	Currency  Currency  `json:"currency"`
	Amount    int64     `json:"amount"` // In smallest unit (cents, satoshis, wei, etc.)
	Available int64     `json:"available"`
	Pending   int64     `json:"pending"`
	UpdatedAt time.Time `json:"updatedAt"`
}

Balance represents a currency balance

type Buyer

type Buyer struct {
	Email           string  `json:"email"`
	UserID          string  `json:"userId"`
	FirstName       string  `json:"firstName"`
	LastName        string  `json:"lastName"`
	Company         string  `json:"company,omitempty"`
	Phone           string  `json:"phone,omitempty"`
	ShippingAddress Address `json:"shippingAddress,omitempty"`
	BillingAddress  Address `json:"billingAddress,omitempty"`
}

Buyer represents buyer information for an order

type CommerceSettings

type CommerceSettings struct {
	// Default addresses
	DefaultShippingAddressID string `json:"defaultShippingAddressId,omitempty"`
	DefaultBillingAddressID  string `json:"defaultBillingAddressId,omitempty"`

	// Payment preferences
	DefaultPaymentMethodID string `json:"defaultPaymentMethodId,omitempty"`
	SavePaymentMethods     bool   `json:"savePaymentMethods"`
	AutoApplyRewards       bool   `json:"autoApplyRewards"`

	// Currency and locale
	PreferredCurrency string `json:"preferredCurrency,omitempty"`
	PreferredLanguage string `json:"preferredLanguage,omitempty"`

	// Shopping preferences
	ShowPricesWithTax bool `json:"showPricesWithTax"`
	EnableOneClickBuy bool `json:"enableOneClickBuy"`
	SaveCartOnLogout  bool `json:"saveCartOnLogout"`

	// Subscription preferences
	AutoRenewSubscriptions bool `json:"autoRenewSubscriptions"`
}

CommerceSettings controls shopping preferences

type Currency

type Currency string

Currency represents a supported currency

const (
	CurrencyUSD  Currency = "USD"
	CurrencyEUR  Currency = "EUR"
	CurrencyGBP  Currency = "GBP"
	CurrencyLUX  Currency = "LUX" // Native Lux token
	CurrencyETH  Currency = "ETH"
	CurrencyBTC  Currency = "BTC"
	CurrencyUSDC Currency = "USDC"
)

type DeveloperSettings

type DeveloperSettings struct {
	APIEnabled    bool     `json:"apiEnabled"`
	WebhookURL    string   `json:"webhookUrl,omitempty"`
	WebhookSecret string   `json:"-"`
	APIKeys       []APIKey `json:"apiKeys,omitempty"`
	RateLimit     int      `json:"rateLimit,omitempty"` // Requests per minute
}

DeveloperSettings for API access

type DisplaySettings

type DisplaySettings struct {
	Theme         string `json:"theme,omitempty"`       // "light", "dark", "system"
	ColorScheme   string `json:"colorScheme,omitempty"` // Custom color scheme
	CompactMode   bool   `json:"compactMode"`
	HighContrast  bool   `json:"highContrast"`
	ReducedMotion bool   `json:"reducedMotion"`
	FontSize      string `json:"fontSize,omitempty"` // "small", "medium", "large"

	// Dashboard preferences
	DashboardLayout string   `json:"dashboardLayout,omitempty"`
	VisibleWidgets  []string `json:"visibleWidgets,omitempty"`
	DefaultView     string   `json:"defaultView,omitempty"` // "grid", "list"
}

DisplaySettings controls UI preferences

type Event

type Event struct {
	Type      string                 `json:"type"`
	Timestamp time.Time              `json:"timestamp"`
	Data      map[string]interface{} `json:"data,omitempty"`
	Actor     string                 `json:"actor,omitempty"`
}

Event represents a historical event for audit trail

type Facebook

type Facebook struct {
	AccessToken string `json:"-"`
	UserID      string `json:"userId,omitempty"`
	FirstName   string `json:"firstName,omitempty"`
	LastName    string `json:"lastName,omitempty"`
	MiddleName  string `json:"middleName,omitempty"`
	Name        string `json:"-"`
	NameFormat  string `json:"nameFormat,omitempty"`
	Email       string `json:"-"`
	Verified    bool   `json:"-"`
}

Facebook holds Facebook OAuth data

type HanzoIDConfig

type HanzoIDConfig struct {
	ClientID     string
	ClientSecret string
	RedirectURI  string
	AuthURL      string // Default: https://hanzo.id/v1/iam/oauth/authorize
	TokenURL     string // Default: https://hanzo.id/v1/iam/oauth/access_token
	UserInfoURL  string // Default: https://hanzo.id/v1/iam/userinfo
	Scopes       []string
}

HanzoIDConfig holds configuration for hanzo.id OAuth2

func DefaultHanzoIDConfig

func DefaultHanzoIDConfig() *HanzoIDConfig

DefaultHanzoIDConfig returns default hanzo.id configuration

type HanzoIDIndex

type HanzoIDIndex struct {
	HanzoID string `json:"hanzoId"`
	UserID  string `json:"userId"`
}

HanzoIDIndex maps hanzo.id to user ID

func (*HanzoIDIndex) Kind

func (i *HanzoIDIndex) Kind() string

Kind implements db.Entity

type HanzoIDUserInfo

type HanzoIDUserInfo struct {
	Sub           string `json:"sub"`
	Email         string `json:"email"`
	EmailVerified bool   `json:"email_verified"`
	Name          string `json:"name"`
	GivenName     string `json:"given_name"`
	FamilyName    string `json:"family_name"`
	Picture       string `json:"picture"`
	Locale        string `json:"locale"`

	// Extended hanzo.id fields
	WalletAddress string   `json:"wallet_address,omitempty"`
	Organizations []string `json:"organizations,omitempty"`
	Permissions   []string `json:"permissions,omitempty"`
}

HanzoIDUserInfo represents the user info response from hanzo.id

type Hold

type Hold struct {
	ID          string    `json:"id"`
	Currency    Currency  `json:"currency"`
	Amount      int64     `json:"amount"`
	Reason      string    `json:"reason"`
	ReferenceID string    `json:"referenceId,omitempty"`
	ExpiresAt   time.Time `json:"expiresAt,omitempty"`
	CreatedAt   time.Time `json:"createdAt"`
}

Hold represents a held/reserved amount

type KYC

type KYC struct {
	KYCData
	Status KYCStatus `json:"status,omitempty"`
	Hash   string    `json:"hash,omitempty"`
}

KYC holds the full KYC verification state

type KYCData

type KYCData struct {
	Flagged      bool      `json:"flagged,omitempty"`
	Frozen       bool      `json:"frozen,omitempty"`
	DateApproved time.Time `json:"dateApproved,omitempty"`

	WalletAddresses []string `json:"walletAddresses,omitempty"`
	Address         Address  `json:"address,omitempty"`
	Documents       []string `json:"documents,omitempty"`

	TaxID     string    `json:"taxId,omitempty"`
	Phone     string    `json:"phone,omitempty"`
	Birthdate time.Time `json:"birthdate,omitempty"`
	Gender    string    `json:"gender,omitempty"`

	// Blockchain addresses
	EthereumAddress string `json:"ethereumAddress,omitempty"`
	LuxAddress      string `json:"luxAddress,omitempty"`
	EOSPublicKey    string `json:"eosPublicKey,omitempty"`
}

KYCData holds Know Your Customer verification data

type KYCStatus

type KYCStatus string

KYCStatus represents the Know Your Customer verification status

const (
	KYCStatusInitiated KYCStatus = "initiated"
	KYCStatusPending   KYCStatus = "pending"
	KYCStatusApproved  KYCStatus = "approved"
	KYCStatusDenied    KYCStatus = "denied"
)

type ListOptions

type ListOptions struct {
	Limit      int
	Offset     int
	OrderBy    string
	Descending bool
	Filters    map[string]interface{}
}

ListOptions for paginated queries

type NotificationSettings

type NotificationSettings struct {
	// Email notifications
	EmailEnabled      bool `json:"emailEnabled"`
	OrderUpdates      bool `json:"orderUpdates"`
	ShippingUpdates   bool `json:"shippingUpdates"`
	PromotionalEmails bool `json:"promotionalEmails"`
	Newsletter        bool `json:"newsletter"`
	SecurityAlerts    bool `json:"securityAlerts"`

	// Push notifications
	PushEnabled      bool `json:"pushEnabled"`
	PushOrderUpdates bool `json:"pushOrderUpdates"`
	PushPromos       bool `json:"pushPromos"`

	// SMS notifications
	SMSEnabled        bool `json:"smsEnabled"`
	SMSOrderUpdates   bool `json:"smsOrderUpdates"`
	SMSSecurityAlerts bool `json:"smsSecurityAlerts"`

	// Digest preferences
	DigestFrequency string `json:"digestFrequency,omitempty"` // "daily", "weekly", "never"
}

NotificationSettings controls notification delivery

type OAuthProvider

type OAuthProvider string

OAuthProvider represents supported OAuth providers

const (
	OAuthProviderHanzo    OAuthProvider = "hanzo"
	OAuthProviderGoogle   OAuthProvider = "google"
	OAuthProviderGitHub   OAuthProvider = "github"
	OAuthProviderFacebook OAuthProvider = "facebook"
	OAuthProviderApple    OAuthProvider = "apple"
)

type OAuthService

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

OAuthService handles OAuth2 authentication flows

func NewOAuthService

func NewOAuthService(config *HanzoIDConfig, service *Service) *OAuthService

NewOAuthService creates a new OAuth service

func (*OAuthService) AuthenticateWithCode

func (o *OAuthService) AuthenticateWithCode(ctx context.Context, code string) (*User, error)

AuthenticateWithCode performs the full OAuth2 flow and returns/creates a user

func (*OAuthService) AuthorizationURL

func (o *OAuthService) AuthorizationURL(state string) string

AuthorizationURL generates the OAuth2 authorization URL

func (*OAuthService) ExchangeCode

func (o *OAuthService) ExchangeCode(ctx context.Context, code string) (*TokenResponse, error)

ExchangeCode exchanges an authorization code for tokens

func (*OAuthService) GetUserInfo

func (o *OAuthService) GetUserInfo(ctx context.Context, accessToken string) (*HanzoIDUserInfo, error)

GetUserInfo fetches user info from hanzo.id

func (*OAuthService) Logout

func (o *OAuthService) Logout(ctx context.Context, user *User) error

Logout revokes the user's hanzo.id token

func (*OAuthService) RefreshToken

func (o *OAuthService) RefreshToken(ctx context.Context, refreshToken string) (*TokenResponse, error)

RefreshToken refreshes an access token

func (*OAuthService) ValidateToken

func (o *OAuthService) ValidateToken(ctx context.Context, user *User) error

ValidateToken checks if a user's hanzo.id token is still valid

type OAuthToken

type OAuthToken struct {
	Provider     OAuthProvider `json:"provider"`
	AccessToken  string        `json:"-"`
	RefreshToken string        `json:"-"`
	TokenType    string        `json:"tokenType,omitempty"`
	ExpiresAt    time.Time     `json:"expiresAt,omitempty"`
	Scope        string        `json:"scope,omitempty"`
	ProviderUID  string        `json:"providerUid,omitempty"`
}

OAuthToken represents an OAuth2 token from a provider

type PrivacySettings

type PrivacySettings struct {
	// Profile visibility
	ProfileVisible   bool `json:"profileVisible"`
	ShowOrderHistory bool `json:"showOrderHistory"`
	ShowWishlist     bool `json:"showWishlist"`
	ShowReviews      bool `json:"showReviews"`

	// Data sharing
	ShareAnalytics       bool `json:"shareAnalytics"`
	AllowPersonalization bool `json:"allowPersonalization"`
	AllowThirdParty      bool `json:"allowThirdParty"`

	// Activity tracking
	TrackActivity       bool `json:"trackActivity"`
	SaveBrowsingHistory bool `json:"saveBrowsingHistory"`
	SaveSearchHistory   bool `json:"saveSearchHistory"`
}

PrivacySettings controls data privacy options

type Profile

type Profile struct {
	UserID string `json:"userId"`

	// Display info
	DisplayName string `json:"displayName,omitempty"`
	Bio         string `json:"bio,omitempty"`
	AvatarURL   string `json:"avatarUrl,omitempty"`
	CoverURL    string `json:"coverUrl,omitempty"`

	// Contact preferences
	PreferredLanguage string `json:"preferredLanguage,omitempty"`
	Timezone          string `json:"timezone,omitempty"`
	Currency          string `json:"currency,omitempty"`

	// Social links
	Website  string `json:"website,omitempty"`
	Twitter  string `json:"twitter,omitempty"`
	GitHub   string `json:"github,omitempty"`
	LinkedIn string `json:"linkedin,omitempty"`
	Discord  string `json:"discord,omitempty"`
	Telegram string `json:"telegram,omitempty"`

	// Professional info
	JobTitle   string   `json:"jobTitle,omitempty"`
	Department string   `json:"department,omitempty"`
	Skills     []string `json:"skills,omitempty"`
	Interests  []string `json:"interests,omitempty"`

	// Verification badges
	Badges []Badge `json:"badges,omitempty"`

	// Activity tracking
	LastActiveAt time.Time `json:"lastActiveAt,omitempty"`
	JoinedAt     time.Time `json:"joinedAt,omitempty"`

	// Stats (cached)
	OrderCount    int `json:"orderCount,omitempty"`
	ReferralCount int `json:"referralCount,omitempty"`
	ReviewCount   int `json:"reviewCount,omitempty"`
	TotalSpent    int `json:"totalSpent,omitempty"` // In cents
	LoyaltyPoints int `json:"loyaltyPoints,omitempty"`

	// Privacy settings
	ProfilePublic     bool `json:"profilePublic,omitempty"`
	ShowEmail         bool `json:"showEmail,omitempty"`
	ShowWalletAddress bool `json:"showWalletAddress,omitempty"`
	ShowActivity      bool `json:"showActivity,omitempty"`

	// Timestamps
	CreatedAt time.Time `json:"createdAt"`
	UpdatedAt time.Time `json:"updatedAt"`
}

Profile represents extended user profile information

func (*Profile) Kind

func (p *Profile) Kind() string

Kind implements db.Entity

func (*Profile) ToPublic

func (p *Profile) ToPublic() *PublicProfile

ToPublic converts a profile to its public representation

type ProfileRepository

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

ProfileRepository provides data access for Profile entities

func NewProfileRepository

func NewProfileRepository(database db.DB) *ProfileRepository

NewProfileRepository creates a new Profile repository

func (*ProfileRepository) AddBadge

func (r *ProfileRepository) AddBadge(ctx context.Context, userID string, badge Badge) error

AddBadge adds a badge to the profile

func (*ProfileRepository) Create

func (r *ProfileRepository) Create(ctx context.Context, profile *Profile) error

Create creates a new profile

func (*ProfileRepository) Delete

func (r *ProfileRepository) Delete(ctx context.Context, userID string) error

Delete deletes a profile

func (*ProfileRepository) Get

func (r *ProfileRepository) Get(ctx context.Context, userID string) (*Profile, error)

Get retrieves a profile by user ID

func (*ProfileRepository) GetOrCreate

func (r *ProfileRepository) GetOrCreate(ctx context.Context, userID string) (*Profile, error)

GetOrCreate retrieves a profile or creates a default one

func (*ProfileRepository) RemoveBadge

func (r *ProfileRepository) RemoveBadge(ctx context.Context, userID string, badgeID string) error

RemoveBadge removes a badge from the profile

func (*ProfileRepository) Update

func (r *ProfileRepository) Update(ctx context.Context, profile *Profile) error

Update updates an existing profile

func (*ProfileRepository) UpdateActivity

func (r *ProfileRepository) UpdateActivity(ctx context.Context, userID string) error

UpdateActivity updates the last active timestamp

func (*ProfileRepository) UpdateStats

func (r *ProfileRepository) UpdateStats(ctx context.Context, userID string, stats *ProfileStats) error

UpdateStats updates cached statistics

type ProfileService

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

ProfileService provides high-level profile operations

func NewProfileService

func NewProfileService(service *Service) *ProfileService

NewProfileService creates a new profile service

func (*ProfileService) Get

func (s *ProfileService) Get(ctx context.Context, userID string) (*Profile, error)

Get retrieves a user's profile

func (*ProfileService) GetPublic

func (s *ProfileService) GetPublic(ctx context.Context, userID string) (*PublicProfile, error)

GetPublic retrieves a public profile

func (*ProfileService) Update

func (s *ProfileService) Update(ctx context.Context, profile *Profile) error

Update updates a user's profile

type ProfileStats

type ProfileStats struct {
	OrderCount    int
	ReferralCount int
	ReviewCount   int
	TotalSpent    int
	LoyaltyPoints int
}

ProfileStats holds stats to update

type PublicProfile

type PublicProfile struct {
	UserID      string    `json:"userId"`
	DisplayName string    `json:"displayName,omitempty"`
	Bio         string    `json:"bio,omitempty"`
	AvatarURL   string    `json:"avatarUrl,omitempty"`
	Website     string    `json:"website,omitempty"`
	Twitter     string    `json:"twitter,omitempty"`
	GitHub      string    `json:"github,omitempty"`
	Badges      []Badge   `json:"badges,omitempty"`
	JoinedAt    time.Time `json:"joinedAt,omitempty"`
}

PublicProfile returns a sanitized profile for public viewing

type Repository

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

Repository provides data access for User entities

func NewRepository

func NewRepository(database db.DB) *Repository

NewRepository creates a new User repository

func (*Repository) Authenticate

func (r *Repository) Authenticate(ctx context.Context, email, password string) (*User, error)

Authenticate validates credentials and returns the user

func (*Repository) Count

func (r *Repository) Count(ctx context.Context) (int, error)

Count returns the total number of users

func (*Repository) Create

func (r *Repository) Create(ctx context.Context, user *User) error

Create creates a new user

func (*Repository) Delete

func (r *Repository) Delete(ctx context.Context, id string) error

Delete soft-deletes a user

func (*Repository) Get

func (r *Repository) Get(ctx context.Context, id string) (*User, error)

Get retrieves a user by ID

func (*Repository) GetByEmail

func (r *Repository) GetByEmail(ctx context.Context, email string) (*User, error)

GetByEmail retrieves a user by email

func (*Repository) GetByHanzoID

func (r *Repository) GetByHanzoID(ctx context.Context, hanzoID string) (*User, error)

GetByHanzoID retrieves a user by their hanzo.id

func (*Repository) GetByUsername

func (r *Repository) GetByUsername(ctx context.Context, username string) (*User, error)

GetByUsername retrieves a user by username

func (*Repository) HardDelete

func (r *Repository) HardDelete(ctx context.Context, id string) error

HardDelete permanently deletes a user

func (*Repository) List

func (r *Repository) List(ctx context.Context, opts *ListOptions) ([]*User, error)

List retrieves users with pagination

func (*Repository) ListByOrganization

func (r *Repository) ListByOrganization(ctx context.Context, orgID string, opts *ListOptions) ([]*User, error)

ListByOrganization retrieves users belonging to an organization

func (*Repository) Update

func (r *Repository) Update(ctx context.Context, user *User) error

Update updates an existing user

type SecuritySettings

type SecuritySettings struct {
	// Two-factor authentication
	TwoFactorEnabled bool   `json:"twoFactorEnabled"`
	TwoFactorMethod  string `json:"twoFactorMethod,omitempty"` // "totp", "sms", "email"

	// Session management
	SessionTimeout    int  `json:"sessionTimeout,omitempty"` // Minutes
	RememberMe        bool `json:"rememberMe"`
	SingleSessionOnly bool `json:"singleSessionOnly"`

	// Login security
	RequirePasswordChange bool      `json:"requirePasswordChange"`
	LastPasswordChange    time.Time `json:"lastPasswordChange,omitempty"`
	LoginNotifications    bool      `json:"loginNotifications"`

	// Trusted devices
	TrustedDevices []TrustedDevice `json:"trustedDevices,omitempty"`

	// Recovery options
	RecoveryEmail string `json:"recoveryEmail,omitempty"`
	RecoveryPhone string `json:"recoveryPhone,omitempty"`
}

SecuritySettings controls account security

type Service

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

Service provides high-level user operations. It manages the database connection and provides factory methods.

func NewService

func NewService(manager *db.Manager) *Service

NewService creates a new user service with the database manager

func (*Service) Authenticate

func (s *Service) Authenticate(ctx context.Context, email, password string) (*User, error)

Authenticate validates credentials against the user's database

func (*Service) Create

func (s *Service) Create(ctx context.Context, user *User) error

Create creates a new user and initializes their personal database

func (*Service) Delete

func (s *Service) Delete(ctx context.Context, userID string) error

Delete soft-deletes a user

func (*Service) Get

func (s *Service) Get(ctx context.Context, userID string) (*User, error)

Get retrieves a user by ID using their personal database

func (*Service) OrgDB

func (s *Service) OrgDB(orgID string) (db.DB, error)

OrgDB returns a database for an organization. This provides access to the organization's shared SQLite database.

func (*Service) Repository

func (s *Service) Repository(database db.DB) *Repository

Repository returns a user repository for the given database

func (*Service) Update

func (s *Service) Update(ctx context.Context, user *User) error

Update updates an existing user in their personal database

func (*Service) UserDB

func (s *Service) UserDB(userID string) (db.DB, error)

UserDB returns a database for a specific user. This provides access to the user's personal SQLite database.

type Settings

type Settings struct {
	UserID string `json:"userId"`

	// Notification preferences
	Notifications NotificationSettings `json:"notifications"`

	// Privacy settings
	Privacy PrivacySettings `json:"privacy"`

	// Commerce preferences
	Commerce CommerceSettings `json:"commerce"`

	// Display preferences
	Display DisplaySettings `json:"display"`

	// Security settings
	Security SecuritySettings `json:"security"`

	// API/Developer settings
	Developer DeveloperSettings `json:"developer,omitempty"`

	// Timestamps
	CreatedAt time.Time `json:"createdAt"`
	UpdatedAt time.Time `json:"updatedAt"`
}

Settings represents user preferences and configuration

func DefaultSettings

func DefaultSettings(userID string) *Settings

DefaultSettings returns default settings for a new user

func (*Settings) Kind

func (s *Settings) Kind() string

Kind implements db.Entity

type SettingsRepository

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

SettingsRepository provides data access for Settings entities

func NewSettingsRepository

func NewSettingsRepository(database db.DB) *SettingsRepository

NewSettingsRepository creates a new Settings repository

func (*SettingsRepository) AddAPIKey

func (r *SettingsRepository) AddAPIKey(ctx context.Context, userID string, key APIKey) error

AddAPIKey adds an API key

func (*SettingsRepository) AddTrustedDevice

func (r *SettingsRepository) AddTrustedDevice(ctx context.Context, userID string, device TrustedDevice) error

AddTrustedDevice adds a trusted device

func (*SettingsRepository) Create

func (r *SettingsRepository) Create(ctx context.Context, settings *Settings) error

Create creates new settings

func (*SettingsRepository) Delete

func (r *SettingsRepository) Delete(ctx context.Context, userID string) error

Delete deletes settings

func (*SettingsRepository) Get

func (r *SettingsRepository) Get(ctx context.Context, userID string) (*Settings, error)

Get retrieves settings by user ID

func (*SettingsRepository) GetOrCreate

func (r *SettingsRepository) GetOrCreate(ctx context.Context, userID string) (*Settings, error)

GetOrCreate retrieves settings or creates defaults

func (*SettingsRepository) RemoveAPIKey

func (r *SettingsRepository) RemoveAPIKey(ctx context.Context, userID string, keyID string) error

RemoveAPIKey removes an API key

func (*SettingsRepository) RemoveTrustedDevice

func (r *SettingsRepository) RemoveTrustedDevice(ctx context.Context, userID string, deviceID string) error

RemoveTrustedDevice removes a trusted device

func (*SettingsRepository) Update

func (r *SettingsRepository) Update(ctx context.Context, settings *Settings) error

Update updates existing settings

type SettingsService

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

SettingsService provides high-level settings operations

func NewSettingsService

func NewSettingsService(service *Service) *SettingsService

NewSettingsService creates a new settings service

func (*SettingsService) Get

func (s *SettingsService) Get(ctx context.Context, userID string) (*Settings, error)

Get retrieves user settings

func (*SettingsService) Update

func (s *SettingsService) Update(ctx context.Context, settings *Settings) error

Update updates user settings

func (*SettingsService) UpdateNotifications

func (s *SettingsService) UpdateNotifications(ctx context.Context, userID string, notifications NotificationSettings) error

UpdateNotifications updates only notification settings

func (*SettingsService) UpdatePrivacy

func (s *SettingsService) UpdatePrivacy(ctx context.Context, userID string, privacy PrivacySettings) error

UpdatePrivacy updates only privacy settings

func (*SettingsService) UpdateSecurity

func (s *SettingsService) UpdateSecurity(ctx context.Context, userID string, security SecuritySettings) error

UpdateSecurity updates only security settings

type TokenResponse

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

TokenResponse represents the OAuth2 token response

type Transaction

type Transaction struct {
	ID            string                 `json:"id"`
	WalletID      string                 `json:"walletId"`
	UserID        string                 `json:"userId"`
	AccountType   AccountType            `json:"accountType"`
	Type          string                 `json:"type"` // "credit", "debit", "hold", "release", "capture"
	Currency      Currency               `json:"currency"`
	Amount        int64                  `json:"amount"`
	BalanceAfter  int64                  `json:"balanceAfter"`
	Reason        string                 `json:"reason,omitempty"`
	ReferenceID   string                 `json:"referenceId,omitempty"`
	ReferenceType string                 `json:"referenceType,omitempty"` // "order", "refund", "reward", etc.
	Metadata      map[string]interface{} `json:"metadata,omitempty"`
	CreatedAt     time.Time              `json:"createdAt"`
}

Transaction represents a wallet transaction

func (*Transaction) Kind

func (t *Transaction) Kind() string

Kind implements db.Entity

type TrustedDevice

type TrustedDevice struct {
	ID         string    `json:"id"`
	Name       string    `json:"name"`
	DeviceType string    `json:"deviceType"` // "desktop", "mobile", "tablet"
	Browser    string    `json:"browser,omitempty"`
	OS         string    `json:"os,omitempty"`
	LastUsed   time.Time `json:"lastUsed"`
	AddedAt    time.Time `json:"addedAt"`
	IPAddress  string    `json:"ipAddress,omitempty"`
}

TrustedDevice represents a device trusted for login

type User

type User struct {
	// Core identity
	ID        string    `json:"id"`
	CreatedAt time.Time `json:"createdAt"`
	UpdatedAt time.Time `json:"updatedAt"`
	Deleted   bool      `json:"deleted,omitempty"`

	// Basic info
	Username  string `json:"username,omitempty"`
	Email     string `json:"email"`
	FirstName string `json:"firstName"`
	LastName  string `json:"lastName"`
	Company   string `json:"company,omitempty"`
	Phone     string `json:"phone,omitempty"`

	// Addresses
	BillingAddress  Address `json:"billingAddress,omitempty"`
	ShippingAddress Address `json:"shippingAddress,omitempty"`

	// Auth
	PasswordHash []byte `json:"-"`
	Enabled      bool   `json:"enabled"`
	PreApproved  bool   `json:"preApproved,omitempty"`

	// OAuth integration
	OAuthTokens []OAuthToken `json:"-"`
	Facebook    Facebook     `json:"-"`

	// Hanzo.id IAM integration
	HanzoID         string `json:"hanzoId,omitempty"`
	HanzoIDVerified bool   `json:"hanzoIdVerified,omitempty"`

	// KYC verification
	KYC KYC `json:"kyc,omitempty"`

	// Organization membership
	Organizations []string `json:"-"`

	// Commerce
	StoreID    string `json:"storeId,omitempty"`
	ReferrerID string `json:"referrerId,omitempty"`
	FormID     string `json:"formId,omitempty"`

	// Wallet integration (Lux blockchain)
	WalletID         string `json:"walletId,omitempty"`
	WalletPassphrase string `json:"-"`

	// Affiliate
	IsAffiliate bool   `json:"isAffiliate,omitempty"`
	AffiliateID string `json:"affiliateId,omitempty"`

	// Payment
	PaypalEmail string `json:"paypalEmail,omitempty"`

	// Metadata
	Metadata map[string]interface{} `json:"metadata,omitempty"`

	// Flags
	Test    bool `json:"test,omitempty"`
	IsOwner bool `json:"owner,omitempty"`

	// History tracking
	History []Event `json:"-"`
}

User represents a user in the commerce system. It uses per-user SQLite databases for personal data storage.

func New

func New() *User

New creates a new User with default values

func NewFromHanzoID

func NewFromHanzoID(hanzoID string, email string) *User

NewFromHanzoID creates a new User linked to a hanzo.id account

func NewWithEmail

func NewWithEmail(email string) *User

NewWithEmail creates a new User with the given email

func (*User) AddEvent

func (u *User) AddEvent(eventType string, data map[string]interface{}, actor string)

AddEvent adds a historical event to the user

func (*User) AddOrganization

func (u *User) AddOrganization(orgID string)

AddOrganization adds an organization to the user's membership

func (*User) Buyer

func (u *User) Buyer() Buyer

Buyer returns buyer information for orders

func (*User) Clone

func (u *User) Clone() *User

Clone creates a deep copy of the user

func (*User) ComparePassword

func (u *User) ComparePassword(pass string) bool

ComparePassword compares the given password against the stored hash

func (*User) GetMetadata

func (u *User) GetMetadata(key string) (interface{}, bool)

GetMetadata gets a metadata value by key

func (*User) GetOAuthToken

func (u *User) GetOAuthToken(provider OAuthProvider) *OAuthToken

GetOAuthToken returns the OAuth token for a provider

func (*User) HasHanzoID

func (u *User) HasHanzoID() bool

HasHanzoID returns true if the user is linked to hanzo.id

func (*User) HasPassword

func (u *User) HasPassword() bool

HasPassword returns true if the user has a password set

func (*User) InOrganization

func (u *User) InOrganization(orgID string) bool

InOrganization checks if the user belongs to an organization

func (*User) IsKYCApproved

func (u *User) IsKYCApproved() bool

IsKYCApproved returns true if the user has completed KYC verification

func (*User) IsKYCRequired

func (u *User) IsKYCRequired() bool

IsKYCRequired returns true if KYC verification is required but not completed

func (*User) Kind

func (u *User) Kind() string

Kind implements db.Entity

func (*User) MarshalJSON

func (u *User) MarshalJSON() ([]byte, error)

MarshalJSON customizes JSON marshaling

func (*User) Merge

func (u *User) Merge(other *User)

Merge updates the user with non-zero values from another user

func (*User) Name

func (u *User) Name() string

Name returns the user's full name

func (*User) RemoveOAuthToken

func (u *User) RemoveOAuthToken(provider OAuthProvider)

RemoveOAuthToken removes an OAuth token for a provider

func (*User) RemoveOrganization

func (u *User) RemoveOrganization(orgID string)

RemoveOrganization removes an organization from the user's membership

func (*User) SetMetadata

func (u *User) SetMetadata(key string, value interface{})

SetMetadata sets a metadata key-value pair

func (*User) SetOAuthToken

func (u *User) SetOAuthToken(token OAuthToken)

SetOAuthToken sets or updates an OAuth token

func (*User) SetPassword

func (u *User) SetPassword(newPassword string) error

SetPassword hashes and stores a new password

func (*User) SyncToDatastore

func (u *User) SyncToDatastore() bool

SyncToDatastore returns true - users should be synced to analytics

func (*User) Validate

func (u *User) Validate() error

Validate validates the user data

type UserEmailIndex

type UserEmailIndex struct {
	Email  string `json:"email"`
	UserID string `json:"userId"`
}

UserEmailIndex is stored in the system database for email lookups

func (*UserEmailIndex) Kind

func (i *UserEmailIndex) Kind() string

Kind implements db.Entity

type Wallet

type Wallet struct {
	ID     string `json:"id"`
	UserID string `json:"userId"`

	// Accounts by type
	Accounts map[AccountType]*Account `json:"accounts"`

	// Blockchain addresses
	Addresses []WalletAddress `json:"addresses,omitempty"`

	// Default currency
	DefaultCurrency Currency `json:"defaultCurrency"`

	// Security
	Locked     bool      `json:"locked"`
	LockedAt   time.Time `json:"lockedAt,omitempty"`
	LockReason string    `json:"lockReason,omitempty"`

	// Timestamps
	CreatedAt time.Time `json:"createdAt"`
	UpdatedAt time.Time `json:"updatedAt"`
}

Wallet represents a user's wallet with multiple accounts

func (*Wallet) GetAccount

func (w *Wallet) GetAccount(accountType AccountType) *Account

GetAccount returns an account by type, creating if needed

func (*Wallet) GetAddresses

func (w *Wallet) GetAddresses(chain string) []WalletAddress

GetAddresses returns all addresses for a chain

func (*Wallet) GetAvailableBalance

func (w *Wallet) GetAvailableBalance(accountType AccountType, currency Currency) int64

GetAvailableBalance returns the available balance (total - holds)

func (*Wallet) GetBalance

func (w *Wallet) GetBalance(accountType AccountType, currency Currency) *Balance

GetBalance returns the balance for a currency in an account

func (*Wallet) GetPrimaryAddress

func (w *Wallet) GetPrimaryAddress(chain string) *WalletAddress

GetPrimaryAddress returns the primary address for a chain

func (*Wallet) Kind

func (w *Wallet) Kind() string

Kind implements db.Entity

type WalletAddress

type WalletAddress struct {
	ID        string    `json:"id"`
	Chain     string    `json:"chain"` // "lux", "ethereum", "bitcoin"
	Address   string    `json:"address"`
	Label     string    `json:"label,omitempty"`
	IsPrimary bool      `json:"isPrimary"`
	Verified  bool      `json:"verified"`
	AddedAt   time.Time `json:"addedAt"`
}

WalletAddress represents a blockchain address linked to the wallet

type WalletRepository

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

WalletRepository provides data access for Wallet entities

func NewWalletRepository

func NewWalletRepository(database db.DB) *WalletRepository

NewWalletRepository creates a new Wallet repository

func (*WalletRepository) Create

func (r *WalletRepository) Create(ctx context.Context, wallet *Wallet) error

Create creates a new wallet

func (*WalletRepository) Delete

func (r *WalletRepository) Delete(ctx context.Context, walletID string) error

Delete deletes a wallet

func (*WalletRepository) Get

func (r *WalletRepository) Get(ctx context.Context, walletID string) (*Wallet, error)

Get retrieves a wallet by ID

func (*WalletRepository) GetByUserID

func (r *WalletRepository) GetByUserID(ctx context.Context, userID string) (*Wallet, error)

GetByUserID retrieves a wallet by user ID

func (*WalletRepository) GetOrCreate

func (r *WalletRepository) GetOrCreate(ctx context.Context, userID string) (*Wallet, error)

GetOrCreate retrieves a wallet or creates a new one

func (*WalletRepository) Update

func (r *WalletRepository) Update(ctx context.Context, wallet *Wallet) error

Update updates an existing wallet

type WalletService

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

WalletService provides high-level wallet operations

func NewWalletService

func NewWalletService(service *Service) *WalletService

NewWalletService creates a new wallet service

func (*WalletService) AddAddress

func (s *WalletService) AddAddress(ctx context.Context, userID string, address WalletAddress) error

AddAddress adds a blockchain address to the wallet

func (*WalletService) CaptureHold

func (s *WalletService) CaptureHold(ctx context.Context, userID string, accountType AccountType, holdID string) error

CaptureHold captures (deducts) a held amount

func (*WalletService) Credit

func (s *WalletService) Credit(ctx context.Context, userID string, accountType AccountType, currency Currency, amount int64, reason string) error

Credit adds funds to a wallet account

func (*WalletService) Debit

func (s *WalletService) Debit(ctx context.Context, userID string, accountType AccountType, currency Currency, amount int64, reason string) error

Debit removes funds from a wallet account

func (*WalletService) Get

func (s *WalletService) Get(ctx context.Context, userID string) (*Wallet, error)

Get retrieves a user's wallet

func (*WalletService) GetOrCreate

func (s *WalletService) GetOrCreate(ctx context.Context, userID string) (*Wallet, error)

GetOrCreate retrieves or creates a user's wallet

func (*WalletService) LockWallet

func (s *WalletService) LockWallet(ctx context.Context, userID string, reason string) error

LockWallet locks a wallet

func (*WalletService) PlaceHold

func (s *WalletService) PlaceHold(ctx context.Context, userID string, accountType AccountType, currency Currency, amount int64, reason string, referenceID string, expiresAt time.Time) (*Hold, error)

PlaceHold places a hold on funds

func (*WalletService) ReleaseHold

func (s *WalletService) ReleaseHold(ctx context.Context, userID string, accountType AccountType, holdID string) error

ReleaseHold releases a hold

func (*WalletService) RemoveAddress

func (s *WalletService) RemoveAddress(ctx context.Context, userID string, addressID string) error

RemoveAddress removes a blockchain address from the wallet

func (*WalletService) SetPrimaryAddress

func (s *WalletService) SetPrimaryAddress(ctx context.Context, userID string, addressID string) error

SetPrimaryAddress sets an address as primary for its chain

func (*WalletService) UnlockWallet

func (s *WalletService) UnlockWallet(ctx context.Context, userID string) error

UnlockWallet unlocks a wallet

Jump to

Keyboard shortcuts

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