Compare commits

...

29 Commits

Author SHA1 Message Date
Alexander Andreev 455999a9d5
Added /v2 in module name. 2023-08-12 22:39:42 +04:00
Alexander Andreev dede76d13e
Simplified file structure. 2023-08-12 22:29:01 +04:00
Alexander Andreev ce1df27e3a
Removed code for a standalone executable. go min ver was downgraded to 1.12. 2023-08-12 22:23:52 +04:00
Alexander Andreev 4d9daca977
In README.md removed version. 2023-08-12 22:12:49 +04:00
Alexander Andreev 310dfb0fe9
Updated dependencies. 2023-08-12 22:12:05 +04:00
Alexander Andreev 406fb66c17
A little change to pkgdesc. Removed unused fields. Pass a VERSION var to make. Added a v prefix for tag and made use of pkgver. pkgrel was incremented. 2023-05-06 04:52:25 +04:00
Alexander Andreev 918fb18d22
Added a VERSION variable in Makefile. 2023-05-06 04:50:32 +04:00
Alexander Andreev a5f46d9187
A little update for README.md. 2023-05-06 04:49:57 +04:00
Alexander Andreev 352576385b
Removed bin/ dir. 2023-03-05 00:32:26 +04:00
Alexander Andreev e8129849c8
Version was up to 2.0.2. 2023-03-05 00:31:07 +04:00
Alexander Andreev 7c513f9f24
Updated golang.org/x/image dependency to v0.5.0. 2023-03-05 00:30:50 +04:00
Alexander Andreev 5a16c4d678
InMemoryCaptchaDB was renamed to InMemoryDB. 2023-03-05 00:30:24 +04:00
Alexander Andreev fe2c3c8e59
CaptchaDB interface was renamed to DB. 2023-03-05 00:29:44 +04:00
Alexander Andreev 0311a391ed
Replace arav.top with arav.su. 2023-03-05 00:18:52 +04:00
Alexander Andreev 4f254db2bb
Added tests for InMemoryCaptchaDB and DwellingCaptcha. 2023-01-12 04:42:23 +04:00
Alexander Andreev e26bdd64f5
Added more comments. 2023-01-12 04:41:09 +04:00
Alexander Andreev f3e68f4c41
Added missing expiry changing. 2023-01-12 04:40:54 +04:00
Alexander Andreev f9154ab02f
Removed unnecessary guard around delete(). 2023-01-12 04:39:22 +04:00
Alexander Andreev fcb656d4ea
Module name was changet to git.arav.top/Arav/justcaptcha. 2023-01-08 18:49:33 +04:00
Alexander Andreev 9bb80f1f6c
Version updated to 2.0.1. No drastic changes were made. Internal cleaning. Hope it is ready to be correctly used as a library. 2023-01-08 18:36:39 +04:00
Alexander Andreev ee93284cdc
Added a library usage example in README. 2023-01-08 18:34:35 +04:00
Alexander Andreev 073384cc34
ExpiryDate() func was being used in just one place, so it was removed. 2023-01-08 18:21:46 +04:00
Alexander Andreev 6ab62fc43b
getURLParam() was made into a private module func. 2023-01-08 17:53:13 +04:00
Alexander Andreev ea9877f6c4
HTTP server and handlers were restructurised. 2023-01-08 17:49:03 +04:00
Alexander Andreev 49a64f553e
README updated. 2023-01-08 17:38:51 +04:00
Alexander Andreev 275e3c500b
Dependency update. 2023-01-08 17:32:31 +04:00
Alexander Andreev e4225db960
Changed defaults. Now expiry is 10 minutes and socket named just as sock. 2023-01-08 17:04:20 +04:00
Alexander Andreev b91c24998a
SystemD service moved out to the root of init dir and renamed to systemd.service. 2023-01-08 17:02:43 +04:00
Alexander Andreev d7599bdf46
HTTP server moved to internal. DwellingCaptcha moved to pkg. 2023-01-08 17:00:19 +04:00
17 changed files with 150 additions and 456 deletions

View File

@ -1,6 +1,6 @@
The MIT License
Copyright (c) 2022 Alexander "Arav" Andreev <me@arav.top>
Copyright (c) 2022,2023 Alexander "Arav" Andreev <me@arav.su>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal

