captchas

package module
v0.3.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 9, 2020 License: BSD-3-Clause Imports: 3 Imported by: 7

README

Captchas

Build Status Coverage Status GoDoc Go Report Card Release

Base64 Captchas Manager, supports multiple drivers(digit, math, audio, string, chinese etc.) and stores(memory, redis, memcached etc.).

Usage

Preview: http://129.204.189.159:10000/.

$ cd example
$ go run main.go
Quick Start
package main

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

	"github.com/clevergo/captchas"
	"github.com/clevergo/captchas/drivers"
	"github.com/clevergo/captchas/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()
	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(captchaID, captcha, true); err != nil {
		io.WriteString(w, fmt.Sprintf("captcha is invalid: %s", err.Error()))
		return
	}

	io.WriteString(w, "valid")
}

Drivers

import "github.com/clevergo/captchas/drivers"
Digit
// all options are optional.
opts := []drivers.DigitOption{
	drivers.DigitHeight(50),
	drivers.DigitWidth(120),
	drivers.DigitLength(6),
	drivers.DigitMaxSkew(0.8),
	drivers.DigitDotCount(80),
}
driver := drivers.NewDigit(opts...)
Audio
// all options are optional.
opts := []drivers.AudioOption{
	drivers.AudioLangauge("en"),
	drivers.AudioLength(6),
}
driver := drivers.NewAudio(opts...)
Math
// all options are optional.
opts := []drivers.MathOption{
	drivers.MathHeight(50),
	drivers.MathWidth(120),
	drivers.MathNoiseCount(0),
	drivers.MathFonts([]string{}),
	drivers.MathBGColor(&color.RGBA{}),
}
driver := drivers.NewMath(opts...)
String
// all options are optional.
opts := []drivers.StringOption{
	drivers.StringHeight(50),
	drivers.StringWidth(120),
	drivers.StringLength(4),
	drivers.StringNoiseCount(0),
	drivers.StringFonts([]string{}),
	drivers.StringSource("abcdefghijklmnopqrstuvwxyz"),
	drivers.StringBGColor(&color.RGBA{}),
}
driver := drivers.NewString(opts...)
Chinese
// all options are optional.
opts := []drivers.ChineseOption{
	drivers.ChineseHeight(50),
	drivers.ChineseWidth(120),
	drivers.ChineseLength(4),
	drivers.ChineseNoiseCount(0),
	drivers.ChineseFonts([]string{"wqy-microhei.ttc"}),
	drivers.ChineseSource("零一二三四五六七八九十"),
	drivers.ChineseBGColor(&color.RGBA{}),
}
driver := drivers.NewChinese(opts...)

Stores

Memory
import "github.com/clevergo/captchas/memstore"
store := memstore.New(
	memstore.Expiration(10*time.Minute), // captcha expiration, optional.
	memstore.GCInterval(time.Minute), // garbage collection interval to delete expired captcha, optional.
)

Inspired by scs.memstore.

Redis
import (
    "github.com/clevergo/captchas/redisstore"
    "github.com/go-redis/redis/v7"
)
// redis client.
client := redis.NewClient(&redis.Options{
	Addr: "localhost:6379",
})
store := redisstore.New(
	client,
	redisstore.Expiration(expiration), // captcha expiration, optional.
	redisstore.Prefix("caotchas"), // redis key prefix, optional.
)
Memcached
import (
	"github.com/bradfitz/gomemcache/memcache"
	"github.com/clevergo/captchas/memcachedstore"
)
// client.
client := memcache.New("localhost:11211")
store := memcachedstore.New(
	client,
	memcachedstore.Expiration(int32(600)), // captcha expiration, optional.
	memcachedstore.Prefix("captchas"),     // key prefix, optional.
)

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() (Captcha, error)

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

func (*Manager) Get

func (m *Manager) Get(id string, clear bool) (string, error)

Get is a shortcut of Store.Get.

func (*Manager) Verify

func (m *Manager) Verify(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(id string, clear bool) (string, error)

	// Set saves the captcha ID and answer, returns error
	// if failed.
	Set(id, answer string) error
}

Store defines how to save and load captcha information.

Directories

Path Synopsis
drivers module
memstore module
redisstore module
stores
dbstore Module
memstore Module
redisstore Module

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL