user

package
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Feb 19, 2026 License: Apache-2.0 Imports: 15 Imported by: 0

README

user

A weedbox module for user management. Provides CRUD operations, bcrypt password hashing, authentication, and paginated listing with search and filtering.

Overview

The User module manages the users table via GORM. On startup, it:

  1. Auto-migrates the users table
  2. Creates a default admin user (if enabled and not already present)

User IDs are generated using UUID v7 (time-ordered). Passwords are hashed with bcrypt.

Dependencies

Dependency Source Description
database.DatabaseConnector common-modules GORM database connection

Module Registration

user.Module("user")

Configuration

Key Type Default Description
max_page_size int 100 Maximum page size for list queries
bcrypt_cost int 12 bcrypt cost factor (valid range: 10-14)
min_password_length int 8 Minimum password length
create_default_admin bool true Whether to create a default admin user on startup
default_admin_password string "1qaz@WSX" Default admin password (override in production)

Default Admin User

When create_default_admin is true, the module creates an admin user on first startup:

Field Value
Username admin
Email admin@localhost
Password Value of default_admin_password config
Display Name System Administrator
Roles ["admin"]
Status active

The admin user is only created if no user with username admin exists.

Data Model

The User model (user/models/user.go) maps to the users table:

Field Type Constraints Description
ID varchar(36) Primary key UUID v7
Username varchar(255) Unique, not null Login username
Email varchar(255) Unique Email address
PasswordHash varchar(255) Not null bcrypt hash (never exposed)
DisplayName varchar(255) Display name
Roles text (JSON) JSON array of role keys
Status varchar(50) Default: active active, inactive, suspended
LastLoginAt timestamp Nullable Last successful login time
CreatedAt timestamp Record creation time
UpdatedAt timestamp Last update time

API Reference

UserManager Methods

CRUD:

Method Signature Description
Create (ctx, cfg *UserConfig) (*User, error) Create a user with hashed password
Get (ctx, userID string) (*User, error) Get user by ID
GetByUsername (ctx, username string) (*User, error) Get user by username
GetByEmail (ctx, email string) (*User, error) Get user by email
Update (ctx, userID string, cfg *UserConfig) (*User, error) Update user (partial update, non-empty fields only)
Delete (ctx, userID string) error Delete a user
List (ctx, req *ListUsersRequest, qh *queryhelper.QueryHelper) (*ListUsersResp, error) List with pagination/search/filter

Password:

Method Signature Description
UpdatePassword (ctx, userID string, newPassword string) error Update password (validates min length)
VerifyPassword (ctx, userID string, password string) error Verify a password against stored hash

Authentication:

Method Signature Description
Authenticate (ctx, identifier string, password string) (*User, error) Authenticate by username or email + password
Types

UserConfig — used for Create and Update:

type UserConfig struct {
    Username    string
    Email       string
    Password    string   // Plain text (will be hashed)
    DisplayName string
    Roles       []string
    Status      string
}

User — public structure (password hash is never exposed):

type User struct {
    ID          string
    Username    string
    Email       string
    DisplayName string
    Roles       []string
    Status      string
    LastLoginAt *time.Time
    CreatedAt   time.Time
    UpdatedAt   time.Time
}

ListUsersRequest — filter conditions:

type ListUsersRequest struct {
    Username *string
    Email    *string
    Role     *string
    Status   *string
}
Errors
Error Description
ErrNotFound User not found
ErrUsernameExists Username already taken
ErrEmailExists Email already taken
ErrInvalidInput Invalid input data
ErrInvalidPassword Password verification failed
ErrInvalidCredentials Authentication failed (wrong username/email or password)
ErrPasswordTooShort Password shorter than minimum length
ErrOperationFailed General operation failure
Query Settings

The List method supports pagination, search, and sorting via queryhelper:

  • Allowed order by: created_at, updated_at, username, email, last_login_at
  • Allowed search fields: username, email, display_name
  • Allowed filters: status (=, !=, IN), role (=, !=, IN), username (=, LIKE), email (=, LIKE)

Example: Programmatic User Creation

newUser, err := userManager.Create(ctx, &user.UserConfig{
    Username:    "john",
    Email:       "john@example.com",
    Password:    "secure-password",
    DisplayName: "John Doe",
    Roles:       []string{"user"},
})

