user

package
v1.1.4 Latest Latest
Warning

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

Go to latest
Published: Nov 2, 2026 License: MIT Imports: 10 Imported by: 3 modules, 4 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

Index

Constants

View Source
const RoleCommentator = "Commentator"

RoleCommentator is the comment-system role. Admins may assign it only when comments are enabled. It mirrors internal/constants.RoleCommentator (the frozen role vocabulary); the module owns its assignment checks.

Variables

View Source
var (
	// ErrLastAdminDeletionForbidden is returned when attempting to delete the last admin
	ErrLastAdminDeletionForbidden = errors.New("cannot delete the last administrator account")
	// ErrInvalidConfirmationString is returned when the confirmation string is invalid
	ErrInvalidConfirmationString = errors.New("invalid confirmation string")
)
View Source
var (
	// ErrUsernameInvalid is returned when username format is invalid
	ErrUsernameInvalid = errors.New("username must be 1-50 characters and contain only letters, numbers, underscores, and hyphens")

	// ErrEmailInvalid is returned when email format is invalid
	ErrEmailInvalid = errors.New("please enter a valid email address")

	// ErrUsernameExists is returned when username already exists
	ErrUsernameExists = errors.New("username already exists")

	// ErrEmailExists is returned when email already exists
	ErrEmailExists = errors.New("email address already registered")

	// ErrEmailBlocked is returned when email is blocked
	ErrEmailBlocked = errors.New("this email address has been blocked")

	// ErrInvalidRole is returned when role is not in the allowed list
	ErrInvalidRole = errors.New("invalid user role")

	// ErrAdminCreateFailed is returned when admin user creation fails
	ErrAdminCreateFailed = errors.New("admin user creation failed")
)
View Source
var (
	ErrInvalidEmail        = errors.New("invalid email address")
	ErrEmailAlreadyInUse   = errors.New("email already in use")
	ErrInvalidPassword     = errors.New("invalid password")
	ErrProfileUserNotFound = errors.New("user not found")
)
View Source
var (
	ErrUserNotFound        = errors.New("user not found")
	ErrEmailAlreadyBlocked = errors.New("email is already blocked")
	ErrInvalidStatus       = errors.New("user is not in the expected status")
	ErrEmailNotVerified    = errors.New("user email is not verified")
)
View Source
var (
	// ErrAdminNotFound is returned when no admin user exists yet (fresh
	// install before first-login setup).
	ErrAdminNotFound = errors.New("admin user not found")
	// ErrSetupAlreadyCompleted is returned when first-login setup races:
	// another request completed it first.
	ErrSetupAlreadyCompleted = errors.New("first-login setup has already been completed")
)

Functions

This section is empty.

Types

type AccountDeletionService

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

AccountDeletionService handles account deletion operations

func NewAccountDeletionService

func NewAccountDeletionService(
	userRepo deletionUserStore,
	deletionRepo userDeletionStore,
	emailService Mailer,
	logger kernel.Logger,
) *AccountDeletionService

NewAccountDeletionService creates a new account deletion service. A nil logger degrades to a discard sink so the service is safe to construct in any context.

func (*AccountDeletionService) DeleteAccount

func (s *AccountDeletionService) DeleteAccount(ctx context.Context, principal kernel.Principal, userEmail string) error

DeleteAccount performs a hard delete of a user account and all associated data

func (*AccountDeletionService) ValidateConfirmationString

func (s *AccountDeletionService) ValidateConfirmationString(confirmation string) error

ValidateConfirmationString validates that the confirmation string is exactly "DELETE"

type AccountDeletionServiceInterface

type AccountDeletionServiceInterface interface {
	DeleteAccount(ctx context.Context, principal kernel.Principal, userEmail string) error
	ValidateConfirmationString(confirmation string) error
}

AccountDeletionServiceInterface defines the interface for account deletion operations

type AdminCreateUserOption

