Compare commits

...

10 Commits

12 changed files with 299 additions and 219 deletions

View File

@ -6,7 +6,7 @@ SYSDDIR_=${shell pkg-config systemd --variable=systemdsystemunitdir}
SYSDDIR=${SYSDDIR_:/%=%}
DESTDIR=/
LDFLAGS=-ldflags "-s -w -X main.version=1.2.0" -tags osusergo,netgo
LDFLAGS=-ldflags "-s -w -X main.version=2.0.0" -tags osusergo,netgo
all: ${TARGET}

View File

@ -1,11 +1,11 @@
justcaptcha ver. 1.2.0
justcaptcha ver. 2.0.0
======================
A simple CAPTCHA service implementation.
## Usage
justcaptchad -expiry 5m -listen /var/run/justcaptchad/j.sock
justcaptchad -expiry 5m -listen /var/run/justcaptcha/c.sock
`-expiry` takes time for CAPTCHA to be valid for in format X{s,m,h}.
@ -13,22 +13,26 @@ A simple CAPTCHA service implementation.
## API
### Get a new CAPTCHA
### Errors
GET /
All error codes are returned with an error message in `text/plain`.
It will return an ID of a new CAPTCHA in plain text.
### Create a new CAPTCHA
POST /
It will return an ID of a new CAPTCHA in `text/plain`.
#### HTTP codes
- `200` if created (and it always being created)
- `201` if created (always being created)
### Get an image for a CAPTCHA
GET /:captcha_id/image?style=
Responds with an image in JPEG format.
Responds with an image in JPEG format (`image/jpeg`).
An optional URL query parameter `style=` set a name of a CAPTCHA style if
An optional URL parameter `style=` set a name of a CAPTCHA style if it is
implemented by used CAPTCHA implementation.
#### HTTP codes
@ -47,7 +51,7 @@ It takes one parameter `answer=123456`.
Responds with an empty body and one of the HTTP codes.
#### HTTP codes
- `200` if solved
- `202` if solved
- `403` if not solved
- `404` if doesn't exist
@ -57,17 +61,41 @@ Responds with an empty body and one of the HTTP codes.
Responds with an empty body and one of the HTTP codes.
If an optional `remove` URL query parameter without a value supplied. CAPTCHA
will be removed without check if it is solved and a HTTP code `200` will be sent.
Otherwise, a `403` HTTP code will be sent, and, e.g. browser will print an error
message to console. So, in this case it helps to keep a browser's console cleaner.
If CAPTCHA doesn't exist a `404` HTTP code still will be returned.
If an optional `remove` parameter without a value supplied CAPTCHA will be
removed without checking and a HTTP code `204` will be sent. Otherwise, a `403`
HTTP code will be sent if it is not solved. If a CAPTCHA doesn't exist a `404`
HTTP code still will be returned.
A `remove` parameter was added because browsers will print an error in a console
if HTTP code is not within `2xx`, so to keep a console clean you can provide
this parameter.
This can be useful to remove an unused CAPTCHA from a DB without waiting for it
to be expired. E.g. when a visitor requests for a new CAPTCHA because he struggle
to solve it.
to be expired. E.g. when a visitor requests for a new CAPTCHA or leaving a page.
#### HTTP codes
- `200` if solved
- `204` if solved
- `403` if not solved
- `404` if doesn't exist
- `404` if doesn't exist
### Example of interaction
First a client makes a POST request with empty body to create a new CAPTCHA and obtains an ID for it.
POST /
As a result we get an ID `n60f2K9JiD5c4qX9MYe90A54nT0nnJrtgfhAjfaWtBg`.
Then a client requests an image for a new CAPTCHA. E.g. with a dark style.
GET /n60f2K9JiD5c4qX9MYe90A54nT0nnJrtgfhAjfaWtBg/image?style=dark
Then a client submits an answer for a CAPTCHA.
POST 'answer=198807' /n60f2K9JiD5c4qX9MYe90A54nT0nnJrtgfhAjfaWtBg
And if answer was correct a client gets a HTTP code 202. Or 403 otherwise.
Then a server checks if CAPTCHA was solved with following request.
GET /n60f2K9JiD5c4qX9MYe90A54nT0nnJrtgfhAjfaWtBg

