recaptcha

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Sep 4, 2019 License: GPL-3.0 Imports: 10 Imported by: 0

README

recaptcha

Build Status Go Report Card GoDoc license

A client library for contacting the reCAPTCHA v3 token verification endpoint and validating the response.

This project is not associated with Google or the reCAPTCHA project.

Usage

See godoc for more information, or see the example directory for a complete working example.

// Clients are threadsafe, and should normally be created once and reused
// throughout the life of your application.
client := recaptcha.NewClient("my_secret")

// Fetch the token verification response from the reCAPTCHA endpoint.  The
// userIP is optional, and can be omitted from the request by passing an
// empty string.
response, err := client.Fetch(context.Background(), "token", "user_ip")
if err != nil {
    fmt.Printf("Error making request to reCAPTCHA endpoint: %s\n", err)
}

// Verify the response, with additional optional verification criteria.
// Verifying the hostname and action is strongly recommended, at a minimum.
if err := response.Verify(
    recaptcha.Hostname("my_hostname"),
    recaptcha.Action("my_action"),
    recaptcha.Score(.5),
); err != nil {
    fmt.Printf("Token is invalid: %s\n", err)
} else {
    fmt.Println("Token is valid")
}

License

Copyright (c) 2019 Niche.com, Inc.

This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program. If not, see https://www.gnu.org/licenses/.

Documentation

Overview

Package recaptcha provides functionality for hitting the reCAPTCHA v3 verification endpoint and verifying the response. By default, it simply verifies that the response's "success" field is true, and that the "error-codes" field is empty. Additional optional verification criteria can be provided when calling Verify to ensure, for example, that the correct hostname and action were returned. See the package-level example for a demonstration of how to use the package.

More information about reCAPTCHA v3 can be found here: https://developers.google.com/recaptcha/docs/v3

Example
package main

import (
	"context"
	"fmt"

	"github.com/nicheinc/recaptcha"
)

func main() {
	// Clients are threadsafe, and should normally be created once and reused
	// throughout the life of your application.
	client := recaptcha.NewClient("my_secret")

	// Fetch the token verification response from the reCAPTCHA endpoint.  The
	// userIP is optional, and can be omitted from the request by passing an
	// empty string.
	response, err := client.Fetch(context.Background(), "token", "user_ip")
	if err != nil {
		fmt.Printf("Error making request to reCAPTCHA endpoint: %s\n", err)
	}

	// Verify the response, with additional optional verification criteria.
	// Verifying the hostname and action is strongly recommended, at a minimum.
	if err := response.Verify(
		recaptcha.Hostname("my_hostname"),
		recaptcha.Action("my_action"),
		recaptcha.Score(.5),
	); err != nil {
		fmt.Printf("Token is invalid: %s\n", err)
	} else {
		fmt.Println("Token is valid")
	}
}
Output:

Index

Examples

Constants

View Source
const DefaultURL = "https://www.google.com/recaptcha/api/siteverify"

DefaultURL is the default reCAPTCHA verification endpoint URL. This can be overridden via the SetURL option.

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

type Client interface {
	Fetch(ctx context.Context, token, userIP string) (Response, error)
}

Client for making requests to the reCAPTCHA verification endpoint and receiving token verification responses. Created with NewClient.

func NewClient

func NewClient(secret string, opts ...Option) Client

NewClient creates an instance of Client, which is thread-safe and should be reused instead of created as needed. You must provided your website's secret key, which is shared between your site and reCAPTCHA. Additional configuration options may also be provided (e.g. SetHTTPClient, SetURL).

type Criterion

type Criterion func(r *Response) error

Criterion is an optional token verification criterion that can be applied when a token is verified via the Verify method.

func Action

func Action(actions ...string) Criterion

Action is an optional verification criterion which ensures that the website action associated with the reCAPTCHA matches one of the provided actions. Returns *InvalidActionError if the action is not correct.

func ChallengeTs

func ChallengeTs(window time.Duration) Criterion

