61 lines
946 B
Go
61 lines
946 B
Go
package captcha
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"errors"
|
|
"image"
|
|
"math/big"
|
|
"time"
|
|
)
|
|
|
|
const (
|
|
maxAnswer = 999999
|
|
)
|
|
|
|
var errorNotFound = errors.New("captcha not found")
|
|
|
|
type ID string
|
|
type Answer string
|
|
|
|
type ICaptcha interface {
|
|
generateImage() *image.Image
|
|
GetImage() *image.Image
|
|
GetAnswer() Answer
|
|
Solve(answer Answer) bool
|
|
IsSolved() bool
|
|
Expiry() time.Time
|
|
}
|
|
|
|
type Captcha struct {
|
|
Image image.Image
|
|
Answer Answer
|
|
Solved bool
|
|
ExpireIn time.Time
|
|
}
|
|
|
|
func (c *Captcha) Solve(answer Answer) bool {
|
|
c.Solved = c.Answer == answer
|
|
return c.Solved
|
|
}
|
|
|
|
func (c *Captcha) GetAnswer() Answer {
|
|
return c.Answer
|
|
}
|
|
|
|
func (c *Captcha) IsSolved() bool {
|
|
return c.Solved
|
|
}
|
|
|
|
func (c *Captcha) Expiry() time.Time {
|
|
return c.ExpireIn
|
|
}
|
|
|
|
func GenerateAnswer() Answer {
|
|
ans, _ := rand.Int(rand.Reader, big.NewInt(maxAnswer))
|
|
return (Answer(ans.String()))
|
|
}
|
|
|
|
func ExpiryDate(expiry time.Duration) time.Time {
|
|
return time.Now().Add(expiry)
|
|
}
|