user

package
v0.0.0-...-0299622 Latest Latest
Warning

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

Go to latest
Published: Feb 12, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

Package user provides user management functionality for the netproxy framework.

Package user provides SQLite-based user storage implementation.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrUserNotFound    = errors.New("user not found")
	ErrUserExists      = errors.New("user already exists")
	ErrInvalidPassword = errors.New("invalid password")
	ErrQuotaExceeded   = errors.New("traffic quota exceeded")
	ErrUserExpired     = errors.New("user account expired")
	ErrUserDisabled    = errors.New("user account disabled")
)

Common errors

Functions

This section is empty.

Types

type CreateUserRequest

type CreateUserRequest struct {
	Username       string            `json:"username"`
	Password       string            `json:"password"`
	Email          string            `json:"email,omitempty"`
	Level          Level             `json:"level,omitempty"`
	Quota          int64             `json:"quota,omitempty"`
	ExpireDays     int               `json:"expire_days,omitempty"`
	MaxConnections int               `json:"max_connections,omitempty"`
	SpeedLimit     int64             `json:"speed_limit,omitempty"`
	Metadata       map[string]string `json:"metadata,omitempty"`
}

CreateUserRequest is the request body for creating a user.

type Level

type Level int

Level represents user privilege level.

const (
	// LevelFree is the free tier with limited features.
	LevelFree Level = 0
	// LevelBasic is the basic tier.
	LevelBasic Level = 1
	// LevelPremium is the premium tier with all features.
	LevelPremium Level = 2
	// LevelAdmin is the administrator level.
	LevelAdmin Level = 99
)

type ListOptions

type ListOptions struct {
	Offset        int
	Limit         int
	SortBy        string
	SortOrder     string // "asc" or "desc"
	FilterLevel   *Level
	FilterEnabled *bool
}

ListOptions holds options for listing users.

func DefaultListOptions

func DefaultListOptions() *ListOptions

DefaultListOptions returns default list options.

type MemoryStore

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

MemoryStore implements Store using in-memory storage. This is suitable for development and testing, or small deployments.

func NewMemoryStore

func NewMemoryStore() *MemoryStore

NewMemoryStore creates a new in-memory user store.

func (*MemoryStore) Close

func (s *MemoryStore) Close() error

Close closes the store.

func (*MemoryStore) Count

func (s *MemoryStore) Count(ctx context.Context) (int, error)

Count returns the total number of users.

func (*MemoryStore) Create

func (s *MemoryStore) Create(ctx context.Context, user *User) error

Create creates a new user.

func (*MemoryStore) Delete

func (s *MemoryStore) Delete(ctx context.Context, id string) error

Delete deletes a user by ID.

func (*MemoryStore) Get

func (s *MemoryStore) Get(ctx context.Context, id string) (*User, error)

Get retrieves a user by ID.

func (*MemoryStore) GetActiveUsers

func (s *MemoryStore) GetActiveUsers(ctx context.Context) ([]*User, error)

GetActiveUsers returns all active users.

func (*MemoryStore) GetByUUID

func (s *MemoryStore) GetByUUID(ctx context.Context, uuid string) (*User, error)

GetByUUID retrieves a user by UUID.

func (*MemoryStore) GetByUsername

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

GetByUsername retrieves a user by username.

func (*MemoryStore) List

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

List returns all users with optional pagination.

func (*MemoryStore) ResetAllTraffic

func (s *MemoryStore) ResetAllTraffic(ctx context.Context) error

ResetAllTraffic resets all users' traffic counters.

func (*MemoryStore) ResetTraffic

func (s *MemoryStore) ResetTraffic(ctx context.Context, id string) error

ResetTraffic resets a user's traffic counters.

func (*MemoryStore) Search

func (s *MemoryStore) Search(ctx context.Context, query string, offset, limit int) ([]*User, int, error)

Search searches users by username or email.

func (*MemoryStore) Update

func (s *MemoryStore) Update(ctx context.Context, user *User) error

Update updates an existing user.

func (*MemoryStore) UpdateTraffic

func (s *MemoryStore) UpdateTraffic(ctx context.Context, id string, upload, download int64) error

UpdateTraffic updates a user's traffic counters.

type SQLiteStore

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

SQLiteStore implements Store using SQLite database.

func NewSQLiteStore

func NewSQLiteStore(dbPath string) (*SQLiteStore, error)

NewSQLiteStore creates a new SQLite-based user store.

func (*SQLiteStore) Close