type AdminCreateUserOption func(*AdminCreateUserService)

AdminCreateUserOption configures an AdminCreateUserService. A role service makes the assignable-role allowlist config-driven; without one the legacy three-role allowlist applies.

func WithRegistrationEnabled

func WithRegistrationEnabled(enabled bool) AdminCreateUserOption

WithRegistrationEnabled overrides the registration gate consulted for the Commentator role. When unset it defaults to the comments flag (legacy coupling); the composition root sets it from [registration].IsEnabled.

func WithRoleService

func WithRoleService(rs RoleAssigner) AdminCreateUserOption

WithRoleService attaches the config-driven role registry so admins can assign every registered role (built-ins plus any [[role]] entries).

type AdminCreateUserRepo

type AdminCreateUserRepo interface {
	CheckUsernameExists(ctx context.Context, username string) (bool, error)
	CheckEmailExists(ctx context.Context, email string) (bool, error)
	CreateUser(ctx context.Context, user *User) error
}

AdminCreateUserRepo defines the repository methods needed for admin user creation

type AdminCreateUserRequest

type AdminCreateUserRequest struct {
	Username     string
	Name         string
	Email        string
	Role         string
	CustomFields map[string]any
}

AdminCreateUserRequest represents the input for admin user creation

type AdminCreateUserResult

type AdminCreateUserResult struct {
	User          *User
	PlainPassword string
}

AdminCreateUserResult contains the result of admin user creation

type AdminCreateUserService

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

AdminCreateUserService handles admin-initiated user creation

func NewAdminCreateUserService

func NewAdminCreateUserService(
	userRepo AdminCreateUserRepo,
	blockedEmailRepo BlockedEmailRepo,
	policy CredentialPolicy,
	commentsEnabled bool,
	opts ...AdminCreateUserOption,
) *AdminCreateUserService

NewAdminCreateUserService creates a new admin create user service. commentsEnabled gates the Commentator role: when false, admins cannot assign it (the role exists only for the comment system).

func (*AdminCreateUserService) CreateUser

CreateUser creates a new user with verified status and an auto-generated password

type BlockedEmailRepo

type BlockedEmailRepo interface {
	BlockEmail(ctx context.Context, email string, reason string) error
	IsEmailBlocked(ctx context.Context, email string) (bool, error)
	UnblockEmail(ctx context.Context, email string) error
}

BlockedEmailRepo defines the interface for blocked email repository operations

type CredentialPolicy

type CredentialPolicy interface {
	ValidateEmail(email string) error
	ValidateUsername(username string) error
	ValidatePassword(password string) error
	GeneratePassword(length int) (string, error)
	HashPassword(password string) (string, error)
	VerifyPassword(hash, password string) error
}

CredentialPolicy validates credentials and hashes passwords. The platform owns the policy (internal/auth rules plus the registration username rule); the module declares only the methods its services call.

type EmailUpdateRequest

type EmailUpdateRequest struct {
	NewEmail        string
	CurrentPassword string
}

EmailUpdateRequest represents a request to update email

type EmailUpdateToken

type EmailUpdateToken struct {
	ID        int
	Token     string
	UserID    int
	NewEmail  string
	ExpiresAt string
	CreatedAt time.Time
}

EmailUpdateToken represents an email update token in the system

type Mailer

type Mailer interface {
	SendEmailUpdateVerificationEmail(ctx context.Context, to, username, token string) error
	SendDataExportNotificationEmail(ctx context.Context, to, username string) error
	SendAccountDeletedNotification(ctx context.Context, to, username string) error
}

Mailer sends the account emails the users domain triggers. It carries exactly the sends the services perform; the core email service satisfies it structurally.

type PasswordUpdateRequest

type PasswordUpdateRequest struct {
	CurrentPassword string
	NewPassword     string
}

PasswordUpdateRequest represents a request to update password

type Profile

