domain

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Dec 7, 2025 License: MIT Imports: 6 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AccountLockout

type AccountLockout struct {
	ID          uuid.UUID  `gorm:"type:uuid;primary_key;default:gen_random_uuid()" json:"id"`
	TenantID    uuid.UUID  `gorm:"type:uuid;not null;index" json:"tenant_id"`
	UserID      uuid.UUID  `gorm:"type:uuid;not null;index:idx_lockout_tenant_user,unique" json:"user_id"`
	Email       string     `gorm:"type:varchar(255);not null;index" json:"email"` // Denormalized for faster lookups
	LockedAt    time.Time  `gorm:"not null" json:"locked_at"`
	UnlocksAt   time.Time  `gorm:"not null;index" json:"unlocks_at"`
	LockReason  string     `gorm:"type:varchar(100);not null" json:"lock_reason"`
	FailedCount int        `gorm:"not null" json:"failed_count"`
	UnlockedAt  *time.Time `gorm:"index" json:"unlocked_at,omitempty"`     // Set when manually unlocked
	UnlockedBy  *uuid.UUID `gorm:"type:uuid" json:"unlocked_by,omitempty"` // Admin who unlocked
	CreatedAt   time.Time  `gorm:"autoCreateTime" json:"created_at"`
	UpdatedAt   time.Time  `gorm:"autoUpdateTime" json:"updated_at"`
}

AccountLockout tracks locked accounts Required for brute force protection (HIPAA, SOC 2)

func (*AccountLockout) IsLocked

func (a *AccountLockout) IsLocked() bool

IsLocked checks if the account is currently locked

func (AccountLockout) TableName

func (AccountLockout) TableName() string

TableName specifies the table name for AccountLockout model

type AuditAction

type AuditAction string

AuditAction represents the type of action being audited

const (
	// Authentication actions
	AuditActionLogin         AuditAction = "LOGIN"
	AuditActionLoginFailed   AuditAction = "LOGIN_FAILED"
	AuditActionLogout        AuditAction = "LOGOUT"
	AuditActionTokenRefresh  AuditAction = "TOKEN_REFRESH"
	AuditActionTokenValidate AuditAction = "TOKEN_VALIDATE"
	AuditActionTokenRevoke   AuditAction = "TOKEN_REVOKE"

	// Registration actions
	AuditActionRegister          AuditAction = "REGISTER"
	AuditActionEmailVerify       AuditAction = "EMAIL_VERIFY"
	AuditActionEmailVerifyResend AuditAction = "EMAIL_VERIFY_RESEND"

	// Password actions
	AuditActionPasswordChange       AuditAction = "PASSWORD_CHANGE"
	AuditActionPasswordReset        AuditAction = "PASSWORD_RESET"
	AuditActionPasswordResetRequest AuditAction = "PASSWORD_RESET_REQUEST"

	// MFA actions
	AuditActionMFAEnable         AuditAction = "MFA_ENABLE"
	AuditActionMFADisable        AuditAction = "MFA_DISABLE"
	AuditActionMFAVerify         AuditAction = "MFA_VERIFY"
	AuditActionMFABackupGenerate AuditAction = "MFA_BACKUP_GENERATE"
	AuditActionMFABackupUsed     AuditAction = "MFA_BACKUP_USED"

	// Session actions
	AuditActionSessionCreate    AuditAction = "SESSION_CREATE"
	AuditActionSessionRevoke    AuditAction = "SESSION_REVOKE"
	AuditActionSessionRevokeAll AuditAction = "SESSION_REVOKE_ALL"

	// OAuth actions
	AuditActionOAuthLink   AuditAction = "OAUTH_LINK"
	AuditActionOAuthUnlink AuditAction = "OAUTH_UNLINK"
	AuditActionOAuthLogin  AuditAction = "OAUTH_LOGIN"

	// Passwordless actions
	AuditActionPasswordlessSend   AuditAction = "PASSWORDLESS_SEND"
	AuditActionPasswordlessVerify AuditAction = "PASSWORDLESS_VERIFY"

	// Profile actions
	AuditActionProfileUpdate AuditAction = "PROFILE_UPDATE"
	AuditActionProfileView   AuditAction = "PROFILE_VIEW"

	// Account actions
	AuditActionAccountLock   AuditAction = "ACCOUNT_LOCK"
	AuditActionAccountUnlock AuditAction = "ACCOUNT_UNLOCK"
	AuditActionAccountDelete AuditAction = "ACCOUNT_DELETE"

	// Admin actions
	AuditActionAdminUserCreate AuditAction = "ADMIN_USER_CREATE"
	AuditActionAdminUserUpdate AuditAction = "ADMIN_USER_UPDATE"
	AuditActionAdminUserDelete AuditAction = "ADMIN_USER_DELETE"
)

