all repos — captcha @ 436e363f8439b0ac604f152748e2e13bbe575b53

Go package captcha implements generation and verification of image and audio CAPTCHAs.

captcha.go (view raw)

  1// Package captcha implements generation and verification of image and audio
  2// CAPTCHAs.
  3//
  4// A captcha solution is the sequence of digits 0-9 with the defined length.
  5// There are two captcha representations: image and audio.
  6//
  7// An image representation is a PNG-encoded image with the solution printed on
  8// it in such a way that makes it hard for computers to solve it using OCR.
  9//
 10// An audio representation is a WAVE-encoded (8 kHz unsigned 8-bit) sound
 11// with the spoken solution (currently in English). To make it hard for
 12// computers to solve audio captcha, the voice that pronounces numbers has
 13// random speed and pitch, and there is a randomly generated background noise
 14// mixed into the sound.
 15//
 16// This package doesn't require external files or libraries to generate captcha
 17// representations; it is self-contained.
 18//
 19// To make captchas one-time, the package includes a memory storage that stores
 20// captcha ids, their solutions, and expiration time. Used captchas are removed
 21// from the store immediately after calling Verify or VerifyString, while
 22// unused captchas (user loaded a page with captcha, but didn't submit the
 23// form) are collected automatically after the predefined expiration time.
 24// Developers can also provide custom store (for example, which saves captcha
 25// ids and solutions in database) by implementing Store interface and
 26// registering the object with SetCustomStore.
 27//
 28// Captchas are created by calling New, which returns the captcha id.  Their
 29// representations, though, are created on-the-fly by calling WriteImage or
 30// WriteAudio functions. Created representations are not stored anywhere, so
 31// subsequent calls to these functions with the same id will write the same
 32// captcha solution, but with a different random representation. Reload
 33// function will create a new different solution for the provided captcha,
 34// allowing users to "reload" captcha if they can't solve the displayed one
 35// without reloading the whole page.  Verify and VerifyString are used to
 36// verify that the given solution is the right one for the given captcha id.
 37//
 38// Server provides an http.Handler which can serve image and audio
 39// representations of captchas automatically from the URL. It can also be used
 40// to reload captchas.  Refer to Server function documentation for details, or
 41// take a look at the example in "example" subdirectory.
 42package captcha
 43
 44import (
 45	"bytes"
 46	"crypto/rand"
 47	"github.com/dchest/uniuri"
 48	"io"
 49	"os"
 50)
 51
 52const (
 53	// Default number of digits in captcha solution.
 54	DefaultLen = 6
 55	// The number of captchas created that triggers garbage collection used
 56	// by default store.
 57	CollectNum = 100
 58	// Expiration time of captchas used by default store.
 59	Expiration = 10 * 60 // 10 minutes
 60
 61)
 62
 63var ErrNotFound = os.NewError("captcha with the given id not found")
 64
 65// globalStore is a shared storage for captchas, generated by New function.
 66var globalStore = NewMemoryStore(CollectNum, Expiration)
 67
 68// SetCustomStore sets custom storage for captchas, replacing the default
 69// memory store. This function must be called before generating any captchas.
 70func SetCustomStore(s Store) {
 71	globalStore = s
 72}
 73
 74// RandomDigits returns a byte slice of the given length containing random
 75// digits in range 0-9.
 76func RandomDigits(length int) []byte {
 77	d := make([]byte, length)
 78	if _, err := io.ReadFull(rand.Reader, d); err != nil {
 79		panic("error reading random source: " + err.String())
 80	}
 81	for i := range d {
 82		d[i] %= 10
 83	}
 84	return d
 85}
 86
 87// New creates a new captcha with the standard length, saves it in the internal
 88// storage and returns its id.
 89func New() string {
 90	return NewLen(DefaultLen)
 91}
 92
 93// NewLen is just like New, but accepts length of a captcha solution as the
 94// argument.
 95func NewLen(length int) (id string) {
 96	id = uniuri.New()
 97	globalStore.Set(id, RandomDigits(length))
 98	return
 99}
100
101// Reload generates and remembers new digits for the given captcha id.  This
102// function returns false if there is no captcha with the given id.
103//
104// After calling this function, the image or audio presented to a user must be
105// refreshed to show the new captcha representation (WriteImage and WriteAudio
106// will write the new one).
107func Reload(id string) bool {
108	old := globalStore.Get(id, false)
109	if old == nil {
110		return false
111	}
112	globalStore.Set(id, RandomDigits(len(old)))
113	return true
114}
115
116// WriteImage writes PNG-encoded image representation of the captcha with the
117// given id. The image will have the given width and height.
118func WriteImage(w io.Writer, id string, width, height int) os.Error {
119	d := globalStore.Get(id, false)
120	if d == nil {
121		return ErrNotFound
122	}
123	_, err := NewImage(d, width, height).WriteTo(w)
124	return err
125}
126
127// WriteAudio writes WAV-encoded audio representation of the captcha with the
128// given id.
129func WriteAudio(w io.Writer, id string) os.Error {
130	d := globalStore.Get(id, false)
131	if d == nil {
132		return ErrNotFound
133	}
134	_, err := NewAudio(d).WriteTo(w)
135	return err
136}
137
138// Verify returns true if the given digits are the ones that were used to
139// create the given captcha id.
140// 
141// The function deletes the captcha with the given id from the internal
142// storage, so that the same captcha can't be verified anymore.
143func Verify(id string, digits []byte) bool {
144	if digits == nil || len(digits) == 0 {
145		return false
146	}
147	reald := globalStore.Get(id, true)
148	if reald == nil {
149		return false
150	}
151	return bytes.Equal(digits, reald)
152}
153
154// VerifyString is like Verify, but accepts a string of digits.  It removes
155// spaces and commas from the string, but any other characters, apart from
156// digits and listed above, will cause the function to return false.
157func VerifyString(id string, digits string) bool {
158	if digits == "" {
159		return false
160	}
161	ns := make([]byte, len(digits))
162	for i := range ns {
163		d := digits[i]
164		switch {
165		case '0' <= d && d <= '9':
166			ns[i] = d - '0'
167		case d == ' ' || d == ',':
168			// ignore
169		default:
170			return false
171		}
172	}
173	return Verify(id, ns)
174}