user

package
v0.0.0-...-9e5e0b2 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2026 License: MIT Imports: 17 Imported by: 0 modules, 0 packages

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

Documentation

Overview

Package user provides user management functionality.

Index

Constants

View Source
const PreviewUserID = "preview-user"

PreviewUserID is the special user ID for preview mode.

Variables

View Source
var (
	// ErrResetTokenNotFound is returned when a reset token is not found.
	ErrResetTokenNotFound = errors.New("reset token not found")
	// ErrResetTokenExpired is returned when a reset token has expired.
	ErrResetTokenExpired = errors.New("reset token expired")
	// ErrResetTokenUsed is returned when a reset token has already been used.
	ErrResetTokenUsed = errors.New("reset token already used")
	// ErrTooManyResetRequests is returned when too many reset requests have been made.
	ErrTooManyResetRequests = errors.New("too many reset requests")
)
View Source
var (
	// ErrUserNotFound is returned when a user is not found.
	ErrUserNotFound = errors.New("user not found")
	// ErrUserExists is returned when a user already exists.
	ErrUserExists = errors.New("user already exists")
	// ErrUsernameExists is returned when username is taken.
	ErrUsernameExists = errors.New("username already exists")
	// ErrEmailExists is returned when email is taken.
	ErrEmailExists = errors.New("email already exists")
	// ErrSessionNotFound is returned when a session is not found.
	ErrSessionNotFound = errors.New("session not found")
	// ErrSessionExpired is returned when a session has expired.
	ErrSessionExpired = errors.New("session expired")
	// ErrSessionRevoked is returned when a session has been revoked.
	ErrSessionRevoked = errors.New("session revoked")
)
View Source
var (
	// ErrInvalidCredentials is returned when login credentials are invalid.
	ErrInvalidCredentials = errors.New("invalid credentials")
	// ErrAccountLocked is returned when the account is locked.
	ErrAccountLocked = errors.New("account is locked")
	// ErrAccountDisabled is returned when the account is disabled.
	ErrAccountDisabled = errors.New("account is disabled")
	// ErrMFARequired is returned when MFA verification is required.
	ErrMFARequired = errors.New("MFA verification required")
	// ErrInvalidPassword is returned when password doesn't meet policy.
	ErrInvalidPassword = errors.New("password does not meet requirements")
)

Functions

This section is empty.

Types

type ChangePasswordRequest

type ChangePasswordRequest struct {
	CurrentPassword string `json:"current_password" validate:"required"`
	NewPassword     string `json:"new_password" validate:"required"`
}

ChangePasswordRequest represents a request to change password.

type CreateUserRequest

type CreateUserRequest struct {
	Username    string   `json:"username" validate:"required,min=3,max=50"`
	Email       *string  `json:"email,omitempty" validate:"omitempty,email"`
	Password    string   `json:"password" validate:"required"`
	Role        Role     `json:"role,omitempty"`
	Permissions []string `json:"permissions,omitempty"`
}

CreateUserRequest represents a request to create a user.

type Handler

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

Handler handles HTTP requests for user management.

func NewHandler

func NewHandler(service *Service) *Handler

NewHandler creates a new user handler.

func (*Handler) ChangePassword

func (h *Handler) ChangePassword(c echo.Context) error

ChangePassword handles password change.

func (*Handler) CreateUser

func (h *Handler) CreateUser(c echo.Context) error

CreateUser handles user creation.

func (*Handler) DeleteUser

func (h *Handler) DeleteUser(c echo.Context) error

DeleteUser handles deleting a user.

func (*Handler) GetCurrentUser

func (h *Handler) GetCurrentUser(c echo.Context) error

GetCurrentUser handles getting the current user.

func (*Handler) GetPasswordPolicy

func (h *Handler) GetPasswordPolicy(c echo.Context) error

GetPasswordPolicy returns the password policy configuration. GET /api/v1/auth/password-policy

func (*Handler) GetUser

func (h *Handler) GetUser(c echo.Context) error

GetUser handles getting a user by ID.

func (*Handler) ListUsers

func (h *Handler) ListUsers(c echo.Context) error

ListUsers handles listing users.

func (*Handler) LockUser

func (h *Handler) LockUser(c echo.Context) error

LockUser handles locking a user.

func (*Handler) Login

func (h *Handler) Login(c echo.Context) error

Login handles user login.

func (*Handler) Logout

func (h *Handler) Logout(c echo.Context) error

Logout handles user logout.

func (*Handler) RefreshToken

