mirror of
https://github.com/Rain-kl/OpenFlare.git
synced 2026-09-29 14:06:36 +08:00
41 lines
950 B
Go
41 lines
950 B
Go
package cap
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
// VerifyMiddleware returns a Gin middleware that checks and consumes the X-Cap-Token header.
|
|
// enabledFunc is an optional callback allowing dynamic check of whether captcha protection is turned on.
|
|
func (m *Manager) VerifyMiddleware(scope string, enabledFunc func() bool) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
if enabledFunc != nil && !enabledFunc() {
|
|
c.Next()
|
|
return
|
|
}
|
|
|
|
token := c.GetHeader("X-Cap-Token")
|
|
if token == "" {
|
|
c.JSON(http.StatusUnauthorized, gin.H{
|
|
"success": false,
|
|
"error": "验证码验证失败,缺少验证码凭证",
|
|
})
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
valid, err := m.VerifyToken(c.Request.Context(), token, scope)
|
|
if err != nil || !valid {
|
|
c.JSON(http.StatusUnauthorized, gin.H{
|
|
"success": false,
|
|
"error": "验证码校验失败或已过期,请重试",
|
|
})
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
c.Next()
|
|
}
|
|
}
|