type Profile struct {
	ID             int
	Username       string
	Name           string
	Email          string
	Role           string
	ProfilePicture string
	CreatedAt      time.Time
	UpdatedAt      time.Time
	CustomFields   map[string]any
}

Profile represents user profile information

type ProfileService

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

ProfileService handles profile management operations

func NewProfileService

func NewProfileService(
	userRepo profileUserStore,
	emailUpdateTokenRepo emailTokenStore,
	userDataExportRepo userExportStore,
	emailService Mailer,
	policy CredentialPolicy,
	systemFieldProvider systemFieldProvider,
) *ProfileService

NewProfileService creates a new profile service

func (*ProfileService) ChangePassword

func (s *ProfileService) ChangePassword(ctx context.Context, principal kernel.Principal, currentPassword, newPassword string) error

ChangePassword updates a user's password

func (*ProfileService) ExportUserData

func (s *ProfileService) ExportUserData(ctx context.Context, principal kernel.Principal) (*UserDataExport, error)

ExportUserData generates a JSON export of all user data

func (*ProfileService) GetProfile

func (s *ProfileService) GetProfile(ctx context.Context, principal kernel.Principal) (*Profile, error)

GetProfile retrieves user profile information

func (*ProfileService) UpdateCustomFields

func (s *ProfileService) UpdateCustomFields(ctx context.Context, principal kernel.Principal, customFields map[string]any, isAdmin bool) error

UpdateCustomFields updates a user's custom fields. When isAdmin is false, system field slugs are stripped (defense-in-depth).

func (*ProfileService) UpdateEmail

func (s *ProfileService) UpdateEmail(ctx context.Context, principal kernel.Principal, newEmail, currentPasswordHash string) error

UpdateEmail initiates an email update by creating a verification token and sending an email

func (*ProfileService) UpdateName

func (s *ProfileService) UpdateName(ctx context.Context, principal kernel.Principal, name string) error

UpdateName updates a user's display name. Whitespace trimming is handled by the repository.

func (*ProfileService) VerifyEmailUpdate

func (s *ProfileService) VerifyEmailUpdate(ctx context.Context, token string) (int, string, error)

VerifyEmailUpdate verifies an email update token and updates the user's email

type ProfileServiceInterface

type ProfileServiceInterface interface {
	GetProfile(ctx context.Context, principal kernel.Principal) (*Profile, error)
	UpdateEmail(ctx context.Context, principal kernel.Principal, newEmail, currentPasswordHash string) error
	UpdateName(ctx context.Context, principal kernel.Principal, name string) error
	ChangePassword(ctx context.Context, principal kernel.Principal, currentPassword, newPassword string) error
	ExportUserData(ctx context.Context, principal kernel.Principal) (*UserDataExport, error)
	VerifyEmailUpdate(ctx context.Context, token string) (int, string, error)
	UpdateCustomFields(ctx context.Context, principal kernel.Principal, customFields map[string]any, isAdmin bool) error
}

ProfileServiceInterface defines the interface for profile service operations

type RoleAssigner

type RoleAssigner interface {
	IsAssignable(role string) bool
}

RoleAssigner reports whether an admin may assign a role. The core role service satisfies it structurally.

type User

type User struct {
	ID            int    `json:"id"`
	Username      string `json:"username"`
	PasswordHash  string `json:"-"`
	Email         string `json:"email"`
	Name          string `json:"name,omitempty"`
	Role          string `json:"role"`
	Status        string `json:"-"`
	EmailVerified bool   `json:"-"`
	// TokenVersion is embedded in every JWT and compared on each
	// authenticated request. Bumping it (password change or reset) revokes
	// tokens issued before the change instead of waiting for expiry.
	TokenVersion   int            `json:"-"`
	ProfilePicture string         `json:"profilePicture,omitempty"`
	LastLoginAt    *string        `json:"lastLoginAt,omitempty"`
	CustomFields   map[string]any `json:"customFields,omitempty"`
	// ConsentAt records when the user affirmed the terms at registration.
	// Nil for accounts created before consent was required or by an admin.
	ConsentAt *time.Time `json:"-"`
	// ConsentEvidence snapshots the document revisions the affirmation
	// referred to, as JSON. Empty when no evidence was captured.
	ConsentEvidence string    `json:"-"`
	CreatedAt       time.Time `json:"createdAt"`
	UpdatedAt       time.Time `json:"updatedAt"`
}