View File

@ -1,31 +0,0 @@
PACKAGE_NAME=justcaptcha
TARGET=${PACKAGE_NAME}d
SYSCTL=${shell which systemctl}
SYSDDIR_=${shell pkg-config systemd --variable=systemdsystemunitdir}
SYSDDIR=${SYSDDIR_:/%=%}
DESTDIR=/
LDFLAGS=-ldflags "-s -w -X main.version=2.0.0" -tags osusergo,netgo
all: ${TARGET}
.PHONY: ${TARGET}
${TARGET}:
go build -o bin/$@ ${LDFLAGS} cmd/$@/main.go
run:
bin/${TARGET} -expiry 1m -listen 127.0.0.1:19134
install:
install -Dm 0755 bin/${TARGET} ${DESTDIR}usr/bin/${TARGET}
install -Dm 0644 LICENSE ${DESTDIR}usr/share/licenses/${PACKAGE_NAME}/LICENSE
install -Dm 0644 init/systemd/${PACKAGE_NAME}.service ${DESTDIR}${SYSDDIR}/${PACKAGE_NAME}.service
uninstall:
rm ${DESTDIR}usr/bin/${TARGET}
rm ${DESTDIR}usr/share/licenses/${PACKAGE_NAME}/LICENSE
rm ${DESTDIR}${SYSDDIR}/${PACKAGE_NAME}.service

112
README.md
View File

@ -1,98 +1,36 @@
justcaptcha ver. 2.0.0
======================
justcaptcha
===========
A simple CAPTCHA service implementation.
A simple CAPTCHA implementation.
## Usage
An example using built-in "dwelling" implementation.
justcaptchad -expiry 5m -listen /var/run/justcaptcha/c.sock
Create a new CAPTCHA:
`-expiry` takes time for CAPTCHA to be valid for in format X{s,m,h}.
c := dwcaptcha.NewDwellingCaptcha(expiry)
_, id := inmemdb.New(someAdditionalDataUsedInIDGenerationUsuallyIPAddr, c)
`-listen` is `ip:port` or `/path/to/unix.sock` to listen on.
Get an image for a CAPTCHA:
## API
i := inmemdb.Image(captchaID, captchaStyle)
if i == nil {
... // do something if there was no image returned
}
### Errors
jpeg.Encode(w, *i, &jpeg.Options{Quality: 20})
All error codes are returned with an error message in `text/plain`.
Solve a CAPTCHA:
### Create a new CAPTCHA
if ok := inmemdb.Solve(captchaID, answer); !ok {
... // not solved
}
// solved
...
POST /
Check is CAPTCHA was solved:
It will return an ID of a new CAPTCHA in `text/plain`.
#### HTTP codes
- `201` if created (always being created)
### Get an image for a CAPTCHA
GET /:captcha_id/image?style=
Responds with an image in JPEG format (`image/jpeg`).
An optional URL parameter `style=` set a name of a CAPTCHA style if it is
implemented by used CAPTCHA implementation.
#### HTTP codes
- `200` if exists
- `404` if doesn't exist
- `500` if for some reason an image wasn't created
### Submit an answer
POST /:captcha_id
Accepts `application/x-www-form-urlencoded` content type.
It takes one parameter `answer=123456`.
Responds with an empty body and one of the HTTP codes.
#### HTTP codes
- `202` if solved
- `403` if not solved
### Check if captcha is solved
GET /:captcha_id?remove
Responds with an empty body and one of the HTTP codes.
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.
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 or leaving a page.
#### HTTP codes
- `204` if solved
- `403` if not solved
### 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
if ok := inmemdb.IsSolved(captchaID); !ok {
... // not solved
}
// solved
...

View File

View File

@ -1,30 +0,0 @@
# Maintainer: Alexander "Arav" Andreev <me@arav.top>
pkgname=justcaptcha
pkgver=2.0.0
pkgrel=1
pkgdesc="Just a CAPTCHA service"
arch=('i686' 'x86_64' 'arm' 'armv6h' 'armv7h' 'aarch64')
url="https://git.arav.top/Arav/justcaptcha"
license=('MIT')
groups=()
depends=()
makedepends=('go')
provides=('justcaptcha')
conflicts=('justcaptcha')
replaces=()
backup=()
options=()
install=
source=('https://git.arav.top/Arav/justcaptcha/archive/2.0.0.tar.gz')
noextract=()
md5sums=('SKIP')
build() {
cd "$srcdir/$pkgname"
make DESTDIR="$pkgdir/"
}
package() {
cd "$srcdir/$pkgname"
make DESTDIR="$pkgdir/" install
}

