123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241 |
- package captcha
- import (
- "fmt"
- "html/template"
- "path"
- "strings"
- "github.com/Unknwon/com"
- "github.com/go-macaron/cache"
- "gopkg.in/macaron.v1"
- )
- const _VERSION = "0.1.0"
- func Version() string {
- return _VERSION
- }
- var (
- defaultChars = []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
- )
- type Captcha struct {
- store cache.Cache
- SubURL string
- URLPrefix string
- FieldIdName string
- FieldCaptchaName string
- StdWidth int
- StdHeight int
- ChallengeNums int
- Expiration int64
- CachePrefix string
- }
- func (c *Captcha) key(id string) string {
- return c.CachePrefix + id
- }
- func (c *Captcha) genRandChars() string {
- return string(com.RandomCreateBytes(c.ChallengeNums, defaultChars...))
- }
- func (c *Captcha) CreateHtml() template.HTML {
- value, err := c.CreateCaptcha()
- if err != nil {
- panic(fmt.Errorf("fail to create captcha: %v", err))
- }
- return template.HTML(fmt.Sprintf(`<input type="hidden" name="%s" value="%s">
- <a class="captcha" href="javascript:">
- <img onclick="this.src=('%s%s%s.png?reload='+(new Date()).getTime())" class="captcha-img" src="%s%s%s.png">
- </a>`, c.FieldIdName, value, c.SubURL, c.URLPrefix, value, c.SubURL, c.URLPrefix, value))
- }
- func (c *Captcha) CreateCaptcha() (string, error) {
- id := string(com.RandomCreateBytes(15))
- if err := c.store.Put(c.key(id), c.genRandChars(), c.Expiration); err != nil {
- return "", err
- }
- return id, nil
- }
- func (c *Captcha) VerifyReq(req macaron.Request) bool {
- req.ParseForm()
- return c.Verify(req.Form.Get(c.FieldIdName), req.Form.Get(c.FieldCaptchaName))
- }
- func (c *Captcha) Verify(id string, challenge string) bool {
- if len(challenge) == 0 || len(id) == 0 {
- return false
- }
- var chars string
- key := c.key(id)
- if v, ok := c.store.Get(key).(string); ok {
- chars = v
- } else {
- return false
- }
- defer c.store.Delete(key)
- if len(chars) != len(challenge) {
- return false
- }
-
- for i, c := range []byte(chars) {
- if c != challenge[i]-48 {
- return false
- }
- }
- return true
- }
- type Options struct {
-
- SubURL string
-
- URLPrefix string
-
- FieldIdName string
-
- FieldCaptchaName string
-
- ChallengeNums int
-
- Width int
-
- Height int
-
- Expiration int64
-
- CachePrefix string
- }
- func prepareOptions(options []Options) Options {
- var opt Options
- if len(options) > 0 {
- opt = options[0]
- }
- opt.SubURL = strings.TrimSuffix(opt.SubURL, "/")
-
- if len(opt.URLPrefix) == 0 {
- opt.URLPrefix = "/captcha/"
- } else if opt.URLPrefix[len(opt.URLPrefix)-1] != '/' {
- opt.URLPrefix += "/"
- }
- if len(opt.FieldIdName) == 0 {
- opt.FieldIdName = "captcha_id"
- }
- if len(opt.FieldCaptchaName) == 0 {
- opt.FieldCaptchaName = "captcha"
- }
- if opt.ChallengeNums == 0 {
- opt.ChallengeNums = 6
- }
- if opt.Width == 0 {
- opt.Width = stdWidth
- }
- if opt.Height == 0 {
- opt.Height = stdHeight
- }
- if opt.Expiration == 0 {
- opt.Expiration = 600
- }
- if len(opt.CachePrefix) == 0 {
- opt.CachePrefix = "captcha_"
- }
- return opt
- }
- func NewCaptcha(opt Options) *Captcha {
- return &Captcha{
- SubURL: opt.SubURL,
- URLPrefix: opt.URLPrefix,
- FieldIdName: opt.FieldIdName,
- FieldCaptchaName: opt.FieldCaptchaName,
- StdWidth: opt.Width,
- StdHeight: opt.Height,
- ChallengeNums: opt.ChallengeNums,
- Expiration: opt.Expiration,
- CachePrefix: opt.CachePrefix,
- }
- }
- func Captchaer(options ...Options) macaron.Handler {
- return func(ctx *macaron.Context, cache cache.Cache) {
- cpt := NewCaptcha(prepareOptions(options))
- cpt.store = cache
- if strings.HasPrefix(ctx.Req.URL.Path, cpt.URLPrefix) {
- var chars string
- id := path.Base(ctx.Req.URL.Path)
- if i := strings.Index(id, "."); i > -1 {
- id = id[:i]
- }
- key := cpt.key(id)
-
- if len(ctx.Query("reload")) > 0 {
- chars = cpt.genRandChars()
- if err := cpt.store.Put(key, chars, cpt.Expiration); err != nil {
- ctx.Status(500)
- ctx.Write([]byte("captcha reload error"))
- panic(fmt.Errorf("reload captcha: %v", err))
- }
- } else {
- if v, ok := cpt.store.Get(key).(string); ok {
- chars = v
- } else {
- ctx.Status(404)
- ctx.Write([]byte("captcha not found"))
- return
- }
- }
- if _, err := NewImage([]byte(chars), cpt.StdWidth, cpt.StdHeight).WriteTo(ctx.Resp); err != nil {
- panic(fmt.Errorf("write captcha: %v", err))
- }
- return
- }
- ctx.Data["Captcha"] = cpt
- ctx.Map(cpt)
- }
- }
|