Install the package, protect a first form with a session captcha, and add a keyed captcha for an API.
Before you start
- An application key. Answers are checked against an HMAC keyed with
APP_KEY, so the application needs one (go run . key:generate). - A shared cache store. Challenges live in the cache, which must be shared by every process: Redis, or
the database cache on Postgres or on a SQLite file of its own. The package refuses to start on a store that
can't keep challenges safely. For a single process, such as local development or tests, the default
memorystore works withCAPTCHA_SINGLE_PROCESS=true. See Configuration.
Install
go get github.com/bowerbird-si/laravel-go-captcha
Add the package to your application:
// bootstrap/app.go
Packages: []laravel.Package{
captcha.New(),
},
That registers two routes:
GET /captcha/{profile}: a session captcha image, for server-rendered forms. It runs in thewebmiddleware group, because the challenge is tied to the session.GET /captcha/api/{profile}: a keyed captcha for APIs and single-page apps. It returns JSON{"sensitive", "key", "img"}and doesn't use the session.
The profile is optional and defaults to default. The five profiles mews/captcha ships are there:
default, flat, mini, inverse and math. Like PHP's, the shipped math profile draws nine
characters; a profile only asks for a sum when you set Math = true.
A session form
Show the image and an input in your template:
<img src="{{captchaSrc "default"}}" alt="Security code">
<input name="captcha" autocomplete="off">
Check the answer with the captcha.Rule validation rule. It needs the request, so build it in the form's
Rules(r *web.Request) method:
type ContactForm struct {
Message string `json:"message"`
Captcha string `json:"captcha"`
}
func (f *ContactForm) Rules(r *web.Request) (validation.Rules, error) {
return validation.For(f,
rule.Field(&f.Message, rule.Required),
rule.Field(&f.Captcha, rule.Required, captcha.Rule(r)),
), nil
}
A correct answer passes once. Reusing it, a wrong answer, an expired challenge or a challenge for another
profile all fail with "The captcha is incorrect." (the message names the field). The rule fails a missing
or empty answer even without rule.Required.
For another profile, name it in both places: {{captchaSrc "flat"}} and captcha.Rule(r).Profile("flat").
A keyed form for an API
The client fetches GET /captcha/api/default, shows img (a data URI), and sends the answer back with
key:
type KeyedForm struct {
Captcha string `json:"captcha"`
CaptchaKey string `json:"captcha_key"`
}
func (f *KeyedForm) Rules() validation.Rules {
return validation.For(f, rule.Field(&f.Captcha, rule.Required, captcha.Keyed()))
}
captcha.Keyed() reads the challenge id from the captcha_key field; captcha.KeyedWith(key) takes an
id the handler already has. The key is an opaque random id: nothing the client receives can check a guess.
A keyed form rendered by the server
Issue the challenge in the handler and mark the page as not cacheable, so a cached page can't hand one challenge to many visitors:
func contact(r *web.Request) *web.Response {
ch, err := captcha.Issue(r, "default")
if err != nil {
return web.Fail(err)
}
return ch.NoStore(web.View("contact", ContactPage{Captcha: ch}))
}<form method="POST">{{csrfField}}{{captchaField .Captcha}}<input name="captcha"></form>Checking in code
The session challenge, profile default:
ok, err := captcha.Check(r, value)
The session challenge of another profile:
ok, err := captcha.Check(r, value, captcha.WithProfile("flat"))
A keyed challenge:
ok, err := captcha.CheckKey(r, key, value, "default")
An error means the check couldn't run, for example because the store didn't answer. Treat it as a failed
captcha. captcha.ErrTooManyFailures means the client gave too many wrong answers this minute, and
captcha.ErrContended that the challenge kept changing while it was checked; both can be shown as "try
again".
For more detail, ask the package for the verdict:
v, err := captcha.From(r).CheckSession(r, value)
switch v.Kind {
case captcha.Passed:
case captcha.Wrong: // v.Remaining attempts are left, or -1 when unlimited
case captcha.Expired, captcha.Exhausted, captcha.Missing, captcha.ProfileMismatch:
}
CheckKeyed does the same for a keyed challenge.