You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

95 lines
2.2 KiB

package CaptchaController
//https://gitee.com/lemon527/base64Captcha
//http://127.0.0.1:8006/dsSzxy/static/getcapt.html
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/mojocn/base64Captcha"
"image/color"
"net/http"
)
// Routers 模块的路由配置
func Routers(r *gin.RouterGroup) {
rr := r.Group("/captchaRelate")
rr.GET("/getCaptcha", getCaptcha)
rr.POST("/verifyCaptcha", verifyCaptcha)
}
// 设置自带的store
var store = base64Captcha.DefaultMemStore
//使用redis作为store
//var store = RedisStore{}
// CaptchaResult 存储验证码的结构
type CaptchaResult struct {
Id string `json:"id"`
Base64Blob string `json:"base_64_blob"`
}
// GetOne 生成图形化验证码
func getCaptcha(c *gin.Context) {
id, b64s, err := CaptMake()
if err != nil {
c.JSON(http.StatusOK, gin.H{"success": false, "info": "发生错误!"})
}
captchaResult := CaptchaResult{
Id: id,
Base64Blob: b64s,
}
c.JSON(http.StatusOK, gin.H{"success": true, "captcha": captchaResult})
return
}
// Verify 验证captcha是否正确
func verifyCaptcha(c *gin.Context) {
id := c.PostForm("id")
capt := c.PostForm("capt")
if id == "" || capt == "" {
c.JSON(http.StatusOK, gin.H{"success": false, "msg": "参数错误!"})
}
if CaptVerify(id, capt) == true {
c.JSON(http.StatusOK, gin.H{"success": true})
} else {
c.JSON(http.StatusOK, gin.H{"success": false})
}
return
}
// CaptMake 生成验证码
func CaptMake() (id, b64s string, err error) {
var driver base64Captcha.Driver
var driverString base64Captcha.DriverString
// 配置验证码信息
captchaConfig := base64Captcha.DriverString{
Height: 60,
Width: 200,
NoiseCount: 0,
ShowLineOptions: 2 | 4,
Length: 4,
Source: "1234567890qwertyuioplkjhgfdsazxcvbnm",
BgColor: &color.RGBA{
R: 3,
G: 102,
B: 214,
A: 125,
},
Fonts: []string{"wqy-microhei.ttc"},
}
driverString = captchaConfig
driver = driverString.ConvertFonts()
captcha := base64Captcha.NewCaptcha(driver, store)
lid, lb64s, lerr := captcha.Generate()
return lid, lb64s, lerr
}
// CaptVerify 验证captcha是否正确
func CaptVerify(id string, capt string) bool {
fmt.Println("id:" + id)
fmt.Println("capt:" + capt)
return store.Verify(id, capt, false)
}