Documentation
¶
Overview ¶
Package captcha provides verification code management with Redis storage.
It supports creating, verifying, and deleting captcha codes with automatic expiration. Verification is atomic and one-time (code is deleted after successful verification).
Hertz Backend Setup ¶
// Initialize captcha with Redis client
cap := captcha.New(redisClient)
// Send captcha endpoint
h.POST("/captcha/send", func(ctx context.Context, c *app.RequestContext) {
email := c.Query("email")
code := help.Random(6) // Generate 6-digit code
cap.Create(ctx, "login:"+email, code, 5*time.Minute)
// Send code via email/SMS...
c.JSON(200, utils.H{"message": "sent"})
})
// Verify captcha endpoint
h.POST("/captcha/verify", func(ctx context.Context, c *app.RequestContext) {
email := c.Query("email")
code := c.Query("code")
if err := cap.Verify(ctx, "login:"+email, code); err != nil {
c.JSON(400, utils.H{"error": err.Error()})
return
}
c.JSON(200, utils.H{"message": "verified"})
})
Angular Frontend Setup ¶
// Send captcha request
sendCaptcha(email: string) {
return this.http.post('/captcha/send', null, { params: { email } });
}
// Verify captcha
verifyCaptcha(email: string, code: string) {
return this.http.post('/captcha/verify', null, { params: { email, code } });
}
Security Notes ¶
- Codes are deleted after successful verification (one-time use)
- Use appropriate TTL (e.g., 5 minutes) to limit attack window
- Consider rate limiting to prevent brute force attacks
- Use Redis key prefix to namespace different captcha types
Index ¶
- Variables
- type Captcha
- func (x *Captcha) Create(ctx context.Context, name string, code string, ttl time.Duration) string
- func (x *Captcha) Delete(ctx context.Context, name string) int64
- func (x *Captcha) Exists(ctx context.Context, name string) bool
- func (x *Captcha) Key(name string) string
- func (x *Captcha) Verify(ctx context.Context, name string, code string) error
- type Option
Constants ¶
This section is empty.
Variables ¶
var ( ErrNotExists = errors.New("captcha: code does not exist or expired") ErrInvalidCode = errors.New("captcha: invalid code") )
Errors returned by captcha functions.
Functions ¶
This section is empty.
Types ¶
type Captcha ¶
type Captcha struct {
// RDb is the Redis client for storing captcha codes.
RDb *redis.Client
// Prefix is the key prefix for all captcha keys (default: "captcha").
Prefix string
}
Captcha provides verification code management with Redis storage.
func (*Captcha) Create ¶
Create stores a captcha code with the given name and TTL. If a code already exists for this name, it will be overwritten. Returns "OK" on success.
func (*Captcha) Delete ¶
Delete removes a captcha code by name. Returns the number of keys deleted (0 or 1).
func (*Captcha) Exists ¶
Exists checks if a captcha code exists for the given name. Note: This does not consume the code. Use Verify for actual verification.
func (*Captcha) Key ¶
Key generates the full Redis key for a captcha name. Format: "{prefix}:{name}"