README

Captchas

Build Status Coverage Status Go.Dev reference Go Report Card

Base64 Captchas Manager, supports multiple drivers and stores.

Drivers

Stores

Usage

Preview: https://captcha.clevergo.tech/.

$ cd example
$ go run main.go
Quick Start
$ go get clevergo.tech/captchas \
	clevergo.tech/captchas/drivers \
	clevergo.tech/captchas/stores/memstore
package main

import (
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"text/template"

	"clevergo.tech/captchas"
	"clevergo.tech/captchas/drivers"
	"clevergo.tech/captchas/stores/memstore"
)

var (
	store   = memstore.New()              // memory store.
	driver  = drivers.NewDigit()          // digit driver.
	manager = captchas.New(store, driver) // manager
	tmpl    = template.Must(template.New("captcha").Parse(`
<html>
<body>
<form action="/validate" method="POST">
	<input name="captcha">
	{{ .captcha.HTMLField "captcha_id" }}
	<input type="submit" value="Submit">
</form>
</body>
</html>
	`))
)

func main() {
	http.HandleFunc("/generate", generate)
	http.HandleFunc("/validate", validate)
	log.Println(http.ListenAndServe(":8080", http.DefaultServeMux))
}

// generates a new captcha
func generate(w http.ResponseWriter, r *http.Request) {
	captcha, err := manager.Generate(r.Context())
	if err != nil {
		http.Error(w, err.Error(), 500)
                return
	}

	// returns JSON data.
	if r.URL.Query().Get("format") == "json" {
		v := map[string]string{
			"captcha_id":   captcha.ID(),             // captcha ID.
			"captcha_data": captcha.EncodeToString(), // base64 encode string.
		}
		data, _ := json.Marshal(v)
		w.Write(data)
		return
	}

	// render captcha via template.
	tmpl.Execute(w, map[string]interface{}{
		"captcha": captcha,
	})

}

// validates a captcha.
func validate(w http.ResponseWriter, r *http.Request) {
	captchaID := r.PostFormValue("captcha_id")
	captcha := r.PostFormValue("captcha")

	// verify
	if err := manager.Verify(r.Context(), captchaID, captcha, true); err != nil {
		io.WriteString(w, fmt.Sprintf("captcha is invalid: %s", err.Error()))
		return
	}

	io.WriteString(w, "valid")
}
Expand ▾ Collapse ▴

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrCaptchaIncorrect = errors.New("captcha is incorrect")
	ErrCaptchaExpired   = errors.New("captcha is expired")
)

    Errors

    Functions

    This section is empty.

    Types

    type Captcha

    type Captcha interface {
    	// ID returns captcha ID.
    	ID() string
    
    	// Answer returns captcha answer.
    	Answer() string
    
    	// EncodeToString returns encoded base64 string.
    	EncodeToString() string
    
    	// HTMLField returns a template.HTML that includes captcha ID hidden input field
    	// and media field(audio/img).
    	HTMLField(fieldName string) template.HTML
    }

      Captcha is an interface that captchas that generated by driver should implements.

      type Driver

      type Driver interface {
      	// Generate generates a new captcha, returns an error if failed.
      	Generate() (Captcha, error)
      }

        Driver defines how to generate captchas.

        type Manager

        type Manager struct {
        	// contains filtered or unexported fields
        }

          Manager is a captchas manager.

          func New

          func New(store Store, driver Driver, opts ...Option) *Manager

            New returns a manager instance with the given store and driver.

            func (*Manager) Generate

            func (m *Manager) Generate(ctx context.Context) (Captcha, error)

              Generate generates a new captcha and save it to store, returns an error if failed.

              func (*Manager) Get

              func (m *Manager) Get(ctx context.Context, id string, clear bool) (string, error)

                Get is a shortcut of Store.Get.

                func (*Manager) Verify

                func (m *Manager) Verify(ctx context.Context, id, actual string, clear bool) error

                  Verify verifies whether the given actual value is equal to the answer of captcha, returns an error if failed.

                  type Option

                  type Option func(*Manager)

                    Option is a function that receives a pointer of manager.

                    func CaseSensitive

                    func CaseSensitive(v bool) Option

                      CaseSensitive is an option that enable or disable case sensitive.

                      type Store

                      type Store interface {
                      	// Get returns the answer of the given captcha ID, returns
                      	// an error if failed. Clear indicates whether delete the
                      	// captcha after fetching.
                      	Get(ctx context.Context, id string, clear bool) (string, error)
                      
                      	// Set saves the captcha ID and answer, returns error
                      	// if failed.
                      	Set(ctx context.Context, id, answer string) error
                      }

                        Store defines how to save and load captcha information.

                        Directories

                        Path Synopsis
                        drivers module
                        stores
                        dbstore Module
                        memstore Module
                        mysqlstore Module
                        postgresstore Module
                        redisstore Module
                        sqlite3store Module