func (h *Handler) RefreshToken(c echo.Context) error

RefreshToken handles token refresh.

func (*Handler) RegisterRoutes

func (h *Handler) RegisterRoutes(g *echo.Group)

RegisterRoutes registers the user routes.

func (*Handler) ResetPassword

func (h *Handler) ResetPassword(c echo.Context) error

ResetPassword handles admin resetting a user's password.

func (*Handler) SetJWTService

func (h *Handler) SetJWTService(jwtService *auth.JWTService)

SetJWTService sets the JWT service for token generation.

func (*Handler) SetModeService

func (h *Handler) SetModeService(modeService interface {
	IsPreviewMode(context.Context) (bool, error)
})

SetModeService sets the mode service for preview mode detection.

func (*Handler) SetPermissionService

func (h *Handler) SetPermissionService(permissionService PermissionService)

SetPermissionService sets the permission service.

func (*Handler) UnlockUser

func (h *Handler) UnlockUser(c echo.Context) error

UnlockUser handles unlocking a user.

func (*Handler) UpdateCurrentUser

func (h *Handler) UpdateCurrentUser(c echo.Context) error

UpdateCurrentUser handles updating the current user.

func (*Handler) UpdateUser

func (h *Handler) UpdateUser(c echo.Context) error

UpdateUser handles updating a user.

type InMemoryPasswordResetStore

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

InMemoryPasswordResetStore is an in-memory implementation of PasswordResetStore.

func NewInMemoryPasswordResetStore

func NewInMemoryPasswordResetStore() *InMemoryPasswordResetStore

NewInMemoryPasswordResetStore creates a new in-memory store.

func (*InMemoryPasswordResetStore) CountRecentByUser

func (s *InMemoryPasswordResetStore) CountRecentByUser(ctx context.Context, userID uuid.UUID, since time.Time) (int, error)

CountRecentByUser counts recent tokens for a user.

func (*InMemoryPasswordResetStore) Create

Create creates a new reset token.

func (*InMemoryPasswordResetStore) DeleteExpired

func (s *InMemoryPasswordResetStore) DeleteExpired(ctx context.Context) error

DeleteExpired removes expired tokens.

func (*InMemoryPasswordResetStore) GetByToken

GetByToken retrieves a reset token by token string.

func (*InMemoryPasswordResetStore) MarkUsed

MarkUsed marks a token as used.

type ListUsersQuery

type ListUsersQuery struct {
	Page     int     `query:"page"`
	PageSize int     `query:"page_size"`
	Search   string  `query:"search"`
	Role     *Role   `query:"role"`
	Status   *Status `query:"status"`
	SortBy   string  `query:"sort_by"`
	SortDir  string  `query:"sort_dir"`
}

ListUsersQuery represents query parameters for listing users.

type ListUsersResponse

type ListUsersResponse struct {
	Users      []*User `json:"users"`
	Total      int64   `json:"total"`
	Page       int     `json:"page"`
	PageSize   int     `json:"page_size"`
	TotalPages int     `json:"total_pages"`
}

ListUsersResponse represents a paginated list of users.

type LoginRequest

type LoginRequest struct {
	Username string `json:"username" validate:"required"`
	Password string `json:"password" validate:"required"`
}

LoginRequest represents a login request.

type LoginResponse

type LoginResponse struct {
	Token        string `json:"token"`
	RefreshToken string `json:"refresh_token"`
	TokenType    string `json:"token_type"`
	ExpiresIn    int    `json:"expires_in"`
	ExpiresAt    string `json:"expires_at,omitempty"`
	User         *User  `json:"user"`
	MFARequired  bool   `json:"mfa_required,omitempty"`
	MFAToken     string `json:"mfa_token,omitempty"`
}

LoginResponse represents a login response.

type PasswordHistory

type PasswordHistory struct {
	ID           uuid.UUID `db:"id"`
	UserID       uuid.UUID `db:"user_id"`
	PasswordHash string    `db:"password_hash"`
	CreatedAt    time.Time `db:"created_at"`
}

PasswordHistory stores previous password hashes for history checking.

type PasswordResetConfig

type PasswordResetConfig struct {
	// TokenTTL is how long reset tokens are valid.
	TokenTTL time.Duration
	// MaxRequestsPerHour limits reset requests per user per hour.
	MaxRequestsPerHour int
	// TokenLength is the length of the reset token in bytes.
	TokenLength int
}

PasswordResetConfig holds configuration for password reset.

func DefaultPasswordResetConfig

