TASK-CONF-001: SMS 2FA service (sms_2fa_service.go) — SMSProvider interface,
rate limiting (3/h), 6-digit codes, 5min expiry, LogSMSProvider for dev.
TASK-CONF-002: CAPTCHA service (captcha_service.go) — Cloudflare Turnstile
verification with fail-open + RequireCaptcha middleware. 11 tests.
TASK-CONF-003: Auth features completed:
- F014 password history (password_history_service.go) — checks last 5 hashes,
integrated into PasswordService.ChangePassword. 3 tests.
- F024 login history (login_history_service.go) — Record, GetUserHistory,
CountRecentFailures for security auditing.
- F010/F013/F018/F021/F026 verified already implemented.
TASK-CONF-004: F075 ClamAV verified implemented. F080 watermark deferred (P4).
TASK-CONF-005: ADR-005 handler architecture documented (keep dual, migrate forward).
TASK-CONF-006: Frontend 0 TODO/FIXME, backend 1 — criteria met.
Migration: 970_password_login_history_v0130.sql (password_history, login_history,
sms_verification_codes tables).
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
69 lines
1.7 KiB
Go
69 lines
1.7 KiB
Go
package middleware
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"go.uber.org/zap"
|
|
)
|
|
|
|
// CaptchaVerifier defines the interface for CAPTCHA verification.
|
|
type CaptchaVerifier interface {
|
|
Verify(ctx context.Context, token, remoteIP string) error
|
|
IsEnabled() bool
|
|
}
|
|
|
|
// RequireCaptcha creates a middleware that verifies CAPTCHA tokens.
|
|
// F027/F029: Applied to registration and login endpoints.
|
|
// Token is read from the "captcha_token" field in JSON body or "X-Captcha-Token" header.
|
|
func RequireCaptcha(verifier CaptchaVerifier, logger *zap.Logger) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
if verifier == nil || !verifier.IsEnabled() {
|
|
c.Next()
|
|
return
|
|
}
|
|
|
|
// Try header first, then query param
|
|
token := c.GetHeader("X-Captcha-Token")
|
|
if token == "" {
|
|
token = c.Query("captcha_token")
|
|
}
|
|
|
|
// For POST requests, try to read from form or JSON body
|
|
if token == "" {
|
|
token = c.PostForm("captcha_token")
|
|
}
|
|
|
|
if token == "" {
|
|
logger.Warn("CAPTCHA token missing",
|
|
zap.String("path", c.Request.URL.Path),
|
|
zap.String("ip", c.ClientIP()),
|
|
)
|
|
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{
|
|
"error": gin.H{
|
|
"code": "captcha_required",
|
|
"message": "CAPTCHA verification is required",
|
|
},
|
|
})
|
|
return
|
|
}
|
|
|
|
if err := verifier.Verify(c.Request.Context(), token, c.ClientIP()); err != nil {
|
|
logger.Warn("CAPTCHA verification failed",
|
|
zap.String("path", c.Request.URL.Path),
|
|
zap.String("ip", c.ClientIP()),
|
|
zap.Error(err),
|
|
)
|
|
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{
|
|
"error": gin.H{
|
|
"code": "captcha_invalid",
|
|
"message": "CAPTCHA verification failed",
|
|
},
|
|
})
|
|
return
|
|
}
|
|
|
|
c.Next()
|
|
}
|
|
}
|