arnaucube
arnaucube/goCaptchaPublic Self-hosted repository
goCaptcha/captcha.go
captcha.goRaw
 1package main
 2
 3import (
 4	"math/rand"
 5	"os/exec"
 6	"strings"
 7
 8	"gopkg.in/mgo.v2/bson"
 9)
10
11type Captcha struct {
12	Id       string   `json:"id"`
13	Imgs     []string `json:"imgs"`
14	Question string   `json:"question"`
15	Date     string   `json:"date"`
16}
17type CaptchaSol struct {
18	Id           string   `json:"id"`
19	Imgs         []string `json:"imgs"`
20	ImgsSolution []string `json:"imgssolution"`
21	Question     string   `json:"question"` //select all X
22	Date         string   `json:"date"`
23}
24type CaptchaAnswer struct {
25	CaptchaId string `json:"captchaid"`
26	Selection []int  `json:"selection"`
27}
28type ImgFakePath struct {
29	CaptchaId string `json:"captchaid"`
30	Real      string `json:"real"`
31	Fake      string `json:"fake"`
32}
33
34func generateUUID() string {
35	out, err := exec.Command("uuidgen").Output()
36	check(err)
37	uuid := string(out)
38	uuid = strings.Replace(uuid, "\n", "", -1)
39	return uuid
40}
41func generateRandInt(min int, max int) int {
42	//rand.Seed(time.Now().UTC().UnixNano())
43	return rand.Intn(max-min) + min
44}
45func generateCaptcha(count int) Captcha {
46	var captcha Captcha
47	var captchaSol CaptchaSol
48
49	captcha.Id = generateUUID()
50	captchaSol.Id = captcha.Id
51
52	for i := 0; i < count; i++ {
53		nCateg := generateRandInt(0, len(categDataset))
54		nImg := generateRandInt(0, len(dataset[categDataset[nCateg]]))
55		//imgFakePath
56		var imgFakePath ImgFakePath
57		imgFakePath.CaptchaId = captcha.Id
58		imgFakePath.Real = categDataset[nCateg] + "/" + dataset[categDataset[nCateg]][nImg]
59		imgFakePath.Fake = generateUUID() + ".png"
60		err := imgFakePathCollection.Insert(imgFakePath)
61		check(err)
62		captcha.Imgs = append(captcha.Imgs, imgFakePath.Fake)
63		captchaSol.Imgs = append(captchaSol.Imgs, dataset[categDataset[nCateg]][nImg])
64		captchaSol.ImgsSolution = append(captchaSol.ImgsSolution, categDataset[nCateg])
65	}
66	captcha.Question = "leopard"
67	captchaSol.Question = "leopard"
68	err := captchaCollection.Insert(captcha)
69	check(err)
70	err = captchaSolCollection.Insert(captchaSol)
71	check(err)
72	return captcha
73}
74func validateCaptcha(captchaAnswer CaptchaAnswer) bool {
75	var solved bool
76	solved = true
77	captchaSol := CaptchaSol{}
78	err := captchaSolCollection.Find(bson.M{"id": captchaAnswer.CaptchaId}).One(&captchaSol)
79	check(err)
80	for k, imgSol := range captchaSol.ImgsSolution {
81		if imgSol == captchaSol.Question {
82			if captchaAnswer.Selection[k] == 1 {
83				//correct
84			} else {
85				solved = false
86			}
87		}
88		if imgSol != captchaSol.Question {
89			if captchaAnswer.Selection[k] == 0 {
90				//correct
91			} else {
92				solved = false
93			}
94		}
95	}
96
97	return solved
98}