GoCaptcha

repository·master·Indexed 25 days ago

https://github.com/wenlng/go-captcha

A modular and highly customizable behavioral CAPTCHA library for Golang. It provides multiple interactive CAPTCHA types to prevent automated bot interactions, including Click (text and graphic modes), Slide (basic and drag-drop modes), Drag-Drop, and Rotate. The library supports flexible configuration of image sizes, transparency, and random ranges, and provides utilities for exporting image data as JPEG or PNG in raw bytes or Base64 formats.

Tokens
7.1K
Snippets
4
Records
30
Agent score
32%

What's inside go-captcha

  1. Overview of GoCaptcha

    master

    GoCaptcha is a powerful, modular, and highly customizable behavioral CAPTCHA library for Golang. It supports multiple interactive CAPTCHA types designed to adapt to different user interaction scenarios.

    Supported CAPTCHA Types:

    • Click (点选): Users click specified points or characters on a main image. Supports both text and graphic modes.
    • Slide (滑动): Users slide a puzzle piece to the correct position on a main image.
    • Drag-Drop (拖拽): A variant of the slide CAPTCHA that allows users to drag the puzzle piece within a larger range to the target position.
    • Rotate (旋转): Users rotate a thumbnail to align its angle with the main image.
  2. Overview of GoCaptcha CAPTCHA types

    master

    GoCaptcha supports four distinct behavioral CAPTCHA types, each with different interaction models:

    1. Click CAPTCHA: Users click specified points or characters on the main image. It supports both text and graphic modes.
    2. Slide CAPTCHA: Users slide a puzzle piece to the correct position on the main image. It supports basic and drag-drop modes.
    3. Drag-Drop CAPTCHA: A variant of the Slide CAPTCHA where users drag a puzzle piece to a target position within a larger range.
    4. Rotate CAPTCHA: Users rotate a thumbnail to align its angle with the main image.
  3. Use Slide/Drag-Drop CAPTCHA

    master

    Slide/Drag-Drop CAPTCHA requires users to move a puzzle piece to the correct position in a main image. It supports two modes:

    1. Basic Mode: The puzzle piece slides along a fixed Y-axis. Use builder.Make() to create this.
    2. Drag-Drop Mode: The puzzle piece can move freely within a larger area. Use builder.MakeDragDrop() to create this.

    Workflow

    1. Generate Master Image (masterImage): Contains the gap and shadow effects (usually JPEG).
    2. Generate Tile Image (tileImage): The piece the user slides (usually PNG).
    3. User Interaction: The frontend captures the final coordinates (TileX, TileY).
    4. Verification: The backend compares the user's position with the target position.
    package main
    
    import (
    	"encoding/json"
    	"fmt"
    	"image"
    	"log"
    	"io/ioutil"
    
    	"github.com/wenlng/go-captcha/v2/base/option"
    	"github.com/wenlng/go-captcha/v2/slide"
    	"github.com/wenlng/go-captcha/v2/base/codec"
    )
    
    var slideTileCapt slide.Captcha
    
    func init() {
    	builder := slide.NewBuilder()
    
    	bgImage, err := loadPng("../resources/bg.png")
    	if err != nil {
    		log.Fatalln(err)
    	}
    
    	bgImage1, err := loadPng("../resources/bg1.png")
    	if err != nil {
    		log.Fatalln(err)
    	}
    
    	graphs := getSlideTileGraphArr()
    
    	builder.SetResources(
    		slide.WithGraphImages(graphs),
    		slide.WithBackgrounds([]image.Image{
    			bgImage,
    			bgImage1,
    		}),
    	)
    
    	slideTileCapt = builder.Make()
    }
    
    func getSlideTileGraphArr() []*slide.GraphImage {
    	tileImage1, err := loadPng("../resources/tile-1.png")
    	if err != nil {
    		log.Fatalln(err)
    	}
    
    	tileShadowImage1, err := loadPng("../resources/tile-shadow-1.png")
    	if err != nil {
    		log.Fatalln(err)
    	}
    
    	tileMaskImage1, err := loadPng("../resources/tile-mask-1.png")
    	if err != nil {
    		log.Fatalln(err)
    	}
    
    	return []*slide.GraphImage{
    		{
    			OverlayImage: tileImage1,
    			ShadowImage:  tileShadowImage1,
    			MaskImage:    tileMaskImage1,
    		},
    	}
    }
    
    func main() {
    	captData, err := slideTileCapt.Generate()
    	if err != nil {
    		log.Fatalln(err)
    	}
    
    	blockData := captData.GetData()
    	if blockData == nil {
    		log.Fatalln(">>>>> generate err")
    	}
    
    	block, _ := json.Marshal(blockData)
    	fmt.Println(">>>>>", string(block))
    
    	var mBase64, tBase64 string
    	mBase64, err = captData.GetMasterImage().ToBase64()
    	if err != nil {
    		fmt.Println(err)
    	}
    	tBase64, err = captData.GetTileImage().ToBase64()
    	if err != nil {
    		fmt.Println(err)
    	}
    
    	fmt.Println(">>>>> ", mBase64)
    	fmt.Println(">>>>> ", tBase64)
    }
    
    func loadPng(p string) (image.Image, error) {
    	imgBytes, err := ioutil.ReadFile(p)
    	if err != nil {
    		return nil, err
    	}
    	return codec.DecodeByteToPng(imgBytes)
    }
  4. How Click CAPTCHA works

    master

    Click CAPTCHA requires users to click specific points or characters within a main image. It supports two modes:

    1. Text Mode: Displays characters (letters, numbers, or Chinese characters) that the user must click.
    2. Graphic Mode: Displays icons or shapes that the user must click.

    Workflow

    1. Generate Master Image (masterImage): A JPEG containing randomly distributed points or characters.
    2. Generate Thumbnail (thumbImage): A PNG showing the target points or characters to be clicked.
    3. User Interaction: The user clicks coordinates on the master image; the frontend captures these and sends them to the backend.
    4. Verification: The backend compares the user's clicked coordinates against the target coordinates (dots).
  5. Use Rotate CAPTCHA

    master

    The Rotate CAPTCHA requires users to rotate a thumbnail to align with the main image's angle.

    Workflow

    1. Backend: Use rotate.NewBuilder() to configure background images and call .Make() to create an instance.
    2. Generation: Call capt.Generate() to get CaptchaData. This contains the masterImage (rotated background) and the thumbImage (circularly cropped thumbnail).
    3. Frontend: Display images and capture the user's rotation angle.
    4. Verification: Use rotate.Validate(srcAngle, angle, paddingValue) to compare the user's angle against the target angle.

    Configuration Options

    OptionDescription
    rotate.WithImageSquareSize(val int)Set main image size (default 220x220)
    rotate.WithRangeAnglePos(vals []option.RangeVal)Set range for random verification angles
    rotate.WithRangeThumbImageSquareSize(val []int)Set thumbnail size
    rotate.WithThumbImageAlpha(val float32)Set thumbnail transparency

    Resource Options

    OptionDescription
    rotate.WithImages([]image.Image)Set main image backgrounds
  6. Configure Go Proxy for installation

    master

    If you encounter issues downloading modules, you may need to set your Go proxy settings.

    Windows:

    $ set GO111MODULE=on
    $ set GOPROXY=https://goproxy.io,direct
    
    # Or for Golang 1.13+
    $ go env -w GO111MODULE=on
    $ go env -w GOPROXY=https://goproxy.io,direct

    Linux or Mac:

    $ export GO111MODULE=on
    $ export GOPROXY=https://goproxy.io,direct
    
    # Or persist in profile
    $ echo "export GO111MODULE=on" >> ~/.profile
    $ echo "export GOPROXY=https://goproxy.cn,direct" >> ~/.profile
    $ source ~/.profile
  7. Import specific CAPTCHA modules on demand

    master
    GoCaptcha is designed to be modular. Instead of importing the entire library, you should import only the specific module required for the CAPTCHA type you are implementing to keep your binary size small.
  8. Import GoCaptcha modules

    master

    GoCaptcha is designed for modular usage. Instead of importing the entire library, you should import only the specific CAPTCHA type module you need to keep your binary size optimized. Replace ${click|slide|rotate} with the desired module name:

    • click for Click CAPTCHA
    • slide for Slide CAPTCHA
    • rotate for Rotate CAPTCHA
    package main
    
    // Import modules on demand
    import "github.com/wenlng/go-captcha/v2/${click|slide|rotate}"
    
    func main(){
       // ...
    }
  9. Use Slide or Drag-Drop CAPTCHA

    master

    The Slide CAPTCHA requires users to move a puzzle piece to a target position. It offers two modes:

    1. Basic Mode: The puzzle piece slides along a fixed Y-axis.
    2. Drag-Drop Mode: The puzzle piece can be freely dragged within a larger range.

    Workflow

    1. Backend: Use slide.NewBuilder() to configure resources (backgrounds and puzzle graphics) and call .Make() or .MakeDragDrop() to create an instance.
    2. Generation: Call capt.Generate() to get CaptchaData. This contains the masterImage (background with notch), tileImage (the puzzle piece), and the verification Block data.
    3. Frontend: Display the images and capture the user's final TileX and TileY coordinates.
    4. Verification: Use slide.Validate(srcX, srcY, X, Y, paddingValue) to check if the user's position matches the target.
  10. Set resources for Slide/Drag-Drop CAPTCHA

    master

    Use builder.SetResources(slide.WithXxx(), ...) to provide the necessary image assets.

    Resource Options

    OptionDescription
    slide.WithBackgrounds([]image.Image)Set master image backgrounds
    slide.WithGraphImages(images []*GraphImage)Set the graph images for the tile