captcha

package
v0.0.3-beta.6 Latest Latest
Warning

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

Go to latest
Published: Dec 16, 2025 License: MIT Imports: 5 Imported by: 0

Documentation

Overview

Package captcha provides a complete verification code management system with rate limiting. It supports configurable code generation, delivery through pluggable senders, automatic expiration handling, and protection against abuse through minute/daily limits.

Index

Constants

View Source
const (
	// DefaultMinuteLimit defines the default maximum number of verification codes that can be sent per minute.
	DefaultMinuteLimit = 1
	// DefaultDailyLimit defines the default maximum number of verification codes that can be sent per day.
	DefaultDailyLimit = 100
	// DefaultStoreSize defines the default initial capacity for the verification storage maps.
	DefaultStoreSize = 100
)

Variables

This section is empty.

Functions

func RandomCode

func RandomCode(length int) string

RandomCode generates a random numeric verification code of the specified length. Each digit is randomly selected from 0-9. Returns an empty string if length is 0.

Types

type Config

type Config struct {
	CodeLength    int                 `json:"code_length"`     // Length of generated verification codes
	CodeExpiresIn int                 `json:"code_expires_in"` // Code expiration time in seconds
	RateLimit     *VerificationConfig `json:"rate_limit"`      // Rate limiting configuration
}

Config holds the configuration parameters for the verification code system.

type Manager

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

Manager provides verification code generation, sending, and validation capabilities. It combines code generation, delivery, and rate limiting in a single component.

func NewManager

func NewManager(config *Config, sender Sender) *Manager

NewManager creates a new verification code manager with the provided configuration and sender. It initializes the verification system with rate limiting capabilities.

func (*Manager) Identifier

func (m *Manager) Identifier() string

Identifier returns the task identifier for the captcha manager. This implements the Task interface for lifecycle management integration.

func (*Manager) SendCode

func (m *Manager) SendCode(number string) error

SendCode generates and sends a verification code to the specified number. It creates a random code, saves it with expiration, and delivers it using the configured sender. Returns an error if code generation, storage, or delivery fails.

func (*Manager) Start

func (m *Manager) Start(ctx context.Context) error

Start begins the captcha manager's background cleanup routine. It runs a ticker that periodically cleans expired verification codes to prevent memory leaks. This implements the Task interface for lifecycle management integration.

func (*Manager) Stop

func (m *Manager) Stop(ctx context.Context) error

Stop gracefully shuts down the captcha manager by closing the done channel. This signals the cleanup routine to exit and implements the Task interface.

func (*Manager) Verify

func (m *Manager) Verify(number, code string) bool

Verify validates a verification code for the given number. Returns true if the code is valid and not expired, false otherwise.

type Sender

type Sender interface {
	SendCode(number string, code string) error
}

Sender defines the interface for sending verification codes to recipients. Implementations should handle the actual delivery mechanism (SMS, email, etc.).

type VerificationCode

type VerificationCode struct {
	Code      string    `json:"code"`
	ExpiresAt time.Time `json:"expires_at"`
}

VerificationCode represents a verification code with its expiration time.

type VerificationConfig

type VerificationConfig struct {
	MinuteLimit int `json:"minute_limit"`
	DailyLimit  int `json:"daily_limit"`
}

VerificationConfig holds the rate limiting configuration for verification code generation.

type VerificationStorage

type VerificationStorage struct {
	Store map[string][]VerificationCode `json:"store"`

	MinuteCounts map[string]int `json:"minute_counts"`
	DailyCounts  map[string]int `json:"daily_counts"`

	MinuteTimestamps map[string]time.Time `json:"minute_timestamps"`
	DailyTimestamps  map[string]time.Time `json:"daily_timestamps"`
}

type VerificationSystem

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

VerificationSystem provides thread-safe verification code management with rate limiting. It handles code storage, expiration cleanup, and enforces sending limits per phone number.

func NewVerificationSystem

func NewVerificationSystem(config *VerificationConfig) *VerificationSystem

NewVerificationSystem creates a new verification system with the provided configuration. If config is nil, it uses default values for rate limiting and storage capacity.

func (*VerificationSystem) CleanExpired

func (s *VerificationSystem) CleanExpired()

CleanExpired removes all expired verification codes from storage across all numbers. This method should be called periodically to prevent memory leaks from accumulated expired codes.

func (*VerificationSystem) GetCaptchaCount

func (s *VerificationSystem) GetCaptchaCount(number string) int

func (*VerificationSystem) SaveCode

func (s *VerificationSystem) SaveCode(number string, code string, expiresIn time.Duration) error

SaveCode stores a verification code for the given number with rate limiting enforcement. It checks both minute and daily limits before saving the code and returns an error if the limits are exceeded. The code will expire after the specified duration.

func (*VerificationSystem) Verify

func (s *VerificationSystem) Verify(number, code string) bool

Verify checks if the provided verification code is valid for the given number. It returns true if a matching, non-expired code is found, false otherwise. Expired codes are automatically cleaned up during verification.

Jump to

Keyboard shortcuts

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