ChallengeTs is an optional verification criterion which ensures that the response token is being used within the specified window of time from when the reCAPTCHA was presented. By default, the reCAPTCHA verification endpoint only considers a token valid for 2 minutes, so this method is only necessary if you want to enforce an narrower window than that. Returns *InvalidChallengeTsError if the challenge timestamp is outside the valid window.

func Hostname

func Hostname(hostnames ...string) Criterion

Hostname is an optional verification criterion which ensures that the hostname of the website where the reCAPTCHA was presented matches one of the provided hostnames. Returns *InvalidHostnameError if the hostname is not correct.

func Score

func Score(threshold float64) Criterion

Score is an optional verification criterion which ensures that the score associated with the reCAPTCHA meets the minimum threshold. Returns *InvalidScoreError if the score is below the threshold.

type HTTPClient

type HTTPClient interface {
	Do(req *http.Request) (*http.Response, error)
}

HTTPClient is a basic interface for an HTTP client, as required by the SetHTTPClient function. The standard *http.Client satisfies this interface.

type InvalidActionError

type InvalidActionError struct {
	Action string
}

InvalidActionError is returned from Verify if the Action criterion is provided and the response's "action" field does not correspond to the expected action.

func (*InvalidActionError) Error

func (e *InvalidActionError) Error() string

type InvalidChallengeTsError

type InvalidChallengeTsError struct {
	ChallengeTs time.Time
	Diff        time.Duration
}

InvalidChallengeTsError is returned from Verify if the ChallengeTs criterion is provided and the response's "challenge_ts" field falls outside the valid window.

func (*InvalidChallengeTsError) Error

func (e *InvalidChallengeTsError) Error() string

type InvalidHostnameError

type InvalidHostnameError struct {
	Hostname string
}

InvalidHostnameError is returned from Verify if the Hostname criterion is provided and the response's "hostname" field does not correspond to the expected hostname.

func (*InvalidHostnameError) Error

func (e *InvalidHostnameError) Error() string

type InvalidScoreError

type InvalidScoreError struct {
	Score float64
}

InvalidScoreError is returned from Verify if the Score criterion is provided and the response's "score" field is below the minimum threshold.

func (*InvalidScoreError) Error

func (e *InvalidScoreError) Error() string

type Mock

type Mock struct {
	FetchStub   func(ctx context.Context, token string, userIP string) (Response, error)
	FetchCalled int32
}

Mock implements the Client interface, with a stubbed Fetch method for use in testing.

func (*Mock) Fetch

func (m *Mock) Fetch(ctx context.Context, token string, userIP string) (Response, error)

Fetch calls FetchStub with the provided parameters and returns the result.

type Option

type Option func(c *client)

Option represents a configuration option that can be applied when creating a Client via the NewClient method. See SetHTTPClient and SetURL functions.

func SetHTTPClient

func SetHTTPClient(httpClient HTTPClient) Option

SetHTTPClient is an option for creating a Client with a custom *http.Client. If not provided, the Client will use http.DefaultClient.

func SetURL

func SetURL(url string) Option

SetURL is an option for creating a Client that hits a custom verification URL. If not provided, the Client will use DefaultURL.

type Response

type Response struct {
	Success     bool      `json:"success"`
	Score       float64   `json:"score"`
	Action      string    `json:"action"`
	ChallengeTs time.Time `json:"challenge_ts"`
	Hostname    string    `json:"hostname"`
	ErrorCodes  []string  `json:"error-codes"`
}

Response represents a response from the reCAPTCHA token verification endpoint. The validity of the token can be verified via the Verify method.

func (*Response) Verify

func (r *Response) Verify(criteria ...Criterion) error

Verify checks whether the response represents a valid token. It returns an error if the token is invalid (i.e. if Success is false or ErrorCodes is non-empty). Typically, the error will be of type *VerificationError. However, if additional optional verification criteria are provided, their respective error types may be returned as well.

type VerificationError

type VerificationError struct {
	ErrorCodes []string
}

VerificationError is returned from Verify when the response's "success" field is false or the "error-codes" field is non-empty. This is the only error the can be returned from Verify if no additional verification criteria are provided.

func (*VerificationError) Error

func (e *VerificationError) Error() string

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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