View File

@ -45,7 +45,7 @@ type BaseCaptcha struct {
func NewBaseCaptcha(expiry time.Duration) *BaseCaptcha {
return &BaseCaptcha{
expiry: ExpiryDate(expiry),
expiry: time.Now().Add(expiry),
}
}
@ -72,9 +72,3 @@ func (c *BaseCaptcha) IsSolved() bool {
func (c *BaseCaptcha) Expiry() time.Time {
return c.expiry
}
// ExpiryDate returns a date when CAPTCHA expires. It adds a passed
// expiry duration to a current time.
func ExpiryDate(expiry time.Duration) time.Time {
return time.Now().Add(expiry)
}

View File

@ -1,69 +0,0 @@
package main
import (
"flag"
"fmt"
"justcaptcha/internal/handlers"
"justcaptcha/pkg/server"
"log"
"net/netip"
"os"
"os/signal"
"strings"
"syscall"
"time"
)
var version string
var listenAddress *string = flag.String("listen", "/var/run/justcaptcha/c.sock", "listen address (ip:port|unix_path)")
var captchaExpiry *time.Duration = flag.Duration("expiry", 5*time.Minute, "CAPTCHA expiry in format XX{s,m,h}, e.g. 5m, 300s")
var showVersion *bool = flag.Bool("v", false, "show version")
func main() {
flag.Parse()
log.SetFlags(0)
if *showVersion {
fmt.Println("justcaptchad ver.", version, "\nCopyright (c) 2022 Alexander \"Arav\" Andreev <me@arav.top>")
return
}
hand := handlers.New(*captchaExpiry)
srv := server.NewHttpServer()
srv.POST("/", hand.New)
srv.POST("/:captcha", hand.Solve)
srv.GET("/:captcha", hand.IsSolved)
srv.GET("/:captcha/image", hand.Image)
var network string
if !strings.ContainsRune(*listenAddress, ':') {
network = "unix"
defer os.Remove(*listenAddress)
} else {
ap, err := netip.ParseAddrPort(*listenAddress)
if err != nil {
log.Fatalln(err)
}
if ap.Addr().Is4() {
network = "tcp4"
} else if ap.Addr().Is6() {
network = "tcp6"
}
}
if err := srv.Start(network, *listenAddress); err != nil {
log.Fatalln("failed to start a server:", err)
}
doneSignal := make(chan os.Signal, 1)
signal.Notify(doneSignal, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
<-doneSignal
if err := srv.Stop(); err != nil {
log.Fatalln("failed to properly shutdown a server:", err)
}
}

View File

@ -30,8 +30,8 @@ func NewID(additionalData string, answer Answer) ID {
return ID(base64.RawURLEncoding.EncodeToString(idHash.Sum(nil)))
}
// CaptchaDB interface with all necessary methods.
type CaptchaDB interface {
// DB interface with all necessary methods.
type DB interface {
New(data string, captcha Captcha) (Captcha, ID)
GetExpiry() time.Duration
SetExpiry(expiry time.Duration)

View File

@ -0,0 +1,30 @@
package dwcaptcha_test
import (
"testing"
"time"
"git.arav.su/Arav/justcaptcha/v2/dwcaptcha"
)
const expiry = 10 * time.Minute
func TestCaptcha(t *testing.T) {
captcha := dwcaptcha.NewDwellingCaptcha(expiry)
if diff := time.Until(captcha.Expiry()) - expiry; diff >= 1*time.Microsecond {
t.Errorf("Difference %s is more than 1 microsecond", diff.String())
}
if captcha.Image("") == nil {
t.Error("image cannot be nil, but it is!")
}
if !captcha.Solve(captcha.Answer()) {
t.Error("for whatever reason, its own answer doesn't match itself O_O")
}
if !captcha.IsSolved() {
t.Error("after last test it should be true, but it is not!")
}
}

View File

@ -2,10 +2,11 @@ package dwcaptcha
import (
"image"
"justcaptcha/pkg/captcha"
"math/rand"
"time"
captcha "git.arav.su/Arav/justcaptcha/v2"
"github.com/fogleman/gg"
)

11
go.mod
View File

@ -1,13 +1,10 @@
module justcaptcha
module git.arav.su/Arav/justcaptcha/v2
go 1.19
go 1.12
require (
github.com/fogleman/gg v1.3.0
github.com/julienschmidt/httprouter v1.3.0
)
require github.com/fogleman/gg v1.3.0
require (
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 // indirect
golang.org/x/image v0.1.0 // indirect
golang.org/x/image v0.11.0 // indirect
)

15
go.sum
View File

@ -2,31 +2,36 @@ github.com/fogleman/gg v1.3.0 h1:/7zJX8F6AaYQc57WQCyN9cAIz+4bCJGO9B+dyW29am8=
github.com/fogleman/gg v1.3.0/go.mod h1:R/bRT+9gY/C5z7JzPU0zXsXHKM4/ayA+zqcVNZzPa1k=
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 h1:DACJavvAHhabrF08vX0COfcOBJRhZ8lUbR+ZWIs0Y5g=
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=
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/image v0.11.0 h1:ds2RoQvBvYTiJkwpSFDwCcDFNX7DqjL2WsUgTNk0Ooo=
golang.org/x/image v0.11.0/go.mod h1:bglhjqbqVuEb9e9+eNR45Jfu7D+T4Qan+NhQk8Ck2P8=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
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/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
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/sync v0.1.0/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/sys v0.5.0/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/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
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/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.12.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
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/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=

View File

@ -1,39 +0,0 @@
[Unit]
Description=A simple CAPTCHA service for your website
After=network.target
[Service]
Type=simple
Restart=on-failure
DynamicUser=yes
ExecStart=/usr/bin/justcaptchad -expiry 5m -listen /var/run/justcaptcha/j.sock
ReadOnlyPaths=/
# Set here path to directory where uploads are stored.
NoExecPaths=/
ExecPaths=/usr/bin/justcaptchad
RuntimeDirectory=justcaptcha
AmbientCapabilities=
CapabilityBoundingSet=
LockPersonality=true
MemoryDenyWriteExecute=true
NoNewPrivileges=true
PrivateDevices=true
ProtectClock=true
ProtectControlGroups=true
ProtectHome=true
ProtectKernelLogs=true
ProtectKernelModules=true
ProtectKernelTunables=true
ProtectSystem=strict
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
RestrictNamespaces=true
RestrictRealtime=true
RestrictSUIDSGID=true
SystemCallArchitectures=native
[Install]
WantedBy=multi-user.target

View File

@ -2,12 +2,14 @@ package inmemdb
import (
"image"
"justcaptcha/pkg/captcha"
"sync"
"time"
captcha "git.arav.su/Arav/justcaptcha/v2"
)
type InMemoryCaptchaDB struct {
// InMemoryDB implementation that lives in a memory (map).
type InMemoryDB struct {
sync.Mutex
db map[captcha.ID]captcha.Captcha
@ -15,10 +17,11 @@ type InMemoryCaptchaDB struct {
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{
// NewInMemoryDB returns an initialised instance of an InMemoryDB.
// An expiry is a scan interval for expired CAPTCHAs (if passed a longer one,
// resets to a default (captcha.DefaultExpiredScanInterval)).
func NewInMemoryDB(expiry time.Duration) *InMemoryDB {
db := &InMemoryDB{
db: make(map[captcha.ID]captcha.Captcha),
expiry: expiry}
@ -33,10 +36,10 @@ func NewInMemoryCaptchaDB(expiry time.Duration) *InMemoryCaptchaDB {
return db
}
// New accepts a CAPTHA instance, generates an ID and store it in a database.
// New accepts a CAPTCHA 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) {
func (imcdb *InMemoryDB) New(data string, cptcha captcha.Captcha) (captcha.Captcha, captcha.ID) {
id := captcha.NewID(data, cptcha.Answer())
imcdb.Lock()
@ -46,13 +49,15 @@ func (imcdb *InMemoryCaptchaDB) New(data string, cptcha captcha.Captcha) (captch
return cptcha, id
}
// GetExpiry returns time for how long CAPTCHA will last.
func (imcdb *InMemoryCaptchaDB) GetExpiry() time.Duration {
// GetExpiry returns an expiry for a CAPTCHA.
func (imcdb *InMemoryDB) GetExpiry() time.Duration {
return imcdb.expiry
}
// SetExpiry changes an expiry duration to a new one.
func (imcdb *InMemoryCaptchaDB) SetExpiry(expiry time.Duration) {
// SetExpiry changes an expiry for a CAPTCHA and a scan interval. Scan interval
// cannot be longer than a default, so if it is, then resets to a default.
func (imcdb *InMemoryDB) SetExpiry(expiry time.Duration) {
imcdb.expiry = expiry
if expiry < captcha.DefaultExpiredScanInterval {
imcdb.expiryScanInterval = expiry
} else {
@ -60,8 +65,9 @@ func (imcdb *InMemoryCaptchaDB) SetExpiry(expiry time.Duration) {
}
}
// Image returns a freshly generated image for a CAPTCHA.
func (imcdb *InMemoryCaptchaDB) Image(id captcha.ID, style string) *image.Image {
// Image returns a freshly generated image for a CAPTCHA with style if
// applicable.
func (imcdb *InMemoryDB) Image(id captcha.ID, style string) *image.Image {
imcdb.Lock()
defer imcdb.Unlock()
if c, ok := imcdb.db[id]; ok {
@ -72,7 +78,7 @@ func (imcdb *InMemoryCaptchaDB) Image(id captcha.ID, style string) *image.Image
// 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 {
func (imcdb *InMemoryDB) Solve(id captcha.ID, answer captcha.Answer) bool {
imcdb.Lock()
defer imcdb.Unlock()
if c, ok := imcdb.db[id]; ok {
@ -87,7 +93,7 @@ func (imcdb *InMemoryCaptchaDB) Solve(id captcha.ID, answer captcha.Answer) bool
// IsSolved checks if CAPTCHA was solved and removes it
// from a database.
func (imcdb *InMemoryCaptchaDB) IsSolved(id captcha.ID) bool {
func (imcdb *InMemoryDB) IsSolved(id captcha.ID) bool {
imcdb.Lock()
defer imcdb.Unlock()
if c, ok := imcdb.db[id]; ok {
@ -98,16 +104,14 @@ func (imcdb *InMemoryCaptchaDB) IsSolved(id captcha.ID) bool {
}
// Remove a CAPTCHA from a database.
func (imcdb *InMemoryCaptchaDB) Remove(id captcha.ID) {
func (imcdb *InMemoryDB) Remove(id captcha.ID) {
imcdb.Lock()
defer imcdb.Unlock()
if _, ok := imcdb.db[id]; ok {
delete(imcdb.db, id)
}
delete(imcdb.db, id)
}
// cleanExpired removes expired CAPTCHAs in a loop.
func (imcdb *InMemoryCaptchaDB) cleanExpired() {
func (imcdb *InMemoryDB) cleanExpired() {
for {
sleepFor := imcdb.expiryScanInterval - (time.Duration(time.Now().Second()) % imcdb.expiryScanInterval)
time.Sleep(sleepFor)
@ -122,9 +126,9 @@ func (imcdb *InMemoryCaptchaDB) cleanExpired() {
}
}
// An instance of InMemoryCaptchaDB
// An instance of InMemoryDB
var imcdb = NewInMemoryCaptchaDB(captcha.DefaultExpiredScanInterval)
var imcdb = NewInMemoryDB(captcha.DefaultExpiredScanInterval)
func GetExpiry() time.Duration {
return imcdb.GetExpiry()

48
inmemdb/inmemdb_test.go Normal file
View File

@ -0,0 +1,48 @@
package inmemdb_test
import (
"testing"
"time"
captcha "git.arav.su/Arav/justcaptcha/v2"
"git.arav.su/Arav/justcaptcha/v2/dwcaptcha"
"git.arav.su/Arav/justcaptcha/v2/inmemdb"
)
const expiry = 10 * time.Minute
const testData = "192.168.0.1"
func TestInMemDBDefaultInstance(t *testing.T) {
if inmemdb.GetExpiry() != captcha.DefaultExpiredScanInterval {
t.Errorf("expiration is different from a default one (%v != %v)",
inmemdb.GetExpiry(), captcha.DefaultExpiredScanInterval)
}
inmemdb.SetExpiry(expiry)
if expiry != inmemdb.GetExpiry() {
t.Errorf("Expected %v, but got %v", expiry, inmemdb.GetExpiry())
}
captcha, captchaID := inmemdb.New(testData, dwcaptcha.NewDwellingCaptcha(expiry))
if inmemdb.Image(captchaID, "") == nil {
t.Error("nil returned instead of an image.Image struct")
}
if !inmemdb.Solve(captchaID, captcha.Answer()) {
t.Error("CAPTCHA not solved. Looks like provided ID wasn't found")
}
if !inmemdb.IsSolved(captchaID) {
t.Error("last test solved a CAPTCHA, but IsSolved() returned false")
}
}
func TestInMemDBNewInstance(t *testing.T) {
db := inmemdb.NewInMemoryDB(expiry)
if db.GetExpiry() != expiry {
t.Errorf("expected expiry %v, but got %v", expiry, db.GetExpiry())
}
}

View File

@ -1,78 +0,0 @@
package handlers
import (
"fmt"
"image/jpeg"
"justcaptcha/internal/dwcaptcha"
"justcaptcha/pkg/captcha"
"justcaptcha/pkg/captcha/inmemdb"
"justcaptcha/pkg/server"
"net/http"
"time"
)
const errMsgWrongAnswer = "An answer provided was wrong"
const errMsgImageNotFound = "cannot get an image for a non-existing CAPTCHA"
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) {
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 := captcha.ID(server.GetURLParam(r, "captcha"))
captchaStyle := r.URL.Query().Get("style")
captchaImage := inmemdb.Image(captchaID, captchaStyle)
if captchaImage == nil {
http.Error(w, errMsgImageNotFound, http.StatusNotFound)
return
}
w.Header().Add("Content-Disposition", "inline; filename=\""+string(captchaID)+"\"")
jpeg.Encode(w, *captchaImage, &jpeg.Options{Quality: 20})
}
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"))
if ok := inmemdb.Solve(captchaID, answer); !ok {
http.Error(w, errMsgWrongAnswer, http.StatusForbidden)
return
}
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")
if isJustRemove {
inmemdb.Remove(captchaID)
w.WriteHeader(http.StatusNoContent)
return
}
if solved := inmemdb.IsSolved(captchaID); !solved {
http.Error(w, errMsgWrongAnswer, http.StatusForbidden)
return
}
w.WriteHeader(http.StatusNoContent)
}

View File

@ -1,76 +0,0 @@
package server
import (
"context"
"log"
"net"
"net/http"
"os"
"time"
"github.com/julienschmidt/httprouter"
)
type HttpServer struct {
server *http.Server
router *httprouter.Router
}
func NewHttpServer() *HttpServer {
r := httprouter.New()
return &HttpServer{
server: &http.Server{
ReadTimeout: 3 * time.Second,
WriteTimeout: 3 * time.Second,
Handler: r,
},
router: r,
}
}
func (s *HttpServer) GET(path string, handler http.HandlerFunc) {
s.router.Handler(http.MethodGet, path, handler)
}
func (s *HttpServer) POST(path string, handler http.HandlerFunc) {
s.router.Handler(http.MethodPost, path, handler)
}
func (s *HttpServer) SetNotFoundHandler(handler http.HandlerFunc) {
s.router.NotFound = handler
}
// GetURLParam wrapper around underlying router for getting URL parameters.
func GetURLParam(r *http.Request, param string) string {
return httprouter.ParamsFromContext(r.Context()).ByName(param)
}
func (s *HttpServer) Start(network, address string) error {
listener, err := net.Listen(network, address)
if err != nil {
return err
}
if listener.Addr().Network() == "unix" {
os.Chmod(address, 0777)
}
go func() {
if err = s.server.Serve(listener); err != nil && err != http.ErrServerClosed {
log.Fatalln(err)
}
}()
return nil
}
func (s *HttpServer) Stop() error {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := s.server.Shutdown(ctx); err != nil {
return err
}
return nil
}