func DefaultPasswordResetConfig() *PasswordResetConfig

DefaultPasswordResetConfig returns the default configuration.

type PasswordResetConfirmRequest

type PasswordResetConfirmRequest struct {
	Token       string `json:"token" validate:"required"`
	NewPassword string `json:"new_password" validate:"required"`
}

PasswordResetConfirmRequest represents a request to confirm password reset.

type PasswordResetRequest

type PasswordResetRequest struct {
	Email string `json:"email" validate:"required,email"`
}

PasswordResetRequest represents a request to initiate password reset.

type PasswordResetResponse

type PasswordResetResponse struct {
	Message string `json:"message"`
}

PasswordResetResponse represents the response for password reset initiation.

type PasswordResetService

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

PasswordResetService handles password reset operations.

func NewPasswordResetService

func NewPasswordResetService(store PasswordResetStore, config *PasswordResetConfig) *PasswordResetService

NewPasswordResetService creates a new password reset service.

func (*PasswordResetService) Cleanup

func (s *PasswordResetService) Cleanup(ctx context.Context) error

Cleanup removes expired tokens.

func (*PasswordResetService) ConsumeToken

func (s *PasswordResetService) ConsumeToken(ctx context.Context, tokenStr string) error

ConsumeToken marks a token as used.

func (*PasswordResetService) RequestReset

func (s *PasswordResetService) RequestReset(ctx context.Context, userID uuid.UUID) (*PasswordResetToken, error)

RequestReset creates a new password reset token for a user.

func (*PasswordResetService) ValidateToken

func (s *PasswordResetService) ValidateToken(ctx context.Context, tokenStr string) (uuid.UUID, error)

ValidateToken validates a reset token and returns the associated user ID.

type PasswordResetStore

type PasswordResetStore interface {
	// Create creates a new reset token.
	Create(ctx context.Context, token *PasswordResetToken) error
	// GetByToken retrieves a reset token by token string.
	GetByToken(ctx context.Context, token string) (*PasswordResetToken, error)
	// MarkUsed marks a token as used.
	MarkUsed(ctx context.Context, id uuid.UUID) error
	// CountRecentByUser counts recent tokens for a user.
	CountRecentByUser(ctx context.Context, userID uuid.UUID, since time.Time) (int, error)
	// DeleteExpired removes expired tokens.
	DeleteExpired(ctx context.Context) error
}

PasswordResetStore defines the interface for storing reset tokens.

type PasswordResetToken

type PasswordResetToken struct {
	ID        uuid.UUID  `json:"id" db:"id"`
	UserID    uuid.UUID  `json:"user_id" db:"user_id"`
	Token     string     `json:"-" db:"token"`
	ExpiresAt time.Time  `json:"expires_at" db:"expires_at"`
	UsedAt    *time.Time `json:"-" db:"used_at"`
	CreatedAt time.Time  `json:"created_at" db:"created_at"`
}

PasswordResetToken represents a password reset token.

func (*PasswordResetToken) IsValid

func (t *PasswordResetToken) IsValid() bool

IsValid returns true if the token is not expired and not used.

type PermissionService

type PermissionService interface {
	GetEffectivePermissions(ctx context.Context, userID uuid.UUID) ([]string, error)
	SetUserPermissions(ctx context.Context, userID uuid.UUID, permissions []string, grantedBy *string) error
	InitializeUserPermissions(ctx context.Context, userID uuid.UUID, role string, grantedBy *string) error
	DeleteUserPermissions(ctx context.Context, userID uuid.UUID) error
}

PermissionService interface for permission operations

type Repository

