Giter VIP home page Giter VIP logo

go-captcha's Introduction

Go Captcha

Behavior Security Captcha


English | 中文

Go Captcha is a behavior security CAPTCHA, which implements the generation of random verification text and the verification of click position information.

⭐️ If it helps you, please give a star.


Reward Support
Reward Support

Dependency Library

$ go get -u github.com/golang/freetype
$ go get -u golang.org/x/crypto
$ go get -u golang.org/x/image

Install Captcha Module

$ go get -u github.com/wenlng/go-captcha/captcha

Import Captcha Module

package main

import "github.com/wenlng/go-captcha/captcha"

func main(){
   // ...
}

Quick Use

package main
import (
    "fmt"
    "github.com/wenlng/go-captcha/captcha"
)

func main(){
    // Captcha Single Instances
    capt := captcha.GetCaptcha()
    
    // Generate Captcha
    dots, b64, tb64, key, err := capt.Generate()
    if err != nil {
        panic(err)
        return
    }
    
    // Main image base64 code
    fmt.Println(len(b64))
    
    // Thumb image base64 code
    fmt.Println(len(tb64))
    
    // Only key
    fmt.Println(key)
    
    // Dot data For verification
    fmt.Println(dots)
}

Captcha Instances

  • New Instances or Get Single Instances
package main
import (
    "fmt"
    "github.com/wenlng/go-captcha/captcha"
)

func main(){
	// Captcha Instances
    // capt := captcha.NewCaptcha() 
    
    // Captcha Single Instances
    capt := captcha.GetCaptcha()

    // ====================================================
    fmt.Println(capt)

}

Set Configuration

After version v1.2.3, the default size of large drawing is 300×240px, the default size of the small drawing is 150×40px.

Set Chars

Some fonts are attached by default. If other Chinese strings are set, you may need to import a font file.

package main
import (
    "fmt"
    "github.com/wenlng/go-captcha/captcha"
)

func main(){
    capt := captcha.GetCaptcha()
    
    // ====================================================
    // Method: SetRangChars (chars []string) error;
    // Desc: Set random char of captcha
    // ====================================================
    // Letter
    //chars := "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    //_ = capt.SetRangChars(strings.Split(chars, ""))
    
    // Two Letter
    //chars := []string{"HE","CA","WO","NE","HT","IE","PG","GI","CH","CO","DA"}
    //_ = capt.SetRangChars(chars)

    // Chinese Char
    chars := []string{"你","好","呀","这","是","点","击","验","证","码","哟"}
    _ = capt.SetRangChars(chars)

    // ====================================================
    fmt.Println(capt)
}

Set Font File Configuration

You can copy the resource files under the "https://github.com/wenlng/go-captcha-example/tree/main/resources" to the directory of your project.

package main
import (
    "fmt"
    "os"
    "github.com/wenlng/go-captcha/captcha"
)

func main(){
    capt := captcha.GetCaptcha()
    
    path, _ := os.Getwd()    
    // ====================================================
    // Method: SetFont(fonts []string);
    // Desc: Set random font of captcha text
    // ====================================================
    capt.SetFont([]string{
        path + "/__example/resources/fonts/fzshengsksjw_cu.ttf",
    })
}

Set Big Image Configuration

Tip: Some images are attached by default.

package main
import (
    "fmt"
    "golang.org/x/image/font"
    "os"
    "github.com/wenlng/go-captcha/captcha"
)

func main(){
    capt := captcha.GetCaptcha()
    
    path, _ := os.Getwd()    
    // ====================================================
    // Method: SetBackground(color []string);
    // Desc: Set random image of background
    // ====================================================
    capt.SetBackground([]string{
        path + "/__example/resources/images/1.jpg",
        path + "/__example/resources/images/2.jpg",
    })

    // ====================================================
    // Method: SetImageSize(size Size);
    // Desc: Set size of captcha
    // ====================================================
    capt.SetImageSize(captcha.Size{300, 300})

    // ====================================================
    // Method: SetImageQuality(val int);
    // Desc: Set quality of captcha, The compression level ranges from 1 to 5. QualityCompressNone has no compression. The default is the lowest compression level
    // ====================================================
    capt.SetImageQuality(captcha.QualityCompressNone)

    // ====================================================
    // Method: SetFontHinting(val font.Hinting);
    // Desc: Set Hinting of font (HintingNone,HintingVertical,HintingFull)
    // ====================================================
    capt.SetFontHinting(font.HintingFull)

    // ====================================================
    // Method: SetTextRangLen(val captcha.RangeVal);
    // Desc: Set random length of font
    // ====================================================
    capt.SetTextRangLen(captcha.RangeVal{6, 7})

    // ====================================================
    // Method: SetRangFontSize(val captcha.RangeVal);
    // Desc: Set random size of font
    // ====================================================
    capt.SetRangFontSize(captcha.RangeVal{32, 42})

    // ====================================================
    // Method: SetTextRangFontColors(colors []string);
    // Desc: Set random hex color of font
    // ====================================================
    capt.SetTextRangFontColors([]string{
        "#1d3f84",
        "#3a6a1e",
    })
 
    // ====================================================
    // Method: SetImageFontAlpha(val float64);
    // Desc:Set alpha of font
    // ====================================================
    capt.SetImageFontAlpha(0.5)

    // ====================================================
    // Method: SetTextShadow(val bool);
    // Desc:Set shadow of font
    // ====================================================
    capt.SetTextShadow(true)

    // ====================================================
    // Method: SetTextShadowColor(val string);
    // Desc:Set shadow color of font
    // ====================================================
    capt.SetTextShadowColor("#101010")

    // ====================================================
    // Method: SetTextShadowPoint(val captcha.Point);
    // Desc:Set shadow point of font
    // ====================================================
    capt.SetTextShadowPoint(captcha.Point{1, 1})

    // ====================================================
    // Method: SetTextRangAnglePos(pos []captcha.RangeVal);
    // Desc:Set angle of font
    // ====================================================
    capt.SetTextRangAnglePos([]captcha.RangeVal{
        {1, 15},
        {15, 30},
        {30, 45},
        {315, 330},
        {330, 345},
        {345, 359},
    })

    // ====================================================
    // Method: SetImageFontDistort(val int);
    // Desc:Set distort of font
    // ====================================================
    capt.SetImageFontDistort(captcha.DistortLevel2)
}