func (s *SQLiteStore) Close() error

Close closes the database connection.

func (*SQLiteStore) Count

func (s *SQLiteStore) Count(ctx context.Context) (int, error)

Count returns the total number of users.

func (*SQLiteStore) Create

func (s *SQLiteStore) Create(ctx context.Context, user *User) error

Create creates a new user.

func (*SQLiteStore) Delete

func (s *SQLiteStore) Delete(ctx context.Context, id string) error

Delete deletes a user by ID.

func (*SQLiteStore) Get

func (s *SQLiteStore) Get(ctx context.Context, id string) (*User, error)

Get retrieves a user by ID.

func (*SQLiteStore) GetActiveUsers

func (s *SQLiteStore) GetActiveUsers(ctx context.Context) ([]*User, error)

GetActiveUsers returns users who are enabled and not expired.

func (*SQLiteStore) GetByUUID

func (s *SQLiteStore) GetByUUID(ctx context.Context, uuid string) (*User, error)

GetByUUID retrieves a user by UUID.

func (*SQLiteStore) GetByUsername

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

GetByUsername retrieves a user by username.

func (*SQLiteStore) GetTrafficLogs

func (s *SQLiteStore) GetTrafficLogs(ctx context.Context, userID string, start, end time.Time) ([]TrafficLog, error)

GetTrafficLogs retrieves traffic logs for a user within a time range.

func (*SQLiteStore) List

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

List returns all users with pagination.

func (*SQLiteStore) ResetAllTraffic

func (s *SQLiteStore) ResetAllTraffic(ctx context.Context) error

ResetAllTraffic resets all users' traffic counters.

func (*SQLiteStore) ResetTraffic

func (s *SQLiteStore) ResetTraffic(ctx context.Context, id string) error

ResetTraffic resets a user's traffic counters.

func (*SQLiteStore) Search

func (s *SQLiteStore) Search(ctx context.Context, query string, offset, limit int) ([]*User, int, error)

Search searches users by username or email.

func (*SQLiteStore) Update

func (s *SQLiteStore) Update(ctx context.Context, user *User) error

Update updates an existing user.

func (*SQLiteStore) UpdateTraffic

func (s *SQLiteStore) UpdateTraffic(ctx context.Context, id string, upload, download int64) error

UpdateTraffic updates a user's traffic counters.

type Store

type Store interface {
	// Create creates a new user.
	Create(ctx context.Context, user *User) error

	// Get retrieves a user by ID.
	Get(ctx context.Context, id string) (*User, error)

	// GetByUsername retrieves a user by username.
	GetByUsername(ctx context.Context, username string) (*User, error)

	// GetByUUID retrieves a user by UUID.
	GetByUUID(ctx context.Context, uuid string) (*User, error)

	// Update updates an existing user.
	Update(ctx context.Context, user *User) error

	// Delete deletes a user by ID.
	Delete(ctx context.Context, id string) error

	// List returns all users with optional pagination.
	List(ctx context.Context, offset, limit int) ([]*User, int, error)

	// Count returns the total number of users.
	Count(ctx context.Context) (int, error)

	// Search searches users by username or email.
	Search(ctx context.Context, query string, offset, limit int) ([]*User, int, error)

	// UpdateTraffic updates a user's traffic counters.
	UpdateTraffic(ctx context.Context, id string, upload, download int64) error

	// ResetTraffic resets a user's traffic counters.
	ResetTraffic(ctx context.Context, id string) error

	// ResetAllTraffic resets all users' traffic counters.
	ResetAllTraffic(ctx context.Context) error

	// GetActiveUsers returns all active users.
	GetActiveUsers(ctx context.Context) ([]*User, error)

	// Close closes the store.
	Close() error
}

Store defines the interface for user storage.

type TrafficLog

type TrafficLog struct {
	ID        int64     `json:"id"`
	UserID    string    `json:"user_id"`
	Upload    int64     `json:"upload"`
	Download  int64     `json:"download"`
	Timestamp time.Time `json:"timestamp"`
}

TrafficLog represents a traffic log entry.

type TrafficStats

type TrafficStats struct {
	UserID      string    `json:"user_id"`
	Upload      int64     `json:"upload"`
	Download    int64     `json:"download"`
	Total       int64     `json:"total"`
	Quota       int64     `json:"quota"`
	Remaining   int64     `json:"remaining"`
	LastUpdated time.Time `json:"last_updated"`
}

TrafficStats holds traffic statistics for a user.

type UpdateUserRequest