type Repository interface {
	// Create creates a new user.
	Create(ctx context.Context, user *User) error
	// GetByID retrieves a user by ID.
	GetByID(ctx context.Context, id uuid.UUID) (*User, error)
	// GetByUsername retrieves a user by username.
	GetByUsername(ctx context.Context, username string) (*User, error)
	// GetByEmail retrieves a user by email.
	GetByEmail(ctx context.Context, email string) (*User, error)
	// Update updates a user.
	Update(ctx context.Context, user *User) error
	// Delete soft-deletes a user.
	Delete(ctx context.Context, id uuid.UUID) error
	// List retrieves users with pagination and filtering.
	List(ctx context.Context, query *ListUsersQuery) (*ListUsersResponse, error)
	// ExistsByUsername checks if a username exists.
	ExistsByUsername(ctx context.Context, username string) (bool, error)
	// ExistsByEmail checks if an email exists.
	ExistsByEmail(ctx context.Context, email string) (bool, error)
	// AnyUserExists checks if any non-deleted user exists.
	AnyUserExists(ctx context.Context) (bool, error)
	// AdminExists checks if any admin user exists.
	AdminExists(ctx context.Context) (bool, error)

	// Password history
	// AddPasswordHistory adds a password hash to history.
	AddPasswordHistory(ctx context.Context, userID uuid.UUID, passwordHash string) error
	// GetPasswordHistory retrieves password history for a user.
	GetPasswordHistory(ctx context.Context, userID uuid.UUID, limit int) ([]string, error)

	// Sessions
	// CreateSession creates a new session.
	CreateSession(ctx context.Context, session *Session) error
	// GetSessionByID retrieves a session by ID.
	GetSessionByID(ctx context.Context, id uuid.UUID) (*Session, error)
	// GetSessionByRefreshToken retrieves a session by refresh token.
	GetSessionByRefreshToken(ctx context.Context, token string) (*Session, error)
	// GetUserSessions retrieves all sessions for a user.
	GetUserSessions(ctx context.Context, userID uuid.UUID) ([]*Session, error)
	// RevokeSession revokes a session.
	RevokeSession(ctx context.Context, id uuid.UUID) error
	// RevokeUserSessions revokes all sessions for a user.
	RevokeUserSessions(ctx context.Context, userID uuid.UUID) error
	// CleanupExpiredSessions removes expired sessions.
	CleanupExpiredSessions(ctx context.Context) error
}

Repository defines the interface for user data access.

type ResetPasswordRequest

type ResetPasswordRequest struct {
	NewPassword string `json:"new_password" validate:"required"`
}

ResetPasswordRequest represents a request to reset a user's password.

type Role

type Role string

Role represents the user role.

const (
	// RoleAdmin has full access.
	RoleAdmin Role = "admin"
	// RoleUser has standard access.
	RoleUser Role = "user"
	// RoleGuest has limited access.
	RoleGuest Role = "guest"
)

type SQLiteRepository

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

SQLiteRepository implements Repository using SQLite.

func NewSQLiteRepository

func NewSQLiteRepository(db *sql.DB) (*SQLiteRepository, error)

NewSQLiteRepository creates a new SQLiteRepository.

func NewSQLiteRepositoryWithReadDB

func NewSQLiteRepositoryWithReadDB(writeDB, readDB *sql.DB) (*SQLiteRepository, error)

NewSQLiteRepositoryWithReadDB creates a new SQLiteRepository with separate write and read database handles.

func (*SQLiteRepository) AddPasswordHistory

func (r *SQLiteRepository) AddPasswordHistory(ctx context.Context, userID uuid.UUID, passwordHash string) error

AddPasswordHistory adds a password hash to history.

func (*SQLiteRepository) AdminExists

func (r *SQLiteRepository) AdminExists(ctx context.Context) (bool, error)

AdminExists checks if any admin user exists.

func (*SQLiteRepository) AnyUserExists

func (r *SQLiteRepository) AnyUserExists(ctx context.Context) (bool, error)

AnyUserExists checks if any non-deleted user exists.

func (*SQLiteRepository) CleanupExpiredSessions

func (r *SQLiteRepository) CleanupExpiredSessions(ctx context.Context) error

CleanupExpiredSessions removes expired sessions.

func (*SQLiteRepository) Create

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

Create creates a new user.

func (*SQLiteRepository) CreateSession

func (r *SQLiteRepository) CreateSession(ctx context.Context, session *Session) error

CreateSession creates a new session.

func (*SQLiteRepository) Delete

func (r *SQLiteRepository) Delete(ctx context.Context, id uuid.UUID) error

Delete soft-deletes a user.

func (*SQLiteRepository) ExistsByEmail

func (r *SQLiteRepository) ExistsByEmail(ctx context.Context, email string) (bool, error)

ExistsByEmail checks if an email exists.

func (*SQLiteRepository) ExistsByUsername

func (r *SQLiteRepository) ExistsByUsername(ctx context.Context, username string) (bool, error)

ExistsByUsername checks if a username exists.

func (*SQLiteRepository) GetByEmail

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

GetByEmail retrieves a user by email.

func (*SQLiteRepository) GetByID

func (r *SQLiteRepository) GetByID(ctx context.Context, id uuid.UUID) (*User, error)

GetByID retrieves a user by ID.

func (*SQLiteRepository) GetByUsername

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

GetByUsername retrieves a user by username.

func (*SQLiteRepository) GetPasswordHistory