Set Thumb Image Configuration

Tip: Some images are attached by default.

package main
import (
    "fmt"
    "os"
    "github.com/wenlng/go-captcha/captcha"
)

func main(){
    capt := captcha.GetCaptcha()
    
    path, _ := os.Getwd()    
    
    // ====================================================
    // Method: SetRangCheckTextLen(val captcha.RangeVal);
    // Desc:Set random length of font
    // ====================================================
    capt.SetRangCheckTextLen(captcha.RangeVal{2, 4})

    // ====================================================
    // Method: SetRangCheckFontSize(val captcha.RangeVal);
    // Desc:Set random size of font
    // ====================================================
    capt.SetRangCheckFontSize(captcha.RangeVal{24, 30})
 
    // ====================================================
    // Method: SetThumbTextRangFontColors(colors []string);
    // Desc: Set random hex color of font
    // ====================================================
    capt.SetThumbTextRangFontColors([]string{
        "#1d3f84",
        "#3a6a1e",
    })

    // ====================================================
    // Method: SetThumbBgColors(colors []string);
    // Desc: Sets the random hex color of the background
    // ====================================================
    capt.SetThumbBgColors([]string{
        "#1d3f84",
        "#3a6a1e",
    })

    // ====================================================
    // Method: SetThumbBackground(colors []string);
    // Desc:Set random image of background
    // ====================================================
    capt.SetThumbBackground([]string{
        path + "/__example/resources/images/r1.jpg",
        path + "/__example/resources/images/r2.jpg",
    })

    // ====================================================
    // Method: SetThumbBgDistort(val int);
    // Desc:Set the distort of background
    // ====================================================
    capt.SetThumbBgDistort(captcha.DistortLevel2)

    // ====================================================
    // Method: SetThumbFontDistort(val int);
    // Desc:Set the distort of font
    // ====================================================
    capt.SetThumbFontDistort(captcha.DistortLevel2)

    // ====================================================
    // Method: SetThumbBgCirclesNum(val int);
    // Desc:Sets the number of dots
    // ====================================================
    capt.SetThumbBgCirclesNum(20)

    // ====================================================
    // Method: SetThumbBgSlimLineNum(val int);
    // Desc:Set number of lines
    // ====================================================
    capt.SetThumbBgSlimLineNum(3)
  
}

Other

package main
import (
    "fmt"
    "os"
    "github.com/wenlng/go-captcha/captcha"
)

func main(){
    path, _ := os.Getwd()    
    // ====================================================
    // Method: ClearAssetCacheWithPath(paths []string) bool;
    // Desc: Clear Cache
    // ====================================================
    captcha.ClearAssetCacheWithPaths([]string{
    	path + "/__example/resources/images/1.jpg",
    	path + "/__example/resources/fonts/fonts.ttf",
    })     

    // ====================================================
    // Method: captcha.CheckPointDist(sx, sy, dx, dy, width, height int64) bool;
    // Desc: Check point position
    // ====================================================
    captcha.CheckPointDist(0, 30, 0, 30, 30, 30)    

    // ====================================================
    // Method: captcha.CheckPointDistWithPadding(sx, sy, dx, dy, width, height, padding int64) bool;
    // Desc: Check point position
    // ====================================================
    captcha.CheckPointDistWithPadding(0, 30, 0, 30, 30, 30, 5) 
}

Generate Captcha Data

package main
import (
    "fmt"
    "os"
    "github.com/wenlng/go-captcha/captcha"
)