User represents a user in the system

type UserCommentItem

type UserCommentItem struct {
	ID            int       `json:"id"`
	ContentItemID int       `json:"contentItemId"`
	Content       string    `json:"content"`
	CreatedAt     time.Time `json:"createdAt"`
	UpdatedAt     time.Time `json:"updatedAt"`
}

UserCommentItem represents a comment posted by a user

type UserContentItem

type UserContentItem struct {
	ID        int       `json:"id"`
	Type      string    `json:"type"`
	Title     string    `json:"title"`
	Slug      string    `json:"slug"`
	Content   string    `json:"content"`
	Status    string    `json:"status"`
	CreatedAt time.Time `json:"createdAt"`
	UpdatedAt time.Time `json:"updatedAt"`
}

UserContentItem represents a content item (post/page) created by a user

type UserDataExport

type UserDataExport struct {
	ExportDate time.Time          `json:"exportDate"`
	User       *User              `json:"user"`
	Content    []*UserContentItem `json:"content"`
	Comments   []*UserCommentItem `json:"comments"`
	Media      []*UserMediaItem   `json:"media"`
}

UserDataExport represents all user data for export

type UserManagementOption

type UserManagementOption func(*UserManagementService)

UserManagementOption configures a UserManagementService. A role service makes the assignable-role allowlist config-driven; without one the legacy three-role allowlist applies.

func WithApprovalEmailRequired

func WithApprovalEmailRequired() UserManagementOption

WithApprovalEmailRequired makes admin approval conditional on the registrant having already proven their email address: approving a user whose email is not yet verified returns ErrEmailNotVerified. Without it, approval ignores the email state (legacy behavior).

func WithManagementRegistrationEnabled

func WithManagementRegistrationEnabled(enabled bool) UserManagementOption

WithManagementRegistrationEnabled overrides the registration gate consulted for the Commentator role on the update path. When unset it defaults to the comments flag (legacy coupling), mirroring AdminCreateUserService; the composition root sets it from [registration].IsEnabled.

func WithManagementRoleService

func WithManagementRoleService(rs RoleAssigner) UserManagementOption

WithManagementRoleService attaches the config-driven role registry so admins can assign every registered role (built-ins plus any [[role]] entries).

type UserManagementService

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

UserManagementService handles user management operations

func NewUserManagementService

func NewUserManagementService(
	userRepo UserRepo,
	blockedEmailRepo BlockedEmailRepo,
	policy CredentialPolicy,
	commentsEnabled bool,
	opts ...UserManagementOption,
) *UserManagementService

NewUserManagementService creates a new user management service. commentsEnabled gates the Commentator role on the update-user path: when false, admins cannot assign it (the role exists only for the comment system).

func (*UserManagementService) ApproveUser

func (s *UserManagementService) ApproveUser(ctx context.Context, userID int) error

ApproveUser approves a pending user by updating their status to verified. Uses an atomic status update to prevent TOCTOU race conditions. When the service was created with WithApprovalEmailRequired, the registrant must be pending AND have already proven their email address (email_verified) or the respective error is returned — status is checked before the email proof so that a non-pending user is never misreported as EMAIL_NOT_VERIFIED.

func (*UserManagementService) CountUsers

func (s *UserManagementService) CountUsers(ctx context.Context, status string) (int, error)

CountUsers returns the total number of users, optionally filtered by status — mirrors GetAllUsers' WHERE clause so a list's total always matches its rows.

func (*UserManagementService) GetAllUsers

func (s *UserManagementService) GetAllUsers(ctx context.Context, status string, limit int, offset int) ([]*User, error)

GetAllUsers retrieves all users with optional status filtering and pagination

func (*UserManagementService) GetPendingUsers

func (s *UserManagementService) GetPendingUsers(ctx context.Context, limit int, offset int) ([]*User, error)

GetPendingUsers retrieves users with pending status with pagination Default limit: 100, max limit: 1000

func (*UserManagementService) GetUserStatus

func (s *UserManagementService) GetUserStatus(ctx context.Context, userID int) (string, error)

GetUserStatus retrieves the current status of a user

func (*UserManagementService) IsEmailBlocked

func (s *UserManagementService) IsEmailBlocked(ctx context.Context, email string) (bool, error)

IsEmailBlocked checks if an email address is blocked

func (*UserManagementService) MarkUserAsSpam

func (s *UserManagementService) MarkUserAsSpam(ctx context.Context, userID int) error

MarkUserAsSpam deletes a user and blocks their email address

func (*UserManagementService) RejectUser

func (s *UserManagementService) RejectUser(ctx context.Context, userID int) error

RejectUser deletes a user account

func (*UserManagementService) SoftDeleteUser

func (s *UserManagementService) SoftDeleteUser(ctx context.Context, userID int) error

SoftDeleteUser soft deletes a user account Only users with 'verified' or 'suspended' status can be soft deleted

func (*UserManagementService) SuspendUser

func (s *UserManagementService) SuspendUser(ctx context.Context, userID int) error

SuspendUser suspends a user account Only users with 'verified' status can be suspended

func (*UserManagementService) UnsuspendUser

func (s *UserManagementService) UnsuspendUser(ctx context.Context, userID int) error

UnsuspendUser unsuspends a user account Only users with 'suspended' status can be unsuspended; status is set to 'verified'

func (*UserManagementService) UpdateUserProfile

func (s *UserManagementService) UpdateUserProfile(
	ctx context.Context,
	userID int,
	name string,
	email string,
	role string,
	customFields map[string]any,
) (*User, error)

UpdateUserProfile updates a user's profile fields (name, email, role, custom fields). All fields are optional — only non-empty fields are updated.

type UserMediaItem

type UserMediaItem struct {
	ID               int       `json:"id"`
	Filename         string    `json:"filename"`
	OriginalFilename string    `json:"originalFilename"`
	FilePath         string    `json:"filePath"`
	FileSize         int       `json:"fileSize"`
	MimeType         string    `json:"mimeType"`
	CreatedAt        time.Time `json:"createdAt"`
}

UserMediaItem represents a media file uploaded by a user

type UserRepo

type UserRepo interface {
	GetPendingUsers(ctx context.Context, limit int, offset int) ([]*User, error)
	UpdateUserStatus(ctx context.Context, userID int, status string) error
	UpdateUserStatusIfCurrentStatus(ctx context.Context, userID int, currentStatus string, newStatus string) error
	DeleteUser(ctx context.Context, userID int) error
	GetUserByID(ctx context.Context, userID int) (*User, error)
	SuspendUser(ctx context.Context, userID int) error
	UnsuspendUser(ctx context.Context, userID int) error
	SoftDeleteUser(ctx context.Context, userID int) error
	GetAllUsers(ctx context.Context, status string, limit int, offset int) ([]*User, error)
	CountUsers(ctx context.Context, status string) (int, error)
	GetUserStatus(ctx context.Context, userID int) (string, error)
	UpdateProfile(ctx context.Context, userID int, name string, email string, role string, customFields map[string]any) error
	SetEmailVerified(ctx context.Context, userID int, emailVerified bool) error
	CheckEmailExistsForOtherUser(ctx context.Context, userID int, email string) (bool, error)
}

UserRepo defines the interface for user repository operations

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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