type AuditLog

type AuditLog struct {
	ID            uuid.UUID         `gorm:"type:uuid;primary_key;default:gen_random_uuid()" json:"id"`
	TenantID      uuid.UUID         `gorm:"type:uuid;not null;index" json:"tenant_id"`
	UserID        *uuid.UUID        `gorm:"type:uuid;index" json:"user_id,omitempty"`  // The user affected by the action
	ActorID       *uuid.UUID        `gorm:"type:uuid;index" json:"actor_id,omitempty"` // The user who performed the action (for admin actions)
	Action        AuditAction       `gorm:"type:varchar(50);not null;index" json:"action"`
	ResourceType  AuditResourceType `gorm:"type:varchar(50);not null;index" json:"resource_type"`
	ResourceID    string            `gorm:"index" json:"resource_id,omitempty"`
	Status        AuditStatus       `gorm:"type:varchar(20);not null;index" json:"status"`
	FailureReason string            `gorm:"type:text" json:"failure_reason,omitempty"`
	IPAddress     string            `gorm:"type:varchar(45);not null" json:"ip_address"` // IPv6 max length
	UserAgent     string            `gorm:"type:text" json:"user_agent,omitempty"`
	SessionID     *uuid.UUID        `gorm:"type:uuid;index" json:"session_id,omitempty"`
	Metadata      JSONMap           `gorm:"type:jsonb;default:'{}'" json:"metadata,omitempty"` // Additional context
	CreatedAt     time.Time         `gorm:"autoCreateTime;index" json:"created_at"`
}

AuditLog represents a comprehensive audit trail entry This is critical for HIPAA, SOC 2, and GDPR compliance

func NewAuditLog

func NewAuditLog(tenantID uuid.UUID, action AuditAction, resourceType AuditResourceType, status AuditStatus, ipAddress string) *AuditLog

NewAuditLog creates a new audit log entry with required fields

func (AuditLog) TableName

func (AuditLog) TableName() string

TableName specifies the table name for AuditLog model

func (*AuditLog) WithActor

func (a *AuditLog) WithActor(actorID uuid.UUID) *AuditLog

WithActor sets the actor ID for the audit log (for admin actions)

func (*AuditLog) WithFailure

func (a *AuditLog) WithFailure(reason string) *AuditLog

WithFailure sets the failure reason for the audit log

func (*AuditLog) WithMetadata

func (a *AuditLog) WithMetadata(key string, value interface{}) *AuditLog

WithMetadata adds metadata to the audit log

func (*AuditLog) WithResource

func (a *AuditLog) WithResource(resourceID string) *AuditLog

WithResource sets the resource ID for the audit log

func (*AuditLog) WithSession

func (a *AuditLog) WithSession(sessionID uuid.UUID) *AuditLog

WithSession sets the session ID for the audit log

func (*AuditLog) WithUser

func (a *AuditLog) WithUser(userID uuid.UUID) *AuditLog

WithUser sets the user ID for the audit log

func (*AuditLog) WithUserAgent

func (a *AuditLog) WithUserAgent(userAgent string) *AuditLog

WithUserAgent sets the user agent for the audit log

type AuditResourceType

type AuditResourceType string

AuditResourceType represents the type of resource being acted upon

const (
	AuditResourceUser    AuditResourceType = "USER"
	AuditResourceSession AuditResourceType = "SESSION"
	AuditResourceOTP     AuditResourceType = "OTP"
	AuditResourceOAuth   AuditResourceType = "OAUTH"
	AuditResourceTenant  AuditResourceType = "TENANT"
)