View File

@ -1,6 +1,6 @@
# Maintainer: Alexander "Arav" Andreev <me@arav.top>
pkgname=justcaptcha
pkgver=1.2.0
pkgver=2.0.0
pkgrel=1
pkgdesc="Just a CAPTCHA service"
arch=('i686' 'x86_64' 'arm' 'armv6h' 'armv7h' 'aarch64')
@ -15,7 +15,7 @@ replaces=()
backup=()
options=()
install=
source=('https://git.arav.top/Arav/justcaptcha/archive/1.2.0.tar.gz')
source=('https://git.arav.top/Arav/justcaptcha/archive/2.0.0.tar.gz')
noextract=()
md5sums=('SKIP')

View File

@ -3,7 +3,6 @@ package main
import (
"flag"
"fmt"
"justcaptcha/internal/captcha"
"justcaptcha/internal/handlers"
"justcaptcha/pkg/server"
"log"
@ -30,12 +29,10 @@ func main() {
return
}
captcha.Init(*captchaExpiry)
hand := handlers.New()
hand := handlers.New(*captchaExpiry)
srv := server.NewHttpServer()
srv.GET("/", hand.New)
srv.POST("/", hand.New)
srv.POST("/:captcha", hand.Solve)
srv.GET("/:captcha", hand.IsSolved)
srv.GET("/:captcha/image", hand.Image)

4
go.mod
View File

@ -1,6 +1,6 @@
module justcaptcha
go 1.18
go 1.19
require (
github.com/fogleman/gg v1.3.0
@ -9,5 +9,5 @@ require (
require (
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 // indirect
golang.org/x/image v0.0.0-20220722155232-062f8c9fd539 // indirect
golang.org/x/image v0.1.0 // indirect
)

26
go.sum
View File

@ -4,7 +4,29 @@ github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 h1:DACJavvAHhabrF0
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0/go.mod h1:E/TSTwGwJL78qG/PmXZO1EjYhfJinVAhrmmHX6Z8B9k=
github.com/julienschmidt/httprouter v1.3.0 h1:U0609e9tgbseu3rBINet9P48AI/D3oJs4dN7jwJOQ1U=
github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM=
golang.org/x/image v0.0.0-20220722155232-062f8c9fd539 h1:/eM0PCrQI2xd471rI+snWuu251/+/jpBpZqir2mPdnU=
golang.org/x/image v0.0.0-20220722155232-062f8c9fd539/go.mod h1:doUCurBvlfPMKfmIpRIywoHmhN3VyhnoFDbvIEWF4hY=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/image v0.1.0 h1:r8Oj8ZA2Xy12/b5KZYj3tuv7NG/fBz3TwQVvpJ9l8Rk=
golang.org/x/image v0.1.0/go.mod h1:iyPr49SD/G/TBxYVB/9RRtGUT5eNbo2u4NamWeQcD5c=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=

View File

@ -1,38 +0,0 @@
package captcha
import (
"image"
"justcaptcha/pkg/captcha"
"time"
)
var captchaDb captcha.CaptchaDB
func Init(expiry time.Duration) {
captchaDb = captcha.NewInMemoryCaptchaDB(expiry)
}
func New(data string) (captcha.Captcha, captcha.ID) {
dc := NewDwellingCaptcha(captchaDb.GetExpiry())
return captchaDb.New(data, dc)
}
func Image(id captcha.ID, style string) (*image.Image, error) {
return captchaDb.Image(id, style)
}
func Solve(id captcha.ID, answer captcha.Answer) (bool, error) {
return captchaDb.Solve(id, answer)
}
func IsSolved(id captcha.ID) (bool, error) {
return captchaDb.IsSolved(id)
}
func Remove(id captcha.ID) error {
return captchaDb.Remove(id)
}
func GetExpiry() time.Duration {
return captchaDb.GetExpiry()
}

View File

@ -1,4 +1,4 @@
package captcha
package dwcaptcha
import (
"image"

View File

@ -3,36 +3,49 @@ package handlers
import (
"fmt"
"image/jpeg"
"justcaptcha/internal/captcha"
pcaptcha "justcaptcha/pkg/captcha"
"justcaptcha/internal/dwcaptcha"
"justcaptcha/pkg/captcha"
"justcaptcha/pkg/captcha/inmemdb"
"justcaptcha/pkg/server"
"net/http"
"time"
)
type CaptchaHandlers struct{}
const errMsgNotFound = "CAPTCHA with such ID doesn't exist"
const errMsgWrongAnswer = "An answer provided was wrong"
const errMsgFailedToGenImage = "failed to generate an image for a CAPTCHA"
const errMsgImageNotFound = "cannot get an image for a non-existing CAPTCHA"
func New() *CaptchaHandlers {
return &CaptchaHandlers{}
type CaptchaHandlers struct {
expiry time.Duration
}
func New(expiry time.Duration) *CaptchaHandlers {
inmemdb.SetExpiry(expiry)
return &CaptchaHandlers{expiry: expiry}
}
func (h *CaptchaHandlers) New(w http.ResponseWriter, r *http.Request) {
_, id := captcha.New(r.RemoteAddr)
dc := dwcaptcha.NewDwellingCaptcha(h.expiry)
_, id := inmemdb.New(r.RemoteAddr, dc)
w.WriteHeader(http.StatusCreated)
fmt.Fprint(w, id)
}
func (h *CaptchaHandlers) Image(w http.ResponseWriter, r *http.Request) {
captchaID := pcaptcha.ID(server.GetURLParam(r, "captcha"))
captchaID := captcha.ID(server.GetURLParam(r, "captcha"))
captchaStyle := r.URL.Query().Get("style")
captchaImage, err := captcha.Image(captchaID, captchaStyle)
captchaImage, err := inmemdb.Image(captchaID, captchaStyle)
if err != nil {
w.WriteHeader(http.StatusNotFound)
fmt.Fprint(w, errMsgImageNotFound)
return
}
if captchaImage == nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprint(w, errMsgFailedToGenImage)
return
}
@ -42,41 +55,47 @@ func (h *CaptchaHandlers) Image(w http.ResponseWriter, r *http.Request) {
}
func (h *CaptchaHandlers) Solve(w http.ResponseWriter, r *http.Request) {
captchaID := captcha.ID(server.GetURLParam(r, "captcha"))
r.ParseForm()
answer := captcha.Answer(r.FormValue("answer"))
captchaID := pcaptcha.ID(server.GetURLParam(r, "captcha"))
answer := pcaptcha.Answer(r.FormValue("answer"))
ok, err := captcha.Solve(captchaID, answer)
ok, err := inmemdb.Solve(captchaID, answer)
if err != nil {
w.WriteHeader(http.StatusNotFound)
fmt.Fprint(w, errMsgNotFound)
return
}
if !ok {
w.WriteHeader(http.StatusForbidden)
}
}
func (h *CaptchaHandlers) IsSolved(w http.ResponseWriter, r *http.Request) {
captchaID := pcaptcha.ID(server.GetURLParam(r, "captcha"))
isJustRemove := r.URL.Query().Has("remove")
if isJustRemove {
err := captcha.Remove(captchaID)
if err != nil {
w.WriteHeader(http.StatusNotFound)
}
fmt.Fprint(w, errMsgWrongAnswer)
return
}
solved, err := captcha.IsSolved(captchaID)
w.WriteHeader(http.StatusAccepted)
}
func (h *CaptchaHandlers) IsSolved(w http.ResponseWriter, r *http.Request) {
captchaID := captcha.ID(server.GetURLParam(r, "captcha"))
isJustRemove := r.URL.Query().Has("remove")
w.WriteHeader(http.StatusNoContent)
if isJustRemove {
inmemdb.Remove(captchaID)
return
}
solved, err := inmemdb.IsSolved(captchaID)
if err != nil {
w.WriteHeader(http.StatusNotFound)
fmt.Fprint(w, errMsgNotFound)
return
}
if !solved {
w.WriteHeader(http.StatusForbidden)
fmt.Fprint(w, errMsgWrongAnswer)
}
}

View File

@ -20,7 +20,8 @@ func NewIntAnswer() Answer {
// Captcha interface that should be implemented by a CAPTCHA.
type Captcha interface {
// Image generates and returns a pointer to an image of CAPTCHA.
// Image generates an image of a CAPTCHA according to a passed style
// and returns a pointer to it.
Image(style string) *image.Image
// Answer returns a pregenerated answer.
Answer() Answer
@ -37,14 +38,14 @@ type Captcha interface {
// All derivatives that embed this struct only need to implement
// an Image() method.
type BaseCaptcha struct {
answer Answer
solved bool
expireIn time.Time
answer Answer
solved bool
expiry time.Time
}
func NewBaseCaptcha(expiry time.Duration) *BaseCaptcha {
return &BaseCaptcha{
expireIn: ExpiryDate(expiry),
expiry: ExpiryDate(expiry),
}
}
@ -52,8 +53,6 @@ func (c *BaseCaptcha) Image(style string) *image.Image {
return nil
}
// Answer generates an integer answer for a CAPTCHA or just returns
// an existing one.
func (c *BaseCaptcha) Answer() Answer {
if c.answer == "" {
c.answer = NewIntAnswer()
@ -61,8 +60,6 @@ func (c *BaseCaptcha) Answer() Answer {
return c.answer
}
// Solve sets solved field to true if given answer is right and returns a result
// of a check.
func (c *BaseCaptcha) Solve(answer Answer) bool {
c.solved = c.answer == answer
return c.solved
@ -73,7 +70,7 @@ func (c *BaseCaptcha) IsSolved() bool {
}
func (c *BaseCaptcha) Expiry() time.Time {
return c.expireIn
return c.expiry
}
// ExpiryDate returns a date when CAPTCHA expires. It adds a passed

View File

@ -1,147 +1,45 @@
package captcha
import (
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"errors"
"image"
"strconv"
"sync"
"time"
)
var errorNotFound = errors.New("captcha not found")
var ErrorNotFound = errors.New("captcha not found")
var defaultExpiredScanInterval = 60 * time.Second
const DefaultExpiredScanInterval = 60 * time.Second
// ID is a CAPTCHA identifier.
type ID string
// NewID generates an ID as a sha256 hash of additionalData, current time
// and answer encoded with base64 in raw URL variant.
// NewID generates an ID as a sha256 hash of additionalData (usually IP-address),
// current time, answer and more, it adds a set of random bytes and encodes all
// of it with base64 in raw URL variant.
func NewID(additionalData string, answer Answer) ID {
idHash := sha256.New()
idHash.Write([]byte(additionalData))
idHash.Write([]byte(strconv.FormatInt(time.Now().UnixMicro(), 16)))
idHash.Write([]byte(answer))
randData := make([]byte, 32)
rand.Read(randData)
idHash.Write(randData)
return ID(base64.RawURLEncoding.EncodeToString(idHash.Sum(nil)))
}
// CaptchaDB interface with all necessary methods.
type CaptchaDB interface {
New(data string, captcha Captcha) (Captcha, ID)
GetExpiry() time.Duration
SetExpiry(expiry time.Duration)
Image(id ID, style string) (*image.Image, error)
Solve(id ID, answer Answer) (bool, error)
IsSolved(id ID) (bool, error)
Remove(id ID) error
cleanExpired()
}
type InMemoryCaptchaDB struct {
sync.Mutex
db map[ID]Captcha
expireIn time.Duration
expireScanInterval time.Duration
}
func NewInMemoryCaptchaDB(expire time.Duration) *InMemoryCaptchaDB {
db := &InMemoryCaptchaDB{
db: make(map[ID]Captcha),
expireIn: expire}
if expire < defaultExpiredScanInterval {
db.expireScanInterval = expire
} else {
db.expireScanInterval = defaultExpiredScanInterval
}
db.cleanExpired()
return db
}
// New accepts an Captcha instance, generates an ID and store it in a database.
// `data` string is an additional random data used to generate an ID,
// e.g. IP-address.
func (cdb *InMemoryCaptchaDB) New(data string, captcha Captcha) (Captcha, ID) {
id := NewID(data, captcha.Answer())
cdb.Lock()
cdb.db[id] = captcha
cdb.Unlock()
return captcha, id
}
// cleanExpired starts a goroutine that deletes expired CAPTCHAs.
func (cdb *InMemoryCaptchaDB) cleanExpired() {
go func() {
for {
sleepFor := cdb.expireScanInterval - (time.Duration(time.Now().Second()) % cdb.expireScanInterval)
time.Sleep(sleepFor)
cdb.Lock()
for id, captcha := range cdb.db {
if time.Since(captcha.Expiry()) >= cdb.expireIn {
delete(cdb.db, id)
}
}
cdb.Unlock()
}
}()
}
// GetExpiry returns time for how long CAPTCHA will last.
func (cdb *InMemoryCaptchaDB) GetExpiry() time.Duration {
return cdb.expireIn
}
// Image returns image for a CAPTCHA.
func (cdb *InMemoryCaptchaDB) Image(id ID, style string) (*image.Image, error) {
cdb.Lock()
defer cdb.Unlock()
if c, ok := cdb.db[id]; ok {
return c.Image(style), nil
}
return nil, errorNotFound
}
// Solve compares given answer with a stored one and if failed
// deletes a CAPTCHA from database.
func (cdb *InMemoryCaptchaDB) Solve(id ID, answer Answer) (bool, error) {
cdb.Lock()
defer cdb.Unlock()
if c, ok := cdb.db[id]; ok {
ok = c.Solve(answer)
if !ok {
delete(cdb.db, id)
}
return ok, nil
}
return false, errorNotFound
}
// IsSolved checks if CAPTCHA was solved and removes it
// from a database.
func (cdb *InMemoryCaptchaDB) IsSolved(id ID) (bool, error) {
cdb.Lock()
defer cdb.Unlock()
if c, ok := cdb.db[id]; ok {
delete(cdb.db, id)
return c.IsSolved(), nil
}
return false, errorNotFound
}
// Remove a CAPTCHA from a database.
func (cdb *InMemoryCaptchaDB) Remove(id ID) error {
cdb.Lock()
defer cdb.Unlock()
if _, ok := cdb.db[id]; ok {
delete(cdb.db, id)
return nil
}
return errorNotFound
}

View File

@ -0,0 +1,157 @@
package inmemdb
import (
"image"
"justcaptcha/pkg/captcha"
"sync"
"time"
)
type InMemoryCaptchaDB struct {
sync.Mutex
db map[captcha.ID]captcha.Captcha
expiry time.Duration
expiryScanInterval time.Duration
}
// NewInMemoryCaptchaDB returns an initialised instance of an InMemoryCaptchaDB.
// An expiry duration is a time for how long CAPTCHA will be valid.
func NewInMemoryCaptchaDB(expiry time.Duration) *InMemoryCaptchaDB {
db := &InMemoryCaptchaDB{
db: make(map[captcha.ID]captcha.Captcha),
expiry: expiry}
if expiry < captcha.DefaultExpiredScanInterval {
db.expiryScanInterval = expiry
} else {
db.expiryScanInterval = captcha.DefaultExpiredScanInterval
}
go db.cleanExpired()
return db
}
// New accepts a CAPTHA instance, generates an ID and store it in a database.
// A data string is an additional random data used to generate an ID,
// e.g. an IP-address.
func (imcdb *InMemoryCaptchaDB) New(data string, cptcha captcha.Captcha) (captcha.Captcha, captcha.ID) {
id := captcha.NewID(data, cptcha.Answer())
imcdb.Lock()
imcdb.db[id] = cptcha
imcdb.Unlock()
return cptcha, id
}
// GetExpiry returns time for how long CAPTCHA will last.
func (imcdb *InMemoryCaptchaDB) GetExpiry() time.Duration {
return imcdb.expiry
}
// SetExpiry changes an expiry duration to a new one.
func (imcdb *InMemoryCaptchaDB) SetExpiry(expiry time.Duration) {
if expiry < captcha.DefaultExpiredScanInterval {
imcdb.expiryScanInterval = expiry
} else {
imcdb.expiryScanInterval = captcha.DefaultExpiredScanInterval
}
}
// Image returns a freshly generated image for a CAPTCHA.
func (imcdb *InMemoryCaptchaDB) Image(id captcha.ID, style string) (*image.Image, error) {
imcdb.Lock()
defer imcdb.Unlock()
if c, ok := imcdb.db[id]; ok {
return c.Image(style), nil
}
return nil, captcha.ErrorNotFound
}
// Solve compares given answer with a stored one and if failed
// deletes a CAPTCHA from database.
func (imcdb *InMemoryCaptchaDB) Solve(id captcha.ID, answer captcha.Answer) (bool, error) {
imcdb.Lock()
defer imcdb.Unlock()
if c, ok := imcdb.db[id]; ok {
ok = c.Solve(answer)
if !ok {
delete(imcdb.db, id)
}
return ok, nil
}
return false, captcha.ErrorNotFound
}
// IsSolved checks if CAPTCHA was solved and removes it
// from a database.
func (imcdb *InMemoryCaptchaDB) IsSolved(id captcha.ID) (bool, error) {
imcdb.Lock()
defer imcdb.Unlock()
if c, ok := imcdb.db[id]; ok {
delete(imcdb.db, id)
return c.IsSolved(), nil
}
return false, captcha.ErrorNotFound
}
// Remove a CAPTCHA from a database.
func (imcdb *InMemoryCaptchaDB) Remove(id captcha.ID) error {
imcdb.Lock()
defer imcdb.Unlock()
if _, ok := imcdb.db[id]; ok {
delete(imcdb.db, id)
return nil
}
return captcha.ErrorNotFound
}
// cleanExpired removes expired CAPTCHAs in a loop.
func (imcdb *InMemoryCaptchaDB) cleanExpired() {
for {
sleepFor := imcdb.expiryScanInterval - (time.Duration(time.Now().Second()) % imcdb.expiryScanInterval)
time.Sleep(sleepFor)
imcdb.Lock()
for id, captcha := range imcdb.db {
if time.Since(captcha.Expiry()) >= imcdb.expiry {
delete(imcdb.db, id)
}
}
imcdb.Unlock()
}
}
// An instance of InMemoryCaptchaDB
var imcdb = NewInMemoryCaptchaDB(captcha.DefaultExpiredScanInterval)
func GetExpiry() time.Duration {
return imcdb.GetExpiry()
}
func SetExpiry(expiry time.Duration) {
imcdb.SetExpiry(expiry)
}
func New(data string, captcha captcha.Captcha) (captcha.Captcha, captcha.ID) {
return imcdb.New(data, captcha)
}
func Image(id captcha.ID, style string) (*image.Image, error) {
return imcdb.Image(id, style)
}
func Solve(id captcha.ID, answer captcha.Answer) (bool, error) {
return imcdb.Solve(id, answer)
}
func IsSolved(id captcha.ID) (bool, error) {
return imcdb.IsSolved(id)
}
func Remove(id captcha.ID) error {
return imcdb.Remove(id)
}