func (r *SQLiteRepository) GetPasswordHistory(ctx context.Context, userID uuid.UUID, limit int) ([]string, error)

GetPasswordHistory retrieves password history for a user.

func (*SQLiteRepository) GetSessionByID

func (r *SQLiteRepository) GetSessionByID(ctx context.Context, id uuid.UUID) (*Session, error)

GetSessionByID retrieves a session by ID.

func (*SQLiteRepository) GetSessionByRefreshToken

func (r *SQLiteRepository) GetSessionByRefreshToken(ctx context.Context, token string) (*Session, error)

GetSessionByRefreshToken retrieves a session by refresh token.

func (*SQLiteRepository) GetUserSessions

func (r *SQLiteRepository) GetUserSessions(ctx context.Context, userID uuid.UUID) ([]*Session, error)

GetUserSessions retrieves all sessions for a user.

func (*SQLiteRepository) List

List retrieves users with pagination and filtering.

func (*SQLiteRepository) RevokeSession

func (r *SQLiteRepository) RevokeSession(ctx context.Context, id uuid.UUID) error

RevokeSession revokes a session.

func (*SQLiteRepository) RevokeUserSessions

func (r *SQLiteRepository) RevokeUserSessions(ctx context.Context, userID uuid.UUID) error

RevokeUserSessions revokes all sessions for a user.

func (*SQLiteRepository) Update

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

Update updates a user.

type Service

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

Service provides user management operations.

func NewService

func NewService(repo Repository, hasher *password.Hasher, policy *password.Policy, config *ServiceConfig) *Service

NewService creates a new user service.

func (*Service) AdminExists

func (s *Service) AdminExists(ctx context.Context) (bool, error)

AdminExists checks if any admin user exists.

func (*Service) AnyUserExists

func (s *Service) AnyUserExists(ctx context.Context) (bool, error)

AnyUserExists checks if any user exists.

func (*Service) Authenticate

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

Authenticate authenticates a user with username and password. Returns the user if successful, or an error. If MFA is enabled, returns ErrMFARequired.

func (*Service) ChangePassword

func (s *Service) ChangePassword(ctx context.Context, id uuid.UUID, currentPassword, newPassword string) error

ChangePassword changes a user's password.

func (*Service) Create

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

Create creates a new user.

func (*Service) CreateSession

func (s *Service) CreateSession(ctx context.Context, userID uuid.UUID, refreshToken, userAgent, ipAddress string) (*Session, error)

CreateSession creates a new session for a user.

func (*Service) Delete

func (s *Service) Delete(ctx context.Context, id uuid.UUID) error

Delete soft-deletes a user.

func (*Service) ExistsByUsername

func (s *Service) ExistsByUsername(ctx context.Context, username string) (bool, error)

ExistsByUsername checks if a username exists.

func (*Service) GetByEmail

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

GetByEmail retrieves a user by email.

func (*Service) GetByID

func (s *Service) GetByID(ctx context.Context, id uuid.UUID) (*User, error)

GetByID retrieves a user by ID.

func (*Service) GetByUsername

func (s *Service) GetByUsername(ctx context.Context, username string) (*User, error)

GetByUsername retrieves a user by username.

func (*Service) GetPasswordPolicy

func (s *Service) GetPasswordPolicy() *password.PolicyConfig

GetPasswordPolicy returns the password policy configuration.

func (*Service) GetSession

func (s *Service) GetSession(ctx context.Context, refreshToken string) (*Session, error)

GetSession retrieves a session by refresh token.

func (*Service) GetUserSessions

func (s *Service) GetUserSessions(ctx context.Context, userID uuid.UUID) ([]*Session, error)

GetUserSessions retrieves all active sessions for a user.

func (*Service) List

func (s *Service) List(ctx context.Context, query *ListUsersQuery) (*ListUsersResponse, error)

List retrieves users with pagination and filtering.

func (*Service) Lock

func (s *Service) Lock(ctx context.Context, id uuid.UUID) error

Lock locks a user account.

func (*Service) ResetPassword

func (s *Service) ResetPassword(ctx context.Context, id uuid.UUID, newPassword string) error

ResetPassword resets a user's password (admin action, no current password required).

func (*Service) RevokeAllSessions

func (s *Service) RevokeAllSessions(ctx context.Context, userID uuid.UUID) error

RevokeAllSessions revokes all sessions for a user.

func (*Service) RevokeSession

func (s *Service) RevokeSession(ctx context.Context, sessionID uuid.UUID) error