type UpdateUserRequest struct {
	Email          *string           `json:"email,omitempty"`
	Password       *string           `json:"password,omitempty"`
	Level          *Level            `json:"level,omitempty"`
	Quota          *int64            `json:"quota,omitempty"`
	Enabled        *bool             `json:"enabled,omitempty"`
	ExpireAt       *time.Time        `json:"expire_at,omitempty"`
	MaxConnections *int              `json:"max_connections,omitempty"`
	SpeedLimit     *int64            `json:"speed_limit,omitempty"`
	AllowedIPs     []string          `json:"allowed_ips,omitempty"`
	Metadata       map[string]string `json:"metadata,omitempty"`
}

UpdateUserRequest is the request body for updating a user.

func (*UpdateUserRequest) Apply

func (r *UpdateUserRequest) Apply(u *User) error

Apply applies the update request to the user.

type User

type User struct {
	// ID is the unique identifier for the user.
	ID string `json:"id"`

	// Username is the login name.
	Username string `json:"username"`

	// PasswordHash is the bcrypt hash of the password.
	PasswordHash string `json:"-"`

	// Email is the user's email address.
	Email string `json:"email,omitempty"`

	// UUID is used for VMess/VLESS authentication.
	UUID string `json:"uuid"`

	// Level is the user's privilege level.
	Level Level `json:"level"`

	// Quota is the traffic quota in bytes (0 = unlimited).
	Quota int64 `json:"quota"`

	// UsedUpload is the total uploaded bytes.
	UsedUpload int64 `json:"used_upload"`

	// UsedDownload is the total downloaded bytes.
	UsedDownload int64 `json:"used_download"`

	// ExpireAt is when the account expires (zero = never).
	ExpireAt time.Time `json:"expire_at,omitempty"`

	// Enabled indicates if the account is active.
	Enabled bool `json:"enabled"`

	// MaxConnections is the maximum concurrent connections (0 = unlimited).
	MaxConnections int `json:"max_connections"`

	// SpeedLimit is the speed limit in bytes per second (0 = unlimited).
	SpeedLimit int64 `json:"speed_limit"`

	// AllowedIPs is a list of allowed client IP addresses (empty = all).
	AllowedIPs []string `json:"allowed_ips,omitempty"`

	// Metadata holds additional user data.
	Metadata map[string]string `json:"metadata,omitempty"`

	// CreatedAt is when the account was created.
	CreatedAt time.Time `json:"created_at"`

	// UpdatedAt is when the account was last updated.
	UpdatedAt time.Time `json:"updated_at"`

	// LastLoginAt is when the user last logged in.
	LastLoginAt time.Time `json:"last_login_at,omitempty"`

	// LastLoginIP is the IP address of the last login.
	LastLoginIP string `json:"last_login_ip,omitempty"`
}

User represents a user account.

func NewUser

func NewUser(username, password string) (*User, error)

NewUser creates a new user with default values.

func (*User) AddTraffic

func (u *User) AddTraffic(upload, download int64)

AddTraffic adds traffic usage to the user.

func (*User) Clone

func (u *User) Clone() *User

Clone creates a deep copy of the user.

func (*User) GetTrafficStats

func (u *User) GetTrafficStats() *TrafficStats

GetTrafficStats returns the user's traffic statistics.

func (*User) IsActive

func (u *User) IsActive() bool

IsActive returns true if the user account is active and usable.

func (*User) IsExpired

func (u *User) IsExpired() bool

IsExpired returns true if the user account has expired.

func (*User) IsQuotaExceeded

func (u *User) IsQuotaExceeded() bool

IsQuotaExceeded returns true if the user has exceeded their traffic quota.

func (*User) RegenerateUUID

func (u *User) RegenerateUUID()

RegenerateUUID generates a new UUID for the user.

func (*User) RemainingQuota

func (u *User) RemainingQuota() int64

RemainingQuota returns the remaining traffic quota. Returns -1 if quota is unlimited.

func (*User) ResetTraffic

func (u *User) ResetTraffic()

ResetTraffic resets the user's traffic counters.

func (*User) SetPassword

func (u *User) SetPassword(password string) error

SetPassword sets a new password for the user.

func (*User) TotalTraffic

func (u *User) TotalTraffic() int64

TotalTraffic returns the total traffic used.

func (*User) VerifyPassword

func (u *User) VerifyPassword(password string) bool

VerifyPassword checks if the provided password matches the stored hash.

Jump to

Keyboard shortcuts

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