Documentation

Index

Constants

View Source
const (
	DefaultAdminUsername = "admin"
	DefaultAdminEmail    = "admin@localhost"
	DefaultAdminPassword = "1qaz@WSX"
)

Default admin credentials

View Source
const ModuleName = "UserManager"

Variables

View Source
var (
	ErrNotFound           = errors.New("user not found")
	ErrUsernameExists     = errors.New("username already exists")
	ErrEmailExists        = errors.New("email already exists")
	ErrInvalidInput       = errors.New("invalid input")
	ErrInvalidPassword    = errors.New("invalid password")
	ErrInvalidCredentials = errors.New("invalid credentials")
	ErrOperationFailed    = errors.New("operation failed")
	ErrPasswordTooShort   = errors.New("password must be at least 8 characters")
)
View Source
var DefaultQuerySettings = &queryhelper.QuerySettings{
	AllowedOrderBy: []string{"created_at", "updated_at", "username", "email", "last_login_at"},
	AllowedSearch:  []string{"username", "email", "display_name"},
	AllowedFilters: map[string][]string{
		"status":   {"=", "!=", "IN"},
		"role":     {"=", "!=", "IN"},
		"username": {"=", "LIKE"},
		"email":    {"=", "LIKE"},
	},
}

QueryHelper settings

Functions

func Module

func Module(scope string) fx.Option

Types

type ListUsersRequest

type ListUsersRequest struct {
	Username *string
	Email    *string
	Role     *string // Filter by role (checks if user has this role)
	Status   *string
}

ListUsersRequest filter conditions for list query

type ListUsersResp

type ListUsersResp struct {
	Data        []*User
	QueryHelper *queryhelper.QueryHelper
}

ListUsersResp list query response

type Params

type Params struct {
	weedbox.Params
	Database database.DatabaseConnector
}

type User

type User struct {
	ID          string
	Username    string
	Email       string
	DisplayName string
	Roles       []string
	Status      string
	LastLoginAt *time.Time
	CreatedAt   time.Time
	UpdatedAt   time.Time
}

User public user structure (password hash is never exposed)

type UserConfig

type UserConfig struct {
	Username    string
	Email       string
	Password    string // Plain text password (will be hashed)
	DisplayName string
	Roles       []string // Multiple roles
	Status      string
}

UserConfig configuration for create/update

type UserManager

type UserManager struct {
	weedbox.Module[*Params]
	// contains filtered or unexported fields
}

func (*UserManager) Authenticate

func (m *UserManager) Authenticate(ctx context.Context, identifier string, password string) (*User, error)

Authenticate authenticates a user by username/email and password

func (*UserManager) Create

func (m *UserManager) Create(ctx context.Context, cfg *UserConfig) (*User, error)

Create creates a new user with hashed password

func (*UserManager) Delete

func (m *UserManager) Delete(ctx context.Context, userID string) error

Delete deletes a user

func (*UserManager) Get

func (m *UserManager) Get(ctx context.Context, userID string) (*User, error)

Get retrieves a single user by ID

func (*UserManager) GetByEmail

func (m *UserManager) GetByEmail(ctx context.Context, email string) (*User, error)

GetByEmail retrieves a user by email

func (*UserManager) GetByUsername

func (m *UserManager) GetByUsername(ctx context.Context, username string) (*User, error)

GetByUsername retrieves a user by username

func (*UserManager) InitDefaultConfigs

func (m *UserManager) InitDefaultConfigs()

func (*UserManager) List

List queries users with pagination, search, sorting, and filtering

func (*UserManager) OnStart

func (m *UserManager) OnStart(ctx context.Context) error

func (*UserManager) OnStop

func (m *UserManager) OnStop(ctx context.Context) error

func (*UserManager) Update

func (m *UserManager) Update(ctx context.Context, userID string, cfg *UserConfig) (*User, error)

Update updates a user (excluding password)

func (*UserManager) UpdatePassword

func (m *UserManager) UpdatePassword(ctx context.Context, userID string, newPassword string) error

UpdatePassword updates a user's password

func (*UserManager) VerifyPassword

func (m *UserManager) VerifyPassword(ctx context.Context, userID string, password string) error

VerifyPassword verifies if the provided password matches the user's stored password

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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