captcha.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // Copyright 2017 Eric Zhou. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // Package base64Captcha supports digits, numbers,alphabet, arithmetic, audio and digit-alphabet captcha.
  15. // base64Captcha is used for fast development of RESTful APIs, web apps and backend services in Go. give a string identifier to the package and it returns with a base64-encoding-png-string
  16. package base64Captcha
  17. import "strings"
  18. // Captcha captcha basic information.
  19. type Captcha struct {
  20. Driver Driver
  21. Store Store
  22. }
  23. //NewCaptcha creates a captcha instance from driver and store
  24. func NewCaptcha(driver Driver, store Store) *Captcha {
  25. return &Captcha{Driver: driver, Store: store}
  26. }
  27. //Generate generates a random id, base64 image string or an error if any
  28. func (c *Captcha) Generate() (id, b64s string, err error) {
  29. id, content, answer := c.Driver.GenerateIdQuestionAnswer()
  30. item, err := c.Driver.DrawCaptcha(content)
  31. if err != nil {
  32. return "", "", err
  33. }
  34. err = c.Store.Set(id, answer)
  35. if err != nil {
  36. return "", "", err
  37. }
  38. b64s = item.EncodeB64string()
  39. return
  40. }
  41. //Verify by a given id key and remove the captcha value in store,
  42. //return boolean value.
  43. //if you has multiple captcha instances which share a same store.
  44. //You may want to call `store.Verify` method instead.
  45. func (c *Captcha) Verify(id, answer string, clear bool) (match bool) {
  46. vv := c.Store.Get(id, clear)
  47. //fix issue for some redis key-value string value
  48. vv = strings.TrimSpace(vv)
  49. return vv == strings.TrimSpace(answer)
  50. }