recaptcha

package module
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Mar 2, 2023 License: MIT Imports: 7 Imported by: 2

README

recaptcha

GitHub Workflow Status Codecov GoDoc Sourcegraph

Package recaptcha is a middleware that provides reCAPTCHA integration for Flamego.

Installation

The minimum requirement of Go is 1.18.

go get github.com/flamego/recaptcha

Getting started

<!-- templates/home.tmpl -->
<html>
<head>
  <script src="https://www.google.com/recaptcha/api.js"></script>
</head>
<body>
<script>
  function onSubmit(token) {
    document.getElementById("demo-form").submit();
  }
</script>
<form id="demo-form" method="POST">
  <button class="g-recaptcha"
    data-sitekey="{{.SiteKey}}"
    data-callback='onSubmit'
    data-action='submit'>Submit</button>
</form>
</body>
</html>
package main

import (
	"fmt"
	"net/http"

	"github.com/flamego/flamego"
	"github.com/flamego/recaptcha"
	"github.com/flamego/template"
)

func main() {
	f := flamego.Classic()
	f.Use(template.Templater())
	f.Use(recaptcha.V3(
		recaptcha.Options{
			Secret:    "<SECRET>",
			VerifyURL: recaptcha.VerifyURLGoogle,
		},
	))
	f.Get("/", func(t template.Template, data template.Data) {
		data["SiteKey"] = "<SITE KEY>"
		t.HTML(http.StatusOK, "home")
	})
	f.Post("/", func(w http.ResponseWriter, r *http.Request, re recaptcha.RecaptchaV3) {
		token := r.PostFormValue("g-recaptcha-response")
		resp, err := re.Verify(token)
		if err != nil {
			w.WriteHeader(http.StatusBadRequest)
			_, _ = w.Write([]byte(err.Error()))
			return
		} else if !resp.Success {
			w.WriteHeader(http.StatusBadRequest)
			_, _ = w.Write([]byte(fmt.Sprintf("Verification failed, error codes %v", resp.ErrorCodes)))
			return
		}
		w.WriteHeader(http.StatusOK)
		_, _ = w.Write([]byte("Verified!"))
	})
	f.Run()
}

Getting help

License

This project is under the MIT License. See the LICENSE file for the full license text.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func V2

func V2(opts Options) flamego.Handler

V2 returns a middleware handler that injects recaptcha.RecaptchaV2 into the request context, which is used for verifying reCAPTCHA V2 requests.

func V3

func V3(opts Options) flamego.Handler

V3 returns a middleware handler that injects recaptcha.RecaptchaV3 into the request context, which is used for verifying reCAPTCHA V3 requests.

Types

type Options

type Options struct {
	// Client the HTTP client to make requests. The default is http.DefaultClient.
	Client *http.Client
	// Secret is the secret key to check user captcha codes. This field is required.
	Secret string

	VerifyURL
}

Options contains options for both recaptcha.RecaptchaV2 and recaptcha.RecaptchaV3 middleware.

type RecaptchaV2

type RecaptchaV2 interface {
	// Verify verifies the given token. An optional remote IP of the user may be
	// passed as extra security criteria.
	Verify(token string, remoteIP ...string) (*ResponseV2, error)
}

RecaptchaV2 is a reCAPTCHA V2 verify interface.

type RecaptchaV3

type RecaptchaV3 interface {
	// Verify verifies the given token. An optional remote IP of the user may be
	// passed as extra security criteria.
	Verify(token string, remoteIP ...string) (*ResponseV3, error)
}

RecaptchaV3 is a reCAPTCHA V3 verify interface.

type ResponseV2

type ResponseV2 struct {
	// Success indicates whether the passcode valid, and does it meet security
	// criteria you specified.
	Success bool `json:"success"`
	// ChallengeTS is the timestamp of the challenge load (ISO format
	// yyyy-MM-dd'T'HH:mm:ssZZ).
	ChallengeTS time.Time `json:"challenge_ts"`
	// Hostname is the hostname of the site where the challenge was solved.
	Hostname string `json:"hostname"`
	// ErrorCodes contains the error codes when verify failed.
	ErrorCodes []string `json:"error-codes"`
}

ResponseV2 is the response struct which Google send back to the client.

type ResponseV3

type ResponseV3 struct {
	// Success indicates whether the passcode valid, and does it meet security
	// criteria you specified.
	Success bool `json:"success"`
	// ChallengeTS is the timestamp of the challenge load (ISO format
	// yyyy-MM-dd'T'HH:mm:ssZZ).
	ChallengeTS time.Time `json:"challenge_ts"`
	// Hostname is the hostname of the site where the challenge was solved.
	Hostname string `json:"hostname"`
	// ErrorCodes contains the error codes when verify failed.
	ErrorCodes []string `json:"error-codes"`
	// Score indicates the score of the request (0.0 - 1.0).
	Score float64 `json:"score"`
	// Action is the action name of the request.
	Action string `json:"action"`
}

ResponseV3 is the response struct which Google send back to the client.

type VerifyURL

type VerifyURL string

VerifyURL is the API URL to verify user input.

const (
	// VerifyURLGoogle is the default API URL to verify reCAPTCHA requests.
	VerifyURLGoogle VerifyURL = "https://www.google.com/recaptcha/api/siteverify"

	// VerifyURLGlobal is API URL for the people who can't connect to the Google's server.
	VerifyURLGlobal VerifyURL = "https://www.recaptcha.net/recaptcha/api/siteverify"
)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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