func main(){
    capt := captcha.GetCaptcha()
    
    // generate ...
    // ====================================================
    // dots:  Character position information
    //  - {"0":{"Index":0,"Dx":198,"Dy":77,"Size":41,"Width":54,"Height":41,"Text":"SH","Angle":6,"Color":"#885500"} ...}
    // imageBase64:  Verify the clicked image
    // thumbImageBase64: Thumb displayed
    // key: Only Key
    // ====================================================
    dots, imageBase64, thumbImageBase64, key, err := capt.Generate()
    if err != nil {
        panic(err)
        return
    }
    fmt.Println(len(imageBase64))
    fmt.Println(len(thumbImageBase64))
    fmt.Println(key)
    fmt.Println(dots)
}

Api Params

// Example: Get captcha data
    Respose Data = {
        "code": 0,
        "image_base64": "...",
        "thumb_base64": "...",
        "captcha_key": "...",
    }     

// Example: Post check data
    Request Data = {
        dots: "x1,y1,x2,y2,...."
        key: "......"
    }

Buy the author coffee: http://witkeycode.com/sponsor


LICENSE

MIT

go-captcha's People

Contributors

wenlng avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

go-captcha's Issues

是否考虑加入更多验证方式

查看 Demo 好像只支持「选择文字」验证方式,请问是否考虑加入诸如「滑动验证」「旋转验证」等验证方式。

设置字符集为英文字母时,验证容易报错

  1. 设置英文字符集

chars := "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"

_ = capt.SetRangChars(strings.Split(chars, ""))

capt = captcha.GetCaptcha()

dots, b64, tb64, key, err := capt.Generate()

  1. 前端点选结果

{"dot":"110,198,48,88,197,72","key":"c39190357e6e59043729c59a8fa99a71"}
image

  1. 实际点选结果
    {"0":{"Index":0,"Dx":105,"Dy":227,"Size":38,"Width":38,"Height":38,"Text":"N","Angle":330,"Color":"#fcb08e","Color2":"#6e3700"},"1":{"Index":1,"Dx":50,"Dy":111,"Size":31,"Width":31,"Height":31,"Text":"A","Angle":20,"Color":"#60c1ff","Color2":"#6e3700"},"2":{"Index":2,"Dx":193,"Dy":96,"Size":37,"Width":37,"Height":37,"Text":"F","Angle":325,"Color":"#b4fed4","Color2":"#660033"}}

期望和汉字的验证效果一致

There is a problem with the order of return variables in the comment

// Generate is a function
/**

  • @description: 根据设置的尺寸生成验证码图片
  • @return CaptchaCharDot 位置信息
  • @return string 主图Base64
  • @return string 验证码KEY
  • @return string 缩略图Base64
  • @return error
    */
    func (cc *Captcha) Generate() (map[int]CharDot, string, string, string, error) {
    dots, ib64, tb64, key, err := cc.GenerateWithSize(cc.config.imageSize, cc.config.thumbnailSize)
    return dots, ib64, tb64, key, err
    }

There may be misunderstandings about the first use.

capt.SetRangCheckTextLen 判断条件与变量名存在误导

// SetRangCheckTextLen is a function
/**
 * @Description: 设置随机验证文本长度
 * @receiver cc
 * @param val
 */
func (cc *Captcha) SetRangCheckTextLen(val RangeVal) {
	// 检测验证文本范围最大值是否小于随机字符串的最小范围
	if cc.config.rangCheckTextLen.Max > cc.config.rangTextLen.Min {
		panic(fmt.Errorf("CaptchaConfig Error: RangCheckTextLen.max must be less than or equal to RangTextLen.min"))
	}

	cc.config.rangCheckTextLen = val
}

不应该是
if cc.config.rangCheckTextLen.Max < cc.config.rangTextLen.Min {
}

给诸位提个醒,关系文字的坐标的

正常情况下

  • 前端的坐标是以左上角来计算的,这毫无问题

和服务器储存的坐标信息对比,你会发现:

  • X轴的坐标信息是对的(Dx <= fontendX <= Dx+Width),这毫无问题
  • Y轴的坐标信息是错的,前端的Y轴坐标小于了后端的Y轴开始坐标,也就是(fontendY <= Dy <= Dy_Height),你肯定会很紧张,以为自己算错了

把心放肚子里

  • 这是因为文字的坐标是以文字的左下角为原点的,也就是说服务端储存的Dy值已经是加上了Height之后的值了
  • 前端不需要任何处理,后端会在比对的时候自动减去Height值再进行比对,也就是(Dy - Height)≈ fontendY
  • 所以放心大胆的把这个看起来错误的Y值传给服务器,它会自己处理的

文档再完善些,示例再精简些

大神好,这个项目达到了我想要的效果,很强大
但,文档太不友好了。。。(自学go一年多,表示完全上不了手)
给的go_captcha_demo(https://github.com/wenlng/go-captcha-example)
也和文档基本对不上啊

希望大神可以做成开箱即用的那种,js抽离出来,页面简洁些,验证码的生成、验证、以及缓存明确下。。。。

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.