RevokeSession revokes a session.

func (*Service) Unlock

func (s *Service) Unlock(ctx context.Context, id uuid.UUID) error

Unlock unlocks a user account.

func (*Service) Update

func (s *Service) Update(ctx context.Context, id uuid.UUID, req *UpdateUserRequest) (*User, error)

Update updates a user.

type ServiceConfig

type ServiceConfig struct {
	// LockoutThreshold is the number of failed attempts before lockout.
	LockoutThreshold int
	// LockoutDuration is how long the account is locked.
	LockoutDuration time.Duration
	// PasswordHistoryCount is the number of passwords to check for reuse.
	PasswordHistoryCount int
	// SessionDuration is how long sessions are valid.
	SessionDuration time.Duration
}

ServiceConfig holds configuration for the user service.

func DefaultServiceConfig

func DefaultServiceConfig() *ServiceConfig

DefaultServiceConfig returns the default service configuration.

type Session

type Session struct {
	ID           uuid.UUID  `json:"id" db:"id"`
	UserID       uuid.UUID  `json:"user_id" db:"user_id"`
	RefreshToken string     `json:"-" db:"refresh_token"`
	UserAgent    string     `json:"user_agent" db:"user_agent"`
	IPAddress    string     `json:"ip_address" db:"ip_address"`
	ExpiresAt    time.Time  `json:"expires_at" db:"expires_at"`
	CreatedAt    time.Time  `json:"created_at" db:"created_at"`
	RevokedAt    *time.Time `json:"-" db:"revoked_at"`
}

Session represents a user session.

func NewSession

func NewSession(userID uuid.UUID, refreshToken, userAgent, ipAddress string, expiresAt time.Time) *Session

NewSession creates a new Session.

func (*Session) IsValid

func (s *Session) IsValid() bool

IsValid returns true if the session is not expired and not revoked.

type Status

type Status string

Status represents the account status.

const (
	// StatusActive indicates an active account.
	StatusActive Status = "active"
	// StatusLocked indicates a locked account (due to failed login attempts).
	StatusLocked Status = "locked"
	// StatusDisabled indicates a disabled account (by admin).
	StatusDisabled Status = "disabled"
)

type UpdateUserRequest

type UpdateUserRequest struct {
	Email       *string  `json:"email,omitempty" validate:"omitempty,email"`
	Role        *Role    `json:"role,omitempty"`
	Status      *Status  `json:"status,omitempty"`
	Permissions []string `json:"permissions,omitempty"`
}

UpdateUserRequest represents a request to update a user.

type User

type User struct {
	// ID is the unique identifier.
	ID uuid.UUID `json:"id" db:"id"`
	// Username is the unique username.
	Username string `json:"username" db:"username"`
	// Email is the optional email address.
	Email *string `json:"email,omitempty" db:"email"`
	// PasswordHash is the Argon2id hashed password.
	PasswordHash string `json:"-" db:"password_hash"`
	// MFASecret is the encrypted TOTP secret.
	MFASecret *string `json:"-" db:"mfa_secret"`
	// MFAEnabled indicates if MFA is enabled.
	MFAEnabled bool `json:"mfa_enabled" db:"mfa_enabled"`
	// Role is the user's role.
	Role Role `json:"role" db:"role"`
	// Status is the account status.
	Status Status `json:"status" db:"status"`
	// FailedLoginAttempts tracks consecutive failed logins.
	FailedLoginAttempts int `json:"-" db:"failed_login_attempts"`
	// LockedUntil is when the account lockout expires.
	LockedUntil *time.Time `json:"-" db:"locked_until"`
	// LastLoginAt is the last successful login time.
	LastLoginAt *time.Time `json:"last_login_at,omitempty" db:"last_login_at"`
	// CreatedAt is when the user was created.
	CreatedAt time.Time `json:"created_at" db:"created_at"`
	// UpdatedAt is when the user was last updated.
	UpdatedAt time.Time `json:"updated_at" db:"updated_at"`
	// DeletedAt is when the user was soft-deleted.
	DeletedAt *time.Time `json:"-" db:"deleted_at"`
}

User represents a user in the system.

func NewUser

func NewUser(username, passwordHash string) *User

NewUser creates a new User with default values.

func (*User) IsActive

func (u *User) IsActive() bool

IsActive returns true if the user account is active and not locked.

func (*User) IsLocked

func (u *User) IsLocked() bool

IsLocked returns true if the account is currently locked.

Jump to

Keyboard shortcuts

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