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
- Variables
- func GenerateState() (string, error)
- func Query(database db.DB) db.Query
- type APIKey
- type Account
- type AccountType
- type Address
- type Badge
- type Balance
- type Buyer
- type CommerceSettings
- type Currency
- type DeveloperSettings
- type DisplaySettings
- type Event
- type Facebook
- type HanzoIDConfig
- type HanzoIDIndex
- type HanzoIDUserInfo
- type Hold
- type KYC
- type KYCData
- type KYCStatus
- type ListOptions
- type NotificationSettings
- type OAuthProvider
- type OAuthService
- func (o *OAuthService) AuthenticateWithCode(ctx context.Context, code string) (*User, error)
- func (o *OAuthService) AuthorizationURL(state string) string
- func (o *OAuthService) ExchangeCode(ctx context.Context, code string) (*TokenResponse, error)
- func (o *OAuthService) GetUserInfo(ctx context.Context, accessToken string) (*HanzoIDUserInfo, error)
- func (o *OAuthService) Logout(ctx context.Context, user *User) error
- func (o *OAuthService) RefreshToken(ctx context.Context, refreshToken string) (*TokenResponse, error)
- func (o *OAuthService) ValidateToken(ctx context.Context, user *User) error
- type OAuthToken
- type PrivacySettings
- type Profile
- type ProfileRepository
- func (r *ProfileRepository) AddBadge(ctx context.Context, userID string, badge Badge) error
- func (r *ProfileRepository) Create(ctx context.Context, profile *Profile) error
- func (r *ProfileRepository) Delete(ctx context.Context, userID string) error
- func (r *ProfileRepository) Get(ctx context.Context, userID string) (*Profile, error)
- func (r *ProfileRepository) GetOrCreate(ctx context.Context, userID string) (*Profile, error)
- func (r *ProfileRepository) RemoveBadge(ctx context.Context, userID string, badgeID string) error
- func (r *ProfileRepository) Update(ctx context.Context, profile *Profile) error
- func (r *ProfileRepository) UpdateActivity(ctx context.Context, userID string) error
- func (r *ProfileRepository) UpdateStats(ctx context.Context, userID string, stats *ProfileStats) error
- type ProfileService
- type ProfileStats
- type PublicProfile
- type Repository
- func (r *Repository) Authenticate(ctx context.Context, email, password string) (*User, error)
- func (r *Repository) Count(ctx context.Context) (int, error)
- func (r *Repository) Create(ctx context.Context, user *User) error
- func (r *Repository) Delete(ctx context.Context, id string) error
- func (r *Repository) Get(ctx context.Context, id string) (*User, error)
- func (r *Repository) GetByEmail(ctx context.Context, email string) (*User, error)
- func (r *Repository) GetByHanzoID(ctx context.Context, hanzoID string) (*User, error)
- func (r *Repository) GetByUsername(ctx context.Context, username string) (*User, error)
- func (r *Repository) HardDelete(ctx context.Context, id string) error
- func (r *Repository) List(ctx context.Context, opts *ListOptions) ([]*User, error)
- func (r *Repository) ListByOrganization(ctx context.Context, orgID string, opts *ListOptions) ([]*User, error)
- func (r *Repository) Update(ctx context.Context, user *User) error
- type SecuritySettings
- type Service
- func (s *Service) Authenticate(ctx context.Context, email, password string) (*User, error)
- func (s *Service) Create(ctx context.Context, user *User) error
- func (s *Service) Delete(ctx context.Context, userID string) error
- func (s *Service) Get(ctx context.Context, userID string) (*User, error)
- func (s *Service) OrgDB(orgID string) (db.DB, error)
- func (s *Service) Repository(database db.DB) *Repository
- func (s *Service) Update(ctx context.Context, user *User) error
- func (s *Service) UserDB(userID string) (db.DB, error)
- type Settings
- type SettingsRepository
- func (r *SettingsRepository) AddAPIKey(ctx context.Context, userID string, key APIKey) error
- func (r *SettingsRepository) AddTrustedDevice(ctx context.Context, userID string, device TrustedDevice) error
- func (r *SettingsRepository) Create(ctx context.Context, settings *Settings) error
- func (r *SettingsRepository) Delete(ctx context.Context, userID string) error
- func (r *SettingsRepository) Get(ctx context.Context, userID string) (*Settings, error)
- func (r *SettingsRepository) GetOrCreate(ctx context.Context, userID string) (*Settings, error)
- func (r *SettingsRepository) RemoveAPIKey(ctx context.Context, userID string, keyID string) error
- func (r *SettingsRepository) RemoveTrustedDevice(ctx context.Context, userID string, deviceID string) error
- func (r *SettingsRepository) Update(ctx context.Context, settings *Settings) error
- type SettingsService
- func (s *SettingsService) Get(ctx context.Context, userID string) (*Settings, error)
- func (s *SettingsService) Update(ctx context.Context, settings *Settings) error
- func (s *SettingsService) UpdateNotifications(ctx context.Context, userID string, notifications NotificationSettings) error
- func (s *SettingsService) UpdatePrivacy(ctx context.Context, userID string, privacy PrivacySettings) error
- func (s *SettingsService) UpdateSecurity(ctx context.Context, userID string, security SecuritySettings) error
- type TokenResponse
- type Transaction
- type TrustedDevice
- type User
- func (u *User) AddEvent(eventType string, data map[string]interface{}, actor string)
- func (u *User) AddOrganization(orgID string)
- func (u *User) Buyer() Buyer
- func (u *User) Clone() *User
- func (u *User) ComparePassword(pass string) bool
- func (u *User) GetMetadata(key string) (interface{}, bool)
- func (u *User) GetOAuthToken(provider OAuthProvider) *OAuthToken
- func (u *User) HasHanzoID() bool
- func (u *User) HasPassword() bool
- func (u *User) InOrganization(orgID string) bool
- func (u *User) IsKYCApproved() bool
- func (u *User) IsKYCRequired() bool
- func (u *User) Kind() string
- func (u *User) MarshalJSON() ([]byte, error)
- func (u *User) Merge(other *User)
- func (u *User) Name() string
- func (u *User) RemoveOAuthToken(provider OAuthProvider)
- func (u *User) RemoveOrganization(orgID string)
- func (u *User) SetMetadata(key string, value interface{})
- func (u *User) SetOAuthToken(token OAuthToken)
- func (u *User) SetPassword(newPassword string) error
- func (u *User) SyncToDatastore() bool
- func (u *User) Validate() error
- type UserEmailIndex
- type Wallet
- func (w *Wallet) GetAccount(accountType AccountType) *Account
- func (w *Wallet) GetAddresses(chain string) []WalletAddress
- func (w *Wallet) GetAvailableBalance(accountType AccountType, currency Currency) int64
- func (w *Wallet) GetBalance(accountType AccountType, currency Currency) *Balance
- func (w *Wallet) GetPrimaryAddress(chain string) *WalletAddress
- func (w *Wallet) Kind() string
- type WalletAddress
- type WalletRepository
- func (r *WalletRepository) Create(ctx context.Context, wallet *Wallet) error
- func (r *WalletRepository) Delete(ctx context.Context, walletID string) error
- func (r *WalletRepository) Get(ctx context.Context, walletID string) (*Wallet, error)
- func (r *WalletRepository) GetByUserID(ctx context.Context, userID string) (*Wallet, error)
- func (r *WalletRepository) GetOrCreate(ctx context.Context, userID string) (*Wallet, error)
- func (r *WalletRepository) Update(ctx context.Context, wallet *Wallet) error
- type WalletService
- func (s *WalletService) AddAddress(ctx context.Context, userID string, address WalletAddress) error
- func (s *WalletService) CaptureHold(ctx context.Context, userID string, accountType AccountType, holdID string) error
- func (s *WalletService) Credit(ctx context.Context, userID string, accountType AccountType, currency Currency, ...) error
- func (s *WalletService) Debit(ctx context.Context, userID string, accountType AccountType, currency Currency, ...) error
- func (s *WalletService) Get(ctx context.Context, userID string) (*Wallet, error)
- func (s *WalletService) GetOrCreate(ctx context.Context, userID string) (*Wallet, error)
- func (s *WalletService) LockWallet(ctx context.Context, userID string, reason string) error
- func (s *WalletService) PlaceHold(ctx context.Context, userID string, accountType AccountType, currency Currency, ...) (*Hold, error)
- func (s *WalletService) ReleaseHold(ctx context.Context, userID string, accountType AccountType, holdID string) error
- func (s *WalletService) RemoveAddress(ctx context.Context, userID string, addressID string) error
- func (s *WalletService) SetPrimaryAddress(ctx context.Context, userID string, addressID string) error
- func (s *WalletService) UnlockWallet(ctx context.Context, userID string) error
Constants ¶
const Kind = "user"
Entity kind for User
Variables ¶
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
var ( ErrProfileNotFound = errors.New("profile: not found") ErrProfileInvalidField = errors.New("profile: invalid field") ErrAvatarTooLarge = errors.New("profile: avatar too large") )
Profile errors
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") ErrAccountDisabled = errors.New("user: account disabled") ErrKYCRequired = errors.New("user: KYC verification required") )
Common errors
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
var (
ErrSettingsNotFound = errors.New("settings: not found")
)
Settings errors
Functions ¶
func GenerateState ¶
GenerateState generates a secure random state parameter
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 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/oauth/authorize
TokenURL string // Default: https://hanzo.id/oauth/token
UserInfoURL string // Default: https://hanzo.id/api/userinfo
Scopes []string
}
HanzoIDConfig holds configuration for hanzo.id OAuth2
func DefaultHanzoIDConfig ¶
func DefaultHanzoIDConfig() *HanzoIDConfig
DefaultHanzoIDConfig returns default hanzo.id configuration
type HanzoIDIndex ¶
HanzoIDIndex maps hanzo.id to user ID
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
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 ¶
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
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) 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) 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) GetOrCreate ¶
GetOrCreate retrieves a profile or creates a default one
func (*ProfileRepository) RemoveBadge ¶
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) GetPublic ¶
func (s *ProfileService) GetPublic(ctx context.Context, userID string) (*PublicProfile, error)
GetPublic retrieves a public 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 ¶
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) GetByEmail ¶
GetByEmail retrieves a user by email
func (*Repository) GetByHanzoID ¶
GetByHanzoID retrieves a user by their hanzo.id
func (*Repository) GetByUsername ¶
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
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 ¶
NewService creates a new user service with the database manager
func (*Service) Authenticate ¶
Authenticate validates credentials against the user's database
func (*Service) OrgDB ¶
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
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 ¶
DefaultSettings returns default settings for a new user
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) 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) GetOrCreate ¶
GetOrCreate retrieves settings or creates defaults
func (*SettingsRepository) RemoveAPIKey ¶
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
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) 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
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 NewFromHanzoID ¶
NewFromHanzoID creates a new User linked to a hanzo.id account
func NewWithEmail ¶
NewWithEmail creates a new User with the given email
func (*User) AddOrganization ¶
AddOrganization adds an organization to the user's membership
func (*User) ComparePassword ¶
ComparePassword compares the given password against the stored hash
func (*User) GetMetadata ¶
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 ¶
HasHanzoID returns true if the user is linked to hanzo.id
func (*User) HasPassword ¶
HasPassword returns true if the user has a password set
func (*User) InOrganization ¶
InOrganization checks if the user belongs to an organization
func (*User) IsKYCApproved ¶
IsKYCApproved returns true if the user has completed KYC verification
func (*User) IsKYCRequired ¶
IsKYCRequired returns true if KYC verification is required but not completed
func (*User) MarshalJSON ¶
MarshalJSON customizes JSON marshaling
func (*User) RemoveOAuthToken ¶
func (u *User) RemoveOAuthToken(provider OAuthProvider)
RemoveOAuthToken removes an OAuth token for a provider
func (*User) RemoveOrganization ¶
RemoveOrganization removes an organization from the user's membership
func (*User) SetMetadata ¶
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 ¶
SetPassword hashes and stores a new password
func (*User) SyncToDatastore ¶
SyncToDatastore returns true - users should be synced to analytics
type UserEmailIndex ¶
UserEmailIndex is stored in the system database for email lookups
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
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) GetByUserID ¶
GetByUserID retrieves a wallet by user ID
func (*WalletRepository) GetOrCreate ¶
GetOrCreate retrieves a wallet or creates a new one
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) GetOrCreate ¶
GetOrCreate retrieves or creates a user's wallet
func (*WalletService) LockWallet ¶
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 ¶
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