Skip to content

Commit

Permalink
feat: add math captcha
Browse files Browse the repository at this point in the history
Signed-off-by: Manfred Touron <94029+moul@users.noreply.github.com>
  • Loading branch information
moul committed Mar 28, 2021
1 parent 0a21d3d commit 8a43ded
Show file tree
Hide file tree
Showing 2 changed files with 77 additions and 0 deletions.
39 changes: 39 additions & 0 deletions captcha/math.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package captcha

import (
"fmt"
"math/rand"
"strconv"
"strings"
)

type mathCaptcha struct {
equation string
result int
}

func NewMathCaptcha() Captcha {
a := rand.Intn(5) + 1 // nolint:gosec,gomnd
b := rand.Intn(5) + 1 // nolint:gosec,gomnd
equation := fmt.Sprintf("%d + %d", a, b)
result := a + b
return mathCaptcha{equation, result}
}

func (c mathCaptcha) Question() (string, error) {
return c.equation, nil
}

func (c mathCaptcha) Validate(input string) (bool, error) {
input = strings.TrimSpace(input)
if input == "" {
return false, nil
}
nb, err := strconv.Atoi(input)
if err != nil {
return false, fmt.Errorf("invalid input: %w", err)
}
return nb == c.result, nil
}

var _ Captcha = (*mathCaptcha)(nil)
38 changes: 38 additions & 0 deletions captcha/math_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package captcha_test

import (
"fmt"
"math/rand"

"moul.io/captcha/captcha"
)

func ExampleNewMathCaptcha() {
rand.Seed(42)
captcha := captcha.NewMathCaptcha()
question, _ := captcha.Question()
fmt.Println(question)

valid, _ := captcha.Validate("42")
fmt.Println(valid)

valid, _ = captcha.Validate("lorem ipsum")
fmt.Println(valid)

valid, _ = captcha.Validate("1 + 3")
fmt.Println(valid)

valid, _ = captcha.Validate("4")
fmt.Println(valid)

valid, _ = captcha.Validate("\n 4\t \n\n \t")
fmt.Println(valid)

// Output:
// 1 + 3
// false
// false
// false
// true
// true
}

0 comments on commit 8a43ded

Please sign in to comment.