type AuditStatus

type AuditStatus string

AuditStatus represents the status of an audited action

const (
	AuditStatusSuccess AuditStatus = "SUCCESS"
	AuditStatusFailure AuditStatus = "FAILURE"
)

type BackupCode

type BackupCode struct {
	ID        uuid.UUID      `gorm:"type:uuid;primary_key;default:gen_random_uuid()" json:"id"`
	TenantID  uuid.UUID      `gorm:"type:uuid;not null;index" json:"tenant_id"`
	UserID    uuid.UUID      `gorm:"type:uuid;not null;index" json:"user_id"`
	Code      string         `gorm:"not null" json:"code"`
	Used      bool           `gorm:"default:false" json:"used"`
	UsedAt    *time.Time     `gorm:"column:used_at" json:"used_at,omitempty"`
	CreatedAt time.Time      `gorm:"autoCreateTime" json:"created_at"`
	DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
}

BackupCode represents a 2FA backup code

func (BackupCode) TableName

func (BackupCode) TableName() string

TableName specifies the table name for BackupCode model

type IPRateLimit

type IPRateLimit struct {
	ID           uuid.UUID  `gorm:"type:uuid;primary_key;default:gen_random_uuid()" json:"id"`
	TenantID     uuid.UUID  `gorm:"type:uuid;not null;index" json:"tenant_id"`
	IPAddress    string     `gorm:"type:varchar(45);not null;index:idx_ip_rate_tenant_ip,unique" json:"ip_address"`
	AttemptCount int        `gorm:"not null;default:0" json:"attempt_count"`
	BlockedUntil *time.Time `gorm:"index" json:"blocked_until,omitempty"`
	FirstAttempt time.Time  `gorm:"not null" json:"first_attempt"`
	LastAttempt  time.Time  `gorm:"not null" json:"last_attempt"`
	CreatedAt    time.Time  `gorm:"autoCreateTime" json:"created_at"`
	UpdatedAt    time.Time  `gorm:"autoUpdateTime" json:"updated_at"`
}

IPRateLimit tracks rate limiting by IP address Prevents distributed brute force attacks

func (*IPRateLimit) IsBlocked

func (i *IPRateLimit) IsBlocked() bool

IsBlocked checks if the IP is currently blocked

func (IPRateLimit) TableName

func (IPRateLimit) TableName() string

TableName specifies the table name for IPRateLimit model

type JSONMap

type JSONMap map[string]interface{}

JSONMap is a helper type for JSONB columns

func (*JSONMap) Scan

func (j *JSONMap) Scan(value interface{}) error

Scan implements the sql.Scanner interface for database deserialization

func (JSONMap) Value

func (j JSONMap) Value() (driver.Value, error)

Value implements the driver.Valuer interface for database serialization

type LockReason

type LockReason string

LockReason represents the reason for account lockout

const (
	LockReasonTooManyFailedAttempts LockReason = "TOO_MANY_FAILED_ATTEMPTS"
	LockReasonSuspiciousActivity    LockReason = "SUSPICIOUS_ACTIVITY"
	LockReasonAdminAction           LockReason = "ADMIN_ACTION"
	LockReasonSecurityBreach        LockReason = "SECURITY_BREACH"
)

type LoginAttempt

type LoginAttempt struct {
	ID          uuid.UUID  `gorm:"type:uuid;primary_key;default:gen_random_uuid()" json:"id"`
	TenantID    uuid.UUID  `gorm:"type:uuid;not null;index" json:"tenant_id"`
	Email       string     `gorm:"type:varchar(255);not null;index" json:"email"`
	UserID      *uuid.UUID `gorm:"type:uuid;index" json:"user_id,omitempty"` // Set if user exists
	IPAddress   string     `gorm:"type:varchar(45);not null;index" json:"ip_address"`
	UserAgent   string     `gorm:"type:text" json:"user_agent,omitempty"`
	Success     bool       `gorm:"not null;index" json:"success"`
	FailReason  string     `gorm:"type:varchar(100)" json:"fail_reason,omitempty"`
	AttemptedAt time.Time  `gorm:"autoCreateTime;index" json:"attempted_at"`
}

LoginAttempt tracks all authentication attempts for security monitoring Required for HIPAA and SOC 2 compliance

func (LoginAttempt) TableName

func (LoginAttempt) TableName() string

TableName specifies the table name for LoginAttempt model

type LoginFailReason

type LoginFailReason string

LoginFailReason represents the reason for a failed login

const (
	LoginFailReasonInvalidCredentials LoginFailReason = "INVALID_CREDENTIALS"
	LoginFailReasonAccountLocked      LoginFailReason = "ACCOUNT_LOCKED"
	LoginFailReasonAccountDisabled    LoginFailReason = "ACCOUNT_DISABLED"
	LoginFailReasonEmailNotVerified   LoginFailReason = "EMAIL_NOT_VERIFIED"
	LoginFailReasonMFARequired        LoginFailReason = "MFA_REQUIRED"
	LoginFailReasonMFAInvalid         LoginFailReason = "MFA_INVALID"
	LoginFailReasonTenantInactive     LoginFailReason = "TENANT_INACTIVE"
	LoginFailReasonRateLimited        LoginFailReason = "RATE_LIMITED"
)

type OAuthAccount

type OAuthAccount struct {
	ID             uuid.UUID         `gorm:"type:uuid;primary_key;default:gen_random_uuid()" json:"id"`
	TenantID       uuid.UUID         `gorm:"type:uuid;not null;index:idx_oauth_tenant_provider_user,unique" json:"tenant_id"`
	UserID         uuid.UUID         `gorm:"type:uuid;not null;index" json:"user_id"`
	Provider       string            `gorm:"not null;index:idx_oauth_tenant_provider_user,unique" json:"provider"` // google, github, facebook, apple
	ProviderUserID string            `gorm:"column:provider_user_id;not null;index:idx_oauth_tenant_provider_user,unique" json:"provider_user_id"`
	Email          string            `json:"email"`
	AccessToken    string            `gorm:"column:access_token" json:"-"`
	RefreshToken   string            `gorm:"column:refresh_token" json:"-"`
	ExpiresAt      *time.Time        `gorm:"column:expires_at" json:"expires_at,omitempty"`
	Metadata       map[string]string `gorm:"type:jsonb" json:"metadata,omitempty"`
	LinkedAt       time.Time         `gorm:"column:linked_at;autoCreateTime" json:"linked_at"`
	UpdatedAt      time.Time         `gorm:"autoUpdateTime" json:"updated_at"`
	DeletedAt      gorm.DeletedAt    `gorm:"index" json:"-"`
}

OAuthAccount represents a linked OAuth provider account

func (OAuthAccount) TableName

func (OAuthAccount) TableName() string

TableName specifies the table name for OAuthAccount model

type OTP

type OTP struct {
	ID        uuid.UUID         `gorm:"type:uuid;primary_key;default:gen_random_uuid()" json:"id"`
	TenantID  uuid.UUID         `gorm:"type:uuid;not null;index:idx_otp_tenant_email_type" json:"tenant_id"`
	UserID    uuid.UUID         `gorm:"type:uuid;index" json:"user_id"` // May be null for email verification before registration
	Email     string            `gorm:"not null;index:idx_otp_tenant_email_type" json:"email"`
	Token     string            `gorm:"uniqueIndex:idx_otp_tenant_token,unique;not null" json:"token"`
	Type      OTPType           `gorm:"type:varchar(50);not null;index:idx_otp_tenant_email_type" json:"type"`
	Code      string            `json:"code,omitempty"` // Optional numeric code (for 2FA, etc.)
	Used      bool              `gorm:"default:false;index" json:"used"`
	UsedAt    *time.Time        `gorm:"column:used_at" json:"used_at,omitempty"`
	ExpiresAt time.Time         `gorm:"column:expires_at;not null;index" json:"expires_at"`
	Metadata  map[string]string `gorm:"type:jsonb" json:"metadata,omitempty"`
	CreatedAt time.Time         `gorm:"autoCreateTime" json:"created_at"`
	DeletedAt gorm.DeletedAt    `gorm:"index" json:"-"`
}

OTP represents a one-time password/token

func (*OTP) BeforeCreate

func (o *OTP) BeforeCreate(tx *gorm.DB) error

BeforeCreate hook to generate UUID if not set

func (*OTP) IsExpired

func (o *OTP) IsExpired() bool

IsExpired checks if the OTP has expired

func (*OTP) IsValid

func (o *OTP) IsValid() bool

IsValid checks if the OTP is valid (not used and not expired)

func (*OTP) MarkAsUsed

func (o *OTP) MarkAsUsed()

MarkAsUsed marks the OTP as used

func (OTP) TableName

func (OTP) TableName() string

TableName specifies the table name for OTP model

type OTPType

type OTPType string

OTPType represents the type of OTP

const (
	OTPTypeEmailVerification OTPType = "email_verification"
	OTPTypePasswordReset     OTPType = "password_reset"
	OTPTypePasswordless      OTPType = "passwordless"
	OTPType2FA               OTPType = "two_factor"
)

type PasswordHistory

type PasswordHistory struct {
	ID           uuid.UUID `gorm:"type:uuid;primary_key;default:gen_random_uuid()" json:"id"`
	TenantID     uuid.UUID `gorm:"type:uuid;not null;index" json:"tenant_id"`
	UserID       uuid.UUID `gorm:"type:uuid;not null;index" json:"user_id"`
	PasswordHash string    `gorm:"type:varchar(255);not null" json:"-"` // Never expose
	CreatedAt    time.Time `gorm:"autoCreateTime;index" json:"created_at"`
}

PasswordHistory tracks password history to prevent reuse Required for SOC 2 compliance

func (PasswordHistory) TableName

func (PasswordHistory) TableName() string

TableName specifies the table name for PasswordHistory model

type Session

type Session struct {
	ID             uuid.UUID `gorm:"type:uuid;primary_key;default:gen_random_uuid()" json:"id"`
	TenantID       uuid.UUID `gorm:"type:uuid;not null;index:idx_session_tenant_user" json:"tenant_id"`
	UserID         uuid.UUID `gorm:"type:uuid;not null;index:idx_session_tenant_user" json:"user_id"`
	User           *User     `gorm:"foreignKey:UserID" json:"user,omitempty"`
	RefreshToken   string    `gorm:"column:refresh_token;uniqueIndex:idx_session_tenant_refresh,unique;not null" json:"-"`
	DeviceID       string    `gorm:"column:device_id" json:"device_id"`
	DeviceName     string    `gorm:"column:device_name" json:"device_name"`
	IPAddress      string    `gorm:"column:ip_address" json:"ip_address"`
	UserAgent      string    `gorm:"column:user_agent" json:"user_agent"`
	LastAccessedAt time.Time `gorm:"column:last_accessed_at;autoUpdateTime" json:"last_accessed_at"`
	ExpiresAt      time.Time `gorm:"column:expires_at;not null;index" json:"expires_at"`
	// Compliance fields for session security
	IdleTimeoutAt *time.Time     `gorm:"column:idle_timeout_at;index" json:"idle_timeout_at,omitempty"` // For HIPAA idle timeout
	CreatedAt     time.Time      `gorm:"autoCreateTime" json:"created_at"`
	UpdatedAt     time.Time      `gorm:"autoUpdateTime" json:"updated_at"`
	RevokedAt     *time.Time     `gorm:"column:revoked_at;index" json:"revoked_at,omitempty"`
	DeletedAt     gorm.DeletedAt `gorm:"index" json:"-"`
}

Session represents an active user session

func (*Session) BeforeCreate

func (s *Session) BeforeCreate(tx *gorm.DB) error

BeforeCreate hook to generate UUID if not set

func (*Session) IsActive

func (s *Session) IsActive() bool

IsActive checks if the session is still active

func (*Session) IsExpired

func (s *Session) IsExpired() bool

IsExpired checks if the session has expired

func (*Session) Revoke

func (s *Session) Revoke()

Revoke marks the session as revoked

func (Session) TableName

func (Session) TableName() string

TableName specifies the table name for Session model

type Tenant

type Tenant struct {
	ID        uuid.UUID      `gorm:"type:uuid;primary_key;default:gen_random_uuid()" json:"id"`
	Name      string         `gorm:"not null" json:"name"`
	Slug      string         `gorm:"uniqueIndex;not null" json:"slug"`
	Status    TenantStatus   `gorm:"type:varchar(50);default:'active';not null" json:"status"`
	Domain    string         `gorm:"index" json:"domain,omitempty"`           // Optional: for domain-based tenant resolution
	Settings  JSONMap        `gorm:"type:jsonb;default:'{}'" json:"settings"` // Tenant-specific settings
	CreatedAt time.Time      `gorm:"autoCreateTime" json:"created_at"`
	UpdatedAt time.Time      `gorm:"autoUpdateTime" json:"updated_at"`
	DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
}

Tenant represents an organization/tenant in the multi-tenant system

func (*Tenant) BeforeCreate

func (t *Tenant) BeforeCreate(tx *gorm.DB) error

BeforeCreate hook to generate UUID if not set

func (*Tenant) IsActive

func (t *Tenant) IsActive() bool

IsActive checks if the tenant is active

func (Tenant) TableName

func (Tenant) TableName() string

TableName specifies the table name for Tenant model

type TenantStatus

type TenantStatus string

TenantStatus represents the status of a tenant

const (
	TenantStatusActive    TenantStatus = "active"
	TenantStatusSuspended TenantStatus = "suspended"
	TenantStatusPending   TenantStatus = "pending"
)

type User

type User struct {
	ID               uuid.UUID         `gorm:"type:uuid;primary_key;default:gen_random_uuid()" json:"id"`
	TenantID         uuid.UUID         `gorm:"type:uuid;not null;index:idx_user_tenant_email,unique" json:"tenant_id"`
	Email            string            `gorm:"not null;index:idx_user_tenant_email,unique" json:"email"`
	PasswordHash     string            `gorm:"column:password_hash" json:"-"`
	FirstName        string            `gorm:"column:first_name" json:"first_name"`
	LastName         string            `gorm:"column:last_name" json:"last_name"`
	PhoneNumber      string            `gorm:"column:phone_number" json:"phone_number,omitempty"`
	EmailVerified    bool              `gorm:"default:false" json:"email_verified"`
	EmailVerifiedAt  *time.Time        `gorm:"column:email_verified_at" json:"email_verified_at,omitempty"`
	TwoFactorEnabled bool              `gorm:"default:false" json:"two_factor_enabled"`
	TwoFactorSecret  string            `gorm:"column:two_factor_secret" json:"-"`
	BackupCodes      []BackupCode      `gorm:"foreignKey:UserID" json:"-"`
	OAuthAccounts    []OAuthAccount    `gorm:"foreignKey:UserID" json:"oauth_accounts,omitempty"`
	Sessions         []Session         `gorm:"foreignKey:UserID" json:"-"`
	Metadata         map[string]string `gorm:"type:jsonb" json:"metadata,omitempty"`
	LastLoginAt      *time.Time        `gorm:"column:last_login_at" json:"last_login_at,omitempty"`
	// Compliance fields
	LockedUntil        *time.Time     `gorm:"column:locked_until;index" json:"locked_until,omitempty"`
	FailedLoginCount   int            `gorm:"column:failed_login_count;default:0" json:"failed_login_count"`
	LastFailedLoginAt  *time.Time     `gorm:"column:last_failed_login_at" json:"last_failed_login_at,omitempty"`
	MustChangePassword bool           `gorm:"column:must_change_password;default:false" json:"must_change_password"`
	PasswordChangedAt  *time.Time     `gorm:"column:password_changed_at" json:"password_changed_at,omitempty"`
	CreatedAt          time.Time      `gorm:"autoCreateTime" json:"created_at"`
	UpdatedAt          time.Time      `gorm:"autoUpdateTime" json:"updated_at"`
	DeletedAt          gorm.DeletedAt `gorm:"index" json:"-"`
}

User represents a user in the system

func (*User) BeforeCreate

func (u *User) BeforeCreate(tx *gorm.DB) error

BeforeCreate hook to generate UUID if not set

func (User) TableName

func (User) TableName() string

TableName specifies the table name for User model

Jump to

Keyboard shortcuts

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