user

package
v0.1.6 Latest Latest
Warning

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

Go to latest
Published: Apr 14, 2026 License: GPL-3.0 Imports: 5 Imported by: 0

Documentation

Overview

Package user provides the user domain model.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrUserNotFound      = fmt.Errorf("user %w", shared.ErrNotFound)
	ErrUserAlreadyExists = fmt.Errorf("user %w", shared.ErrAlreadyExists)
	ErrUserSuspended     = errors.New("user is suspended")
	ErrUserInactive      = errors.New("user is inactive")
	ErrInvalidEmail      = fmt.Errorf("%w: invalid email", shared.ErrValidation)

	// Authentication errors
	ErrInvalidCredentials        = errors.New("invalid email or password")
	ErrAccountLocked             = errors.New("account is locked due to too many failed attempts")
	ErrEmailNotVerified          = errors.New("email address not verified")
	ErrPasswordTooWeak           = errors.New("password does not meet requirements")
	ErrInvalidVerificationToken  = errors.New("invalid or expired verification token")
	ErrInvalidPasswordResetToken = errors.New("invalid or expired password reset token")
	ErrCannotChangeOIDCPassword  = errors.New("cannot change password for OIDC users")
)

Domain errors for user operations.

Functions

func AlreadyExistsError

func AlreadyExistsError(email string) error

AlreadyExistsError creates an already exists error for a specific email.

func NotFoundByEmailError

func NotFoundByEmailError(email string) error

NotFoundByEmailError creates a not found error for a specific email.

func NotFoundByKeycloakIDError

func NotFoundByKeycloakIDError(keycloakID string) error

NotFoundByKeycloakIDError creates a not found error for a specific Keycloak ID.

func NotFoundError

func NotFoundError(userID shared.ID) error

NotFoundError creates a not found error for a specific user.

Types

type AuthProvider

type AuthProvider string

AuthProvider represents the authentication provider for a user.

const (
	// AuthProviderLocal indicates local email/password authentication.
	AuthProviderLocal AuthProvider = "local"
	// AuthProviderOIDC indicates external OIDC authentication (Keycloak).
	AuthProviderOIDC AuthProvider = "oidc"
	// AuthProviderGoogle indicates Google OAuth authentication.
	AuthProviderGoogle AuthProvider = "google"
	// AuthProviderGitHub indicates GitHub OAuth authentication.
	AuthProviderGitHub AuthProvider = "github"
	// AuthProviderMicrosoft indicates Microsoft/EntraID OAuth authentication.
	AuthProviderMicrosoft AuthProvider = "microsoft"
)

func (AuthProvider) IsOAuth

func (p AuthProvider) IsOAuth() bool

IsOAuth returns true if the auth provider is an OAuth provider.

func (AuthProvider) IsValid

func (p AuthProvider) IsValid() bool

IsValid checks if the auth provider is valid.

func (AuthProvider) String

func (p AuthProvider) String() string

String returns the string representation of the auth provider.

type Filter

type Filter struct {
	Email    *string
	Status   *Status
	Statuses []Status
}

Filter represents criteria for filtering users.

func (Filter) WithEmail

func (f Filter) WithEmail(email string) Filter

WithEmail sets the email filter.

func (Filter) WithStatus

func (f Filter) WithStatus(status Status) Filter

WithStatus sets a single status filter.

func (Filter) WithStatuses

func (f Filter) WithStatuses(statuses ...Status) Filter

WithStatuses sets multiple status filters.

type Preferences

type Preferences struct {
	Theme         string `json:"theme,omitempty"`         // "light", "dark", "system"
	Language      string `json:"language,omitempty"`      // "en", "vi"
	Notifications bool   `json:"notifications,omitempty"` // Enable notifications
}

Preferences represents user preferences stored as JSONB.

type Repository

