Skip to content

Commit

Permalink
frontend
Browse files Browse the repository at this point in the history
  • Loading branch information
EricZhou committed Dec 10, 2019
1 parent 39c5936 commit d053e66
Show file tree
Hide file tree
Showing 20 changed files with 309 additions and 753 deletions.
67 changes: 35 additions & 32 deletions _examples/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,49 +11,49 @@ import (

//configJsonBody json request body.
type configJsonBody struct {
Id string
CaptchaType string
VerifyValue string
ConfigAudio base64Captcha.driverAudio
ConfigCharacter base64Captcha.DriverChar
ConfigDigit base64Captcha.driverDigit
Id string
CaptchaType string
VerifyValue string
DriverAudio *base64Captcha.DriverAudio
DriverString *base64Captcha.DriverString
DriverDigit *base64Captcha.DriverDigit
}

var store = base64Captcha.DefaultMemStore

var captchaMap = map[string]base64Captcha.Captcha{}

// base64Captcha create http handler
func generateCaptchaHandler(w http.ResponseWriter, r *http.Request) {
//parse request parameters
//接收客户端发送来的请求参数
decoder := json.NewDecoder(r.Body)
var postParameters configJsonBody
err := decoder.Decode(&postParameters)
var param configJsonBody
err := decoder.Decode(&param)
if err != nil {
log.Println(err)
}
defer r.Body.Close()
var driver base64Captcha.Driver

//create base64 encoding captcha
//创建base64图像验证码

var config interface{}
switch postParameters.CaptchaType {
switch param.CaptchaType {
case "audio":
config = postParameters.ConfigAudio
driver = param.DriverAudio
case "character":
config = postParameters.ConfigCharacter
driver = param.DriverString
default:
config = postParameters.ConfigDigit
driver = param.DriverDigit
}
captchaId, captcaInterfaceInstance := base64Captcha.GenerateCaptcha(postParameters.Id, config)
base64blob := base64Captcha.CaptchaWriteToBase64Encoding(captcaInterfaceInstance)

//or you can just write the captcha content to the httpResponseWriter.
//before you put the captchaId into the response COOKIE.
//captcaInterfaceInstance.WriteTo(w)

//set json response
//设置json响应
c := base64Captcha.NewCaptcha(driver, store)
id, b64s, err := c.GenerateB64s()
body := map[string]interface{}{"code": 1, "data": b64s, "captchaId": id, "msg": "success"}
if err != nil {
body = map[string]interface{}{"code": 0, "msg": err.Error()}
}
captchaMap[id] = *c
w.Header().Set("Content-Type", "application/json; charset=utf-8")
body := map[string]interface{}{"code": 1, "data": base64blob, "captchaId": captchaId, "msg": "success"}
json.NewEncoder(w).Encode(body)
}

Expand All @@ -63,23 +63,26 @@ func captchaVerifyHandle(w http.ResponseWriter, r *http.Request) {
//parse request parameters
//接收客户端发送来的请求参数
decoder := json.NewDecoder(r.Body)
var postParameters configJsonBody
err := decoder.Decode(&postParameters)
var param configJsonBody
err := decoder.Decode(&param)
if err != nil {
log.Println(err)
}
defer r.Body.Close()
//verify the captcha
//比较图像验证码
verifyResult := base64Captcha.VerifyCaptcha(postParameters.Id, postParameters.VerifyValue)
c, ok := captchaMap[param.Id]
body := map[string]interface{}{"code": 0, "msg": "failed"}
if ok {
if c.Verify(param.Id, param.VerifyValue, true) {
body = map[string]interface{}{"code": 1, "msg": "ok"}
}
}
delete(captchaMap, param.Id)

//set json response
//设置json响应
w.Header().Set("Content-Type", "application/json; charset=utf-8")
body := map[string]interface{}{"code": "error", "data": "验证失败", "msg": "captcha failed"}
if verifyResult {
body = map[string]interface{}{"code": "success", "data": "验证通过", "msg": "captcha verified"}
}

json.NewEncoder(w).Encode(body)
}

Expand Down
298 changes: 151 additions & 147 deletions _examples/static/index.html

Large diffs are not rendered by default.

6 changes: 1 addition & 5 deletions captcha_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,8 @@ func TestCaptcha_GenerateB64s(t *testing.T) {
Store Store
}

dDigit := driverDigit{80, 240, 5, 0.7, 5}
dDigit := DriverDigit{80, 240, 5, 0.7, 5}
audioDriver := NewDriverAudio(rand.Intn(5), "en")
driverChar := NewDriverString(80, 240, 4, OptionShowHollowLine|OptionShowSlimeLine|OptionShowSineLine, 4, nil, fontsAll)
driverChinese := NewDriverLanguage(*driverChar,"zh-CN")
tests := []struct {
name string
fields fields
Expand All @@ -40,8 +38,6 @@ func TestCaptcha_GenerateB64s(t *testing.T) {
}{
{"mem-digit", fields{&dDigit, DefaultMemStore}, "xxxx", "", false},
{"mem-audio", fields{audioDriver, DefaultMemStore}, "xxxx", "", false},
{"mem-char", fields{driverChar, DefaultMemStore}, "xxxx", "", false},
{"mem-chinese", fields{driverChinese, DefaultMemStore}, "xxxx", "", false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
Expand Down
19 changes: 7 additions & 12 deletions const.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,15 +35,10 @@ const (
"眼王按格养易置派层片始却专状育厂京识适属" +
"圆包火住调满县局照参红细引听该铁价严龙飞"

//MimeTypeCaptchaAudio output base64 mine-type.
MimeTypeCaptchaAudio = "audio/wav"
//MimeTypeCaptchaImage output base64 mine-type.
MimeTypeCaptchaImage = "image/png"

//FileExtCaptchaAudio output file extension.
FileExtCaptchaAudio = "wav"
//FileExtCaptchaImage output file extension.
FileExtCaptchaImage = "png"
//MimeTypeAudio output base64 mine-type.
MimeTypeAudio = "audio/wav"
//MimeTypeImage output base64 mine-type.
MimeTypeImage = "image/png"

Emoji = "😀😃💯😄🤖😻😅🤣😂🧑🙃😉😊😇😍👴🤩😘😗☺👽♀😙♂😋😛🎨😜🤪😝🤑🤗🤭🤫🤔🤐🤨😐🙉😶😏💗🙄😬🤥😌😪🤤😷🤢🤮🤯😵🤠😎🧐😨😰😱😭😖😡🤬👿☠💀💥💢"
)
Expand All @@ -68,9 +63,9 @@ const (

const (
//IsShowHollowLine is show hollow line.
OptionShowHollowLine = 1 << iota
OptionShowHollowLine = 2
//IsShowSlimeLine is show slime line.
OptionShowSlimeLine
OptionShowSlimeLine = 4
//IsShowSineLine is show sine line.
OptionShowSineLine
OptionShowSineLine = 8
)
14 changes: 8 additions & 6 deletions driver_audio.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,24 +4,26 @@

package base64Captcha

//driverAudio captcha config for captcha-engine-audio.
type driverAudio struct {
//DriverAudio captcha config for captcha-engine-audio.
type DriverAudio struct {
// Length Default number of digits in captcha solution.
Length int
// Language possible values for lang are "en", "ja", "ru", "zh".
Language string
}

func NewDriverAudio(length int, language string) *driverAudio {
return &driverAudio{Length: length, Language: language}
var DefaultDriverAudio = NewDriverAudio(6, "en")

func NewDriverAudio(length int, language string) *DriverAudio {
return &DriverAudio{Length: length, Language: language}
}

func (d *driverAudio) GenerateItem(content string) (item Item, err error) {
func (d *DriverAudio) GenerateItem(content string) (item Item, err error) {
digits := stringToFakeByte(content)
audio := newAudio("", digits, d.Language)
return audio, nil
}
func (d *driverAudio) GenerateQuestionAnswer() (q, a string) {
func (d *DriverAudio) GenerateQuestionAnswer() (q, a string) {
digits := randomDigits(d.Length)
a = parseDigitsToString(digits)
return a, a
Expand Down
2 changes: 1 addition & 1 deletion driver_audio_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ func TestDriverAudio_GenerateItem(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
d := &driverAudio{
d := &DriverAudio{
Length: tt.fields.CaptchaLen,
Language: tt.fields.Language,
}
Expand Down
14 changes: 8 additions & 6 deletions driver_digit.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ import (
"image"
)

//driverDigit config for captcha-engine-digit.
type driverDigit struct {
//DriverDigit config for captcha-engine-digit.
type DriverDigit struct {
// Height png height in pixel.
// 图像验证码的高度像素.
Height int
Expand All @@ -37,17 +37,19 @@ type driverDigit struct {
DotCount int
}

func NewDriverDigit() *driverDigit {
return &driverDigit{}
func NewDriverDigit(height int, width int, length int, maxSkew float64, dotCount int) *DriverDigit {
return &DriverDigit{Height: height, Width: width, Length: length, MaxSkew: maxSkew, DotCount: dotCount}
}

func (d *driverDigit) GenerateQuestionAnswer() (q, a string) {
var DefaultDriverDigit = NewDriverDigit(80, 240, 5, 0.7, 80)

func (d *DriverDigit) GenerateQuestionAnswer() (q, a string) {
digits := randomDigits(d.Length)
a = parseDigitsToString(digits)
return a, a
}

func (d *driverDigit) GenerateItem(content string) (item Item, err error) {
func (d *DriverDigit) GenerateItem(content string) (item Item, err error) {
// Initialize PRNG.
itemDigit := NewItemDigit(d.Width, d.Height)
//parse digits to string
Expand Down
4 changes: 2 additions & 2 deletions driver_digit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ func TestDriverDigit_GenerateItem(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
d := &driverDigit{
d := &DriverDigit{
Height: tt.fields.Height,
Width: tt.fields.Width,
Length: tt.fields.CaptchaLen,
Expand All @@ -49,7 +49,7 @@ func TestDriverDigit_GenerateItem(t *testing.T) {
}
gotItem, err := d.GenerateItem(tt.args.content)
if (err != nil) != tt.wantErr {
t.Errorf("driverDigit.GenerateItem() error = %v, wantErr %v", err, tt.wantErr)
t.Errorf("DriverDigit.GenerateItem() error = %v, wantErr %v", err, tt.wantErr)
return
}
ItemWriteToFile(gotItem, "_builds", tt.args.content, "png")
Expand Down
36 changes: 29 additions & 7 deletions driver_language.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,15 @@ import (
var langMap = map[string][]int{
//"zh-CN": []int{19968, 40869},
"latin": []int{0x0000, 0x007f},
"zh-CN": []int{0x4e00, 0x9fa5},
"zh": []int{0x4e00, 0x9fa5},
"ko": []int{12593, 12686},
"jp": []int{12449, 12531}, //[]int{12353, 12435}
"ru": []int{1025, 1169},
"th": []int{0x0e00, 0x0e7f},
"greek": []int{0x0380, 0x03ff},
"arabic": []int{0x0600, 0x06ff},
"Hebrew": []int{0x0590, 0x05ff},
"hebrew": []int{0x0590, 0x05ff},
//"emotion": []int{0x1f601, 0x1f64f},
}

func generateRandomRune(size int, code string) string {
Expand All @@ -35,15 +36,36 @@ func generateRandomRune(size int, code string) string {
return string(randRune)
}

func NewDriverLanguage(driverString DriverString, languageCode string) *DriverLanguage {
return &DriverLanguage{DriverString: driverString, LanguageCode: languageCode}
}

type DriverLanguage struct {
DriverString
// Height png height in pixel.
// 图像验证码的高度像素.
Height int
// Width Captcha png width in pixel.
// 图像验证码的宽度像素
Width int

//NoiseCount text noise count.
NoiseCount int

ShowLineOptions int
//CaptchaRunePairs make a list of rune for Captcha random selection.
// 随机字符串可选内容

// Length Default number of digits in captcha solution.
// 默认数字验证长度6.
Length int

//BgColor captcha image background color (optional)
//背景颜色
BgColor *color.RGBA
Fonts []*truetype.Font
LanguageCode string
}

func NewDriverLanguage(height int, width int, noiseCount int, showLineOptions int, length int, bgColor *color.RGBA, fonts []*truetype.Font, languageCode string) *DriverLanguage {
return &DriverLanguage{Height: height, Width: width, NoiseCount: noiseCount, ShowLineOptions: showLineOptions, Length: length, BgColor: bgColor, Fonts: fonts, LanguageCode: languageCode}
}

func (d *DriverLanguage) GenerateQuestionAnswer() (content, answer string) {
content = generateRandomRune(d.Length, d.LanguageCode)
return content, content
Expand Down
19 changes: 19 additions & 0 deletions driver_language_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package base64Captcha

import (
"github.com/golang/freetype/truetype"
"testing"
)

func TestDriverLanguage_GenerateItem(t *testing.T) {
ds := NewDriverLanguage(80, 240, 5, OptionShowSineLine|OptionShowSlimeLine|OptionShowHollowLine, 5, nil, []*truetype.Font{fontChinese}, "emotion")

for i := 0; i < 40; i++ {
q, _ := ds.GenerateQuestionAnswer()
item, err := ds.GenerateItem(q)
if err != nil {
t.Error(err)
}
ItemWriteToFile(item, "_builds", randomId(), "png")
}
}
18 changes: 17 additions & 1 deletion driver_math.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,28 @@ package base64Captcha

import (
"fmt"
"github.com/golang/freetype/truetype"
"image/color"
"math/rand"
)

//DriverChar captcha config for captcha-engine-characters.
type DriverMath DriverString
type DriverMath struct {
Height int
// Width Captcha png width in pixel.
// 图像验证码的宽度像素
Width int

//NoiseCount text noise count.
NoiseCount int

ShowLineOptions int
//CaptchaRunePairs make a list of rune for Captcha random selection.
// 随机字符串可选内容

BgColor *color.RGBA
Fonts []*truetype.Font
}

func (d *DriverMath) GenerateQuestionAnswer() (question, answer string) {
operators := []string{"+", "-", "x"}
Expand Down
Loading

0 comments on commit d053e66

Please sign in to comment.