52 lines
1.2 KiB
Go
52 lines
1.2 KiB
Go
package utils
|
|
|
|
import (
|
|
"github.com/mojocn/base64Captcha"
|
|
"image/color"
|
|
"time"
|
|
)
|
|
|
|
// GenerateCaptcha 生成验证码-base64
|
|
func GenerateCaptcha() (id, b64s string, err error) {
|
|
var driver *base64Captcha.DriverString
|
|
// 配置验证码的参数
|
|
driverString := &base64Captcha.DriverString{
|
|
Height: 40,
|
|
Width: 100,
|
|
NoiseCount: 0,
|
|
ShowLineOptions: 0,
|
|
Length: 4,
|
|
Source: "1234567890",
|
|
BgColor: &color.RGBA{R: 3, G: 102, B: 214, A: 125},
|
|
Fonts: []string{"wqy-microhei.ttc"},
|
|
}
|
|
// ConvertFonts 按名称加载字体
|
|
driver = driverString.ConvertFonts()
|
|
|
|
base64Captcha.Expiration = 30 * time.Minute
|
|
store := base64Captcha.DefaultMemStore
|
|
|
|
captcha := base64Captcha.NewCaptcha(driver, store)
|
|
id, b64s, _, err = captcha.Generate()
|
|
if err != nil {
|
|
return "", "", err
|
|
}
|
|
return id, b64s, nil
|
|
}
|
|
|
|
// VerifyCaptcha 验证验证码
|
|
func VerifyCaptcha(id, answer string) bool {
|
|
// 创建验证码实例
|
|
base64Captcha.Expiration = 30 * time.Minute
|
|
store := base64Captcha.DefaultMemStore
|
|
captcha := base64Captcha.NewCaptcha(nil, store)
|
|
|
|
// 验证验证码
|
|
isValid := captcha.Verify(id, answer, true)
|
|
if !isValid {
|
|
return false
|
|
}
|
|
|
|
return true
|
|
}
|