type Repository interface {
	// CRUD operations
	Create(ctx context.Context, user *User) error
	GetByID(ctx context.Context, id shared.ID) (*User, error)
	GetByKeycloakID(ctx context.Context, keycloakID string) (*User, error)
	GetByEmail(ctx context.Context, email string) (*User, error)
	Update(ctx context.Context, user *User) error
	Delete(ctx context.Context, id shared.ID) error

	// Existence checks
	ExistsByEmail(ctx context.Context, email string) (bool, error)
	ExistsByKeycloakID(ctx context.Context, keycloakID string) (bool, error)

	// Upsert for Keycloak sync - creates or updates user, returns the user
	UpsertFromKeycloak(ctx context.Context, keycloakID, email, name string) (*User, error)

	// Batch operations
	GetByIDs(ctx context.Context, ids []shared.ID) ([]*User, error)

	// Count
	Count(ctx context.Context, filter Filter) (int64, error)

	// Local auth operations
	// GetByEmailForAuth retrieves a local user by email for authentication.
	GetByEmailForAuth(ctx context.Context, email string) (*User, error)

	// GetByEmailVerificationToken retrieves a user by email verification token.
	GetByEmailVerificationToken(ctx context.Context, token string) (*User, error)

	// GetByPasswordResetToken retrieves a user by password reset token.
	GetByPasswordResetToken(ctx context.Context, token string) (*User, error)
}

Repository defines the interface for user persistence.

type Status

type Status string

Status represents the user account status.

const (
	StatusActive    Status = "active"
	StatusInactive  Status = "inactive"
	StatusSuspended Status = "suspended"
)

func (Status) IsValid

func (s Status) IsValid() bool

IsValid checks if the status is valid.

func (Status) String

func (s Status) String() string

String returns the string representation of the status.

type User

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

User represents a user entity in the domain.

func New

func New(email, name string) (*User, error)

New creates a new User without Keycloak (for future standalone auth). Deprecated: Use NewLocalUser for local authentication.

func NewFromKeycloak

func NewFromKeycloak(keycloakID, email, name string) (*User, error)

NewFromKeycloak creates a new User from Keycloak claims.

func NewLocalUser

func NewLocalUser(email, name, passwordHash string) (*User, error)

NewLocalUser creates a new local user with email/password authentication.

func NewLocalUserWithID

func NewLocalUserWithID(id shared.ID, email, name string) (*User, error)

NewLocalUserWithID creates a new local user with a specific ID (for syncing from JWT tokens). This is used when the user ID already exists in the JWT but not in the database.

func NewOAuthUser

func NewOAuthUser(email, name, avatarURL string, provider AuthProvider) (*User, error)

NewOAuthUser creates a new user from OAuth provider (Google, GitHub, Microsoft).

func Reconstitute

func Reconstitute(
	id shared.ID,
	keycloakID *string,
	email, name, avatarURL, phone string,
	status Status,
	preferences Preferences,
	lastLoginAt *time.Time,
	createdAt, updatedAt time.Time,

	authProvider AuthProvider,
	passwordHash *string,
	emailVerified bool,
	emailVerificationToken *string,
	emailVerificationExpiresAt *time.Time,
	passwordResetToken *string,
	passwordResetExpiresAt *time.Time,
	failedLoginAttempts int,
	lockedUntil *time.Time,
) *User

Reconstitute recreates a User from persistence.

func (*User) AuthProvider

func (u *User) AuthProvider() AuthProvider

AuthProvider returns the authentication provider.

func (*User) AvatarURL

func (u *User) AvatarURL() string

AvatarURL returns the user avatar URL.

func (*User) CanLogin

func (u *User) CanLogin() bool

CanLogin returns true if the user can attempt to login.

func (*User) ClearPasswordResetToken

func (u *User) ClearPasswordResetToken()

ClearPasswordResetToken clears the password reset token.

func (*User) CreatedAt

func (u *User) CreatedAt() time.Time

CreatedAt returns the creation timestamp.

func (*User) Email

func (u *User) Email() string

Email returns the user email.

func (*User) EmailVerificationExpiresAt

func (u *User) EmailVerificationExpiresAt() *time.Time

EmailVerificationExpiresAt returns when the verification token expires.

func (*User) EmailVerificationToken

func (u *User) EmailVerificationToken() *string

EmailVerificationToken returns the email verification token.

func (*User) EmailVerified

func (u *User) EmailVerified() bool

