A Q&A platform software for teams at any scales. Whether it's a community forum, help center, or knowledge management platform, you can always count on Apache Answer.
feat(captcha): add captcha plugin
LinkinStarsc55d318e64eb
diff --git a/internal/controller/user_controller.go b/internal/controller/user_controller.goindex f0e70cfe..b35a557b 100644--- a/internal/controller/user_controller.go+++ b/internal/controller/user_controller.go@@ -509,19 +509,6 @@ func (uc *UserController) ActionRecord(ctx *gin.Context) {}-// UserRegisterCaptcha godoc-// @Summary UserRegisterCaptcha-// @Description UserRegisterCaptcha-// @Tags User-// @Accept json-// @Produce json-// @Success 200 {object} handler.RespBody{data=schema.UserLoginResp}-// @Router /answer/api/v1/user/register/captcha [get]-func (uc *UserController) UserRegisterCaptcha(ctx *gin.Context) {- resp, err := uc.actionService.UserRegisterCaptcha(ctx)- handler.HandleResponse(ctx, err, resp)-}-// GetUserNotificationConfig get user's notification config// @Summary get user's notification config// @Description get user's notification configdiff --git a/internal/router/answer_api_router.go b/internal/router/answer_api_router.goindex 1ea2be89..de5cf83f 100644--- a/internal/router/answer_api_router.go+++ b/internal/router/answer_api_router.go@@ -131,7 +131,6 @@ func (a *AnswerAPIRouter) RegisterMustUnAuthAnswerAPIRouter(authUserMiddleware *routerGroup := r.Group("", middleware.BanAPIForUserCenter)routerGroup.POST("/user/login/email", a.userController.UserEmailLogin)routerGroup.POST("/user/register/email", a.userController.UserRegisterByEmail)- routerGroup.GET("/user/register/captcha", a.userController.UserRegisterCaptcha)routerGroup.POST("/user/email/verification", a.userController.UserVerifyEmail)routerGroup.PUT("/user/email", a.userController.UserChangeEmailVerify)routerGroup.POST("/user/password/reset", a.userController.RetrievePassWord)diff --git a/internal/service/action/captcha_service.go b/internal/service/action/captcha_service.goindex 7619b983..888946ff 100644--- a/internal/service/action/captcha_service.go+++ b/internal/service/action/captcha_service.go@@ -21,14 +21,11 @@ package actionimport ("context"- "image/color"- "strings"- "github.com/apache/incubator-answer/internal/base/reason""github.com/apache/incubator-answer/internal/entity""github.com/apache/incubator-answer/internal/schema"- "github.com/mojocn/base64Captcha"- "github.com/segmentfault/pacman/errors"+ "github.com/apache/incubator-answer/pkg/token"+ "github.com/apache/incubator-answer/plugin""github.com/segmentfault/pacman/log")@@ -85,48 +82,27 @@ func (cs *CaptchaService) ActionRecord(ctx context.Context, req *schema.ActionReverificationResult := cs.ValidationStrategy(ctx, unit, req.Action)if !verificationResult {resp.CaptchaID, resp.CaptchaImg, err = cs.GenerateCaptcha(ctx)- resp.Verify = true+ if len(resp.CaptchaID) > 0 {+ resp.Verify = true+ }}return}-func (cs *CaptchaService) UserRegisterCaptcha(ctx context.Context) (resp *schema.ActionRecordResp, err error) {- resp = &schema.ActionRecordResp{}- resp.CaptchaID, resp.CaptchaImg, err = cs.GenerateCaptcha(ctx)- resp.Verify = true- return-}--func (cs *CaptchaService) UserRegisterVerifyCaptcha(- ctx context.Context, id string, VerifyValue string,-) bool {- if id == "" || VerifyValue == "" {- return false- }- pass, err := cs.VerifyCaptcha(ctx, id, VerifyValue)- if err != nil {- return false- }- return pass-}-// ActionRecordVerifyCaptcha// Verify that you need to enter a CAPTCHA, and that the CAPTCHA is correctfunc (cs *CaptchaService) ActionRecordVerifyCaptcha(- ctx context.Context, actionType string, unit string, id string, VerifyValue string,+ ctx context.Context, actionType string, unit string, captchaID string, captchaCode string,) bool {verificationResult := cs.ValidationStrategy(ctx, unit, actionType)- if !verificationResult {- if id == "" || VerifyValue == "" {- return false- }- pass, err := cs.VerifyCaptcha(ctx, id, VerifyValue)- if err != nil {- return false- }- return pass+ if verificationResult {+ return true+ }+ pass, err := cs.VerifyCaptcha(ctx, captchaID, captchaCode)+ if err != nil {+ return false}- return true+ return pass}func (cs *CaptchaService) ActionRecordAdd(ctx context.Context, actionType string, unit string) (int, error) {@@ -155,43 +131,35 @@ func (cs *CaptchaService) ActionRecordDel(ctx context.Context, actionType string// GenerateCaptcha generate captchafunc (cs *CaptchaService) GenerateCaptcha(ctx context.Context) (key, captchaBase64 string, err error) {- driverString := base64Captcha.DriverString{- Height: 60,- Width: 200,- NoiseCount: 0,- ShowLineOptions: 2 | 4,- Length: 4,- Source: "1234567890qwertyuioplkjhgfdsazxcvbnm",- BgColor: &color.RGBA{R: 211, G: 211, B: 211, A: 0},- Fonts: []string{"wqy-microhei.ttc"},+ realCaptcha := ""+ _ = plugin.CallCaptcha(func(fn plugin.Captcha) error {+ if captcha, code := fn.Create(); len(code) > 0 {+ captchaBase64 = captcha+ realCaptcha = code+ }+ return nil+ })+ if len(realCaptcha) == 0 {+ return "", "", nil}- driver := driverString.ConvertFonts()- id, content, answer := driver.GenerateIdQuestionAnswer()- item, err := driver.DrawCaptcha(content)- if err != nil {- return "", "", errors.InternalServer(reason.UnknownError).WithError(err).WithStack()- }- err = cs.captchaRepo.SetCaptcha(ctx, id, answer)+ id := token.GenerateToken()+ err = cs.captchaRepo.SetCaptcha(ctx, id, realCaptcha)if err != nil {return "", "", err}-- captchaBase64 = item.EncodeB64string()return id, captchaBase64, nil}// VerifyCaptcha generate captchafunc (cs *CaptchaService) VerifyCaptcha(ctx context.Context, key, captcha string) (isCorrect bool, err error) {- realCaptcha, err := cs.captchaRepo.GetCaptcha(ctx, key)- if err != nil {- log.Error("VerifyCaptcha GetCaptcha Error", err.Error())- return false, nil- }- err = cs.captchaRepo.DelCaptcha(ctx, key)- if err != nil {- log.Error("VerifyCaptcha DelCaptcha Error", err.Error())- return false, nil- }- return strings.TrimSpace(captcha) == realCaptcha, nil+ realCaptcha, _ := cs.captchaRepo.GetCaptcha(ctx, key)++ _ = plugin.CallCaptcha(func(fn plugin.Captcha) error {+ isCorrect = fn.Verify(realCaptcha, captcha)+ return nil+ })++ _ = cs.captchaRepo.DelCaptcha(ctx, key)+ return isCorrect, nil}diff --git a/internal/service/action/captcha_strategy.go b/internal/service/action/captcha_strategy.goindex 72dfefed..1d2dcbc3 100644--- a/internal/service/action/captcha_strategy.go+++ b/internal/service/action/captcha_strategy.go@@ -21,9 +21,11 @@ package actionimport ("context"- "github.com/segmentfault/pacman/log""time"+ "github.com/apache/incubator-answer/plugin"+ "github.com/segmentfault/pacman/log"+"github.com/apache/incubator-answer/internal/entity")@@ -31,6 +33,10 @@ import (// true pass// false need captchafunc (cs *CaptchaService) ValidationStrategy(ctx context.Context, unit, actionType string) bool {+ // If the captcha is not enabled, the verification is passed directly+ if !plugin.CaptchaEnabled() {+ return true+ }info, err := cs.captchaRepo.GetActionType(ctx, unit, actionType)if err != nil {log.Error(err)diff --git a/plugin/captcha.go b/plugin/captcha.gonew file mode 100644index 00000000..f73fa784--- /dev/null+++ b/plugin/captcha.go@@ -0,0 +1,62 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */++package plugin++type Captcha interface {+ Base+ // Create optional. If this plugin need to create captcha via backend, implement this method.+ // On other hand, if this plugin create captcha via third-party service, ignore this method.+ // Return captcha: The captcha image base64 string, code: The real captcha code.+ Create() (captcha, code string)+ // Verify required. Verify the user input captcha is correct or not+ // captcha: The captchaCode generated by Create method, if not implemented, it's empty.+ Verify(captchaCode, userInput string) (pass bool)+}++var (+ // CallCaptcha is a function that calls all registered parsers+ callCaptcha,+ registerCaptcha = MakePlugin[Captcha](false)+)++func CallCaptcha(fn func(fn Captcha) error) error {+ slugName := ""+ _ = callCaptcha(func(captcha Captcha) error {+ slugName = captcha.Info().SlugName+ return nil+ })+ if slugName == "" {+ return nil+ }+ return callCaptcha(func(captcha Captcha) error {+ if captcha.Info().SlugName == slugName {+ return fn(captcha)+ }+ return nil+ })+}++func CaptchaEnabled() (enabled bool) {+ _ = callCaptcha(func(fn Captcha) error {+ enabled = true+ return nil+ })+ return+}diff --git a/plugin/plugin.go b/plugin/plugin.goindex e492fdc4..1dd14cf6 100644--- a/plugin/plugin.go+++ b/plugin/plugin.go@@ -93,6 +93,10 @@ func Register(p Base) {if _, ok := p.(Reviewer); ok {registerReviewer(p.(Reviewer))}++ if _, ok := p.(Captcha); ok {+ registerCaptcha(p.(Captcha))+ }}type Stack[T Base] struct {