f
This commit is contained in:
@@ -1,7 +1,9 @@
|
||||
package captcha
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
captcha20230305 "github.com/alibabacloud-go/captcha-20230305/client"
|
||||
openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
|
||||
@@ -12,6 +14,24 @@ import (
|
||||
"ycc-server/common/xerr"
|
||||
)
|
||||
|
||||
// 用于在 context 中传递 User-Agent 的 key(仅本包读取)
|
||||
type ctxKey struct{}
|
||||
|
||||
var userAgentCtxKey = &ctxKey{}
|
||||
|
||||
// WithUserAgent 将 User-Agent 写入 context,供 Verify 判断是否微信环境
|
||||
func WithUserAgent(ctx context.Context, userAgent string) context.Context {
|
||||
if ctx == nil {
|
||||
return ctx
|
||||
}
|
||||
return context.WithValue(ctx, userAgentCtxKey, userAgent)
|
||||
}
|
||||
|
||||
// isWechatUserAgent 判断是否为微信内置浏览器(含小程序、H5)
|
||||
func isWechatUserAgent(ua string) bool {
|
||||
return strings.Contains(ua, "MicroMessenger")
|
||||
}
|
||||
|
||||
// Config 验证码配置
|
||||
type Config struct {
|
||||
AccessKeyID string
|
||||
@@ -20,18 +40,23 @@ type Config struct {
|
||||
SceneID string
|
||||
}
|
||||
|
||||
// Verify 验证阿里云滑块验证码
|
||||
func Verify(cfg Config, captchaVerifyParam string) error {
|
||||
// Verify 验证阿里云滑块验证码。若 ctx 中带有 User-Agent 且为微信环境则跳过验证(默认成功)。
|
||||
func Verify(ctx context.Context, cfg Config, captchaVerifyParam string) error {
|
||||
// 开发环境跳过验证
|
||||
if os.Getenv("ENV") == "development" {
|
||||
logx.Info("[Captcha] 开发环境,跳过验证码校验")
|
||||
return nil
|
||||
}
|
||||
|
||||
// 微信环境(内置浏览器/小程序)跳过图形验证码,不要求 captchaVerifyParam
|
||||
if ua, ok := ctx.Value(userAgentCtxKey).(string); ok && ua != "" && isWechatUserAgent(ua) {
|
||||
logx.Info("[Captcha] 微信环境,跳过图形验证码校验")
|
||||
return nil
|
||||
}
|
||||
|
||||
// 检查参数
|
||||
if captchaVerifyParam == "" {
|
||||
logx.Info("[Captcha] 空参数,跳过验证码校验,兼容未做防盗刷验证码的场景")
|
||||
return nil
|
||||
return errors.Wrapf(xerr.NewErrMsg("图形验证码校验失败"), "empty captchaVerifyParam")
|
||||
}
|
||||
|
||||
// 创建客户端配置
|
||||
|
||||
Reference in New Issue
Block a user