EmailVerified returns whether the email is verified.

func (*User) FailedLoginAttempts

func (u *User) FailedLoginAttempts() int

FailedLoginAttempts returns the number of failed login attempts.

func (*User) ID

func (u *User) ID() shared.ID

ID returns the user ID.

func (*User) IsActive

func (u *User) IsActive() bool

IsActive returns true if the user is active.

func (*User) IsEmailVerificationTokenValid

func (u *User) IsEmailVerificationTokenValid(token string) bool

IsEmailVerificationTokenValid returns true if the verification token is valid.

func (*User) IsLocalUser

func (u *User) IsLocalUser() bool

IsLocalUser returns true if this is a local auth user.

func (*User) IsLocked

func (u *User) IsLocked() bool

IsLocked returns true if the account is currently locked.

func (*User) IsOIDCUser

func (u *User) IsOIDCUser() bool

IsOIDCUser returns true if this is an OIDC auth user.

func (*User) IsPasswordResetTokenValid

func (u *User) IsPasswordResetTokenValid(token string) bool

IsPasswordResetTokenValid returns true if the reset token is valid.

func (*User) KeycloakID

func (u *User) KeycloakID() *string

KeycloakID returns the Keycloak user ID (may be nil).

func (*User) LastLoginAt

func (u *User) LastLoginAt() *time.Time

LastLoginAt returns the last login timestamp.

func (*User) LockedUntil

func (u *User) LockedUntil() *time.Time

LockedUntil returns when the account lockout expires.

func (*User) Name

func (u *User) Name() string

Name returns the user name.

func (*User) PasswordHash

func (u *User) PasswordHash() *string

PasswordHash returns the password hash (nil for OIDC users).

func (*User) PasswordResetExpiresAt

func (u *User) PasswordResetExpiresAt() *time.Time

PasswordResetExpiresAt returns when the password reset token expires.

func (*User) PasswordResetToken

func (u *User) PasswordResetToken() *string

PasswordResetToken returns the password reset token.

func (*User) Phone

func (u *User) Phone() string

Phone returns the user phone number.

func (*User) Preferences

func (u *User) Preferences() Preferences

Preferences returns the user preferences.

func (*User) RecordFailedLogin

func (u *User) RecordFailedLogin(maxAttempts int, lockoutDuration time.Duration)

RecordFailedLogin increments the failed login counter.

func (*User) RecordSuccessfulLogin

func (u *User) RecordSuccessfulLogin()

RecordSuccessfulLogin clears failed login attempts and updates last login.

func (*User) SetEmailVerificationToken

func (u *User) SetEmailVerificationToken(token string, expiresAt time.Time)

SetEmailVerificationToken sets a new email verification token.

func (*User) SetPasswordHash

func (u *User) SetPasswordHash(hash string) error

SetPasswordHash sets the password hash for local auth users.

func (*User) SetPasswordResetToken

func (u *User) SetPasswordResetToken(token string, expiresAt time.Time)

SetPasswordResetToken sets a new password reset token.

func (*User) Status

func (u *User) Status() Status

Status returns the user status.

func (*User) SyncFromKeycloak

func (u *User) SyncFromKeycloak(email, name string)

SyncFromKeycloak updates user info from Keycloak claims.

func (*User) Unlock

func (u *User) Unlock()

Unlock unlocks the user account.

func (*User) UpdateEmail

func (u *User) UpdateEmail(email string) error

UpdateEmail updates the user email.

func (*User) UpdateLastLogin

func (u *User) UpdateLastLogin()

UpdateLastLogin updates the last login timestamp to now.

func (*User) UpdatePreferences

func (u *User) UpdatePreferences(prefs Preferences)

UpdatePreferences updates the user preferences.

func (*User) UpdateProfile

func (u *User) UpdateProfile(name, phone, avatarURL string)

UpdateProfile updates the user profile.

func (*User) UpdatedAt

func (u *User) UpdatedAt() time.Time

UpdatedAt returns the last update timestamp.

func (*User) VerifyEmail

func (u *User) VerifyEmail()

VerifyEmail marks the email as verified.

Jump to

Keyboard shortcuts

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