captcha.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. // Copyright 2011 Dmitry Chestnykh. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. // Package captcha implements generation and verification of image and audio
  5. // CAPTCHAs.
  6. //
  7. // A captcha solution is the sequence of digits 0-9 with the defined length.
  8. // There are two captcha representations: image and audio.
  9. //
  10. // An image representation is a PNG-encoded image with the solution printed on
  11. // it in such a way that makes it hard for computers to solve it using OCR.
  12. //
  13. // An audio representation is a WAVE-encoded (8 kHz unsigned 8-bit) sound with
  14. // the spoken solution (currently in English, Russian, Chinese, and Japanese).
  15. // To make it hard for computers to solve audio captcha, the voice that
  16. // pronounces numbers has random speed and pitch, and there is a randomly
  17. // generated background noise mixed into the sound.
  18. //
  19. // This package doesn't require external files or libraries to generate captcha
  20. // representations; it is self-contained.
  21. //
  22. // To make captchas one-time, the package includes a memory storage that stores
  23. // captcha ids, their solutions, and expiration time. Used captchas are removed
  24. // from the store immediately after calling Verify or VerifyString, while
  25. // unused captchas (user loaded a page with captcha, but didn't submit the
  26. // form) are collected automatically after the predefined expiration time.
  27. // Developers can also provide custom store (for example, which saves captcha
  28. // ids and solutions in database) by implementing Store interface and
  29. // registering the object with SetCustomStore.
  30. //
  31. // Captchas are created by calling New, which returns the captcha id. Their
  32. // representations, though, are created on-the-fly by calling WriteImage or
  33. // WriteAudio functions. Created representations are not stored anywhere, but
  34. // subsequent calls to these functions with the same id will write the same
  35. // captcha solution. Reload function will create a new different solution for
  36. // the provided captcha, allowing users to "reload" captcha if they can't solve
  37. // the displayed one without reloading the whole page. Verify and VerifyString
  38. // are used to verify that the given solution is the right one for the given
  39. // captcha id.
  40. //
  41. // Server provides an http.Handler which can serve image and audio
  42. // representations of captchas automatically from the URL. It can also be used
  43. // to reload captchas. Refer to Server function documentation for details, or
  44. // take a look at the example in "capexample" subdirectory.
  45. package captcha
  46. import (
  47. "bytes"
  48. "errors"
  49. "io"
  50. "time"
  51. )
  52. const (
  53. // Default number of digits in captcha solution.
  54. DefaultLen = 6
  55. // The number of captchas created that triggers garbage collection used
  56. // by default store.
  57. CollectNum = 100
  58. // Expiration time of captchas used by default store.
  59. Expiration = 10 * time.Minute
  60. )
  61. var (
  62. ErrNotFound = errors.New("captcha: id not found")
  63. // globalStore is a shared storage for captchas, generated by New function.
  64. globalStore = NewMemoryStore(CollectNum, Expiration)
  65. )
  66. // SetCustomStore sets custom storage for captchas, replacing the default
  67. // memory store. This function must be called before generating any captchas.
  68. func SetCustomStore(s Store) {
  69. globalStore = s
  70. }
  71. // New creates a new captcha with the standard length, saves it in the internal
  72. // storage and returns its id.
  73. func New() string {
  74. return NewLen(DefaultLen)
  75. }
  76. // NewLen is just like New, but accepts length of a captcha solution as the
  77. // argument.
  78. func NewLen(length int) (id string) {
  79. id = randomId()
  80. globalStore.Set(id, RandomDigits(length))
  81. return
  82. }
  83. // Reload generates and remembers new digits for the given captcha id. This
  84. // function returns false if there is no captcha with the given id.
  85. //
  86. // After calling this function, the image or audio presented to a user must be
  87. // refreshed to show the new captcha representation (WriteImage and WriteAudio
  88. // will write the new one).
  89. func Reload(id string) bool {
  90. old := globalStore.Get(id, false)
  91. if old == nil {
  92. return false
  93. }
  94. globalStore.Set(id, RandomDigits(len(old)))
  95. return true
  96. }
  97. // WriteImage writes PNG-encoded image representation of the captcha with the
  98. // given id. The image will have the given width and height.
  99. func WriteImage(w io.Writer, id string, width, height int) error {
  100. d := globalStore.Get(id, false)
  101. if d == nil {
  102. return ErrNotFound
  103. }
  104. _, err := NewImage(id, d, width, height).WriteTo(w)
  105. return err
  106. }
  107. // WriteAudio writes WAV-encoded audio representation of the captcha with the
  108. // given id and the given language. If there are no sounds for the given
  109. // language, English is used.
  110. func WriteAudio(w io.Writer, id string, lang string) error {
  111. d := globalStore.Get(id, false)
  112. if d == nil {
  113. return ErrNotFound
  114. }
  115. _, err := NewAudio(id, d, lang).WriteTo(w)
  116. return err
  117. }
  118. // Verify returns true if the given digits are the ones that were used to
  119. // create the given captcha id.
  120. //
  121. // The function deletes the captcha with the given id from the internal
  122. // storage, so that the same captcha can't be verified anymore.
  123. func Verify(id string, digits []byte) bool {
  124. if digits == nil || len(digits) == 0 {
  125. return false
  126. }
  127. reald := globalStore.Get(id, true)
  128. if reald == nil {
  129. return false
  130. }
  131. return bytes.Equal(digits, reald)
  132. }
  133. // VerifyString is like Verify, but accepts a string of digits. It removes
  134. // spaces and commas from the string, but any other characters, apart from
  135. // digits and listed above, will cause the function to return false.
  136. func VerifyString(id string, digits string) bool {
  137. if digits == "" {
  138. return false
  139. }
  140. ns := make([]byte, len(digits))
  141. for i := range ns {
  142. d := digits[i]
  143. switch {
  144. case '0' <= d && d <= '9':
  145. ns[i] = d - '0'
  146. case d == ' ' || d == ',':
  147. // ignore
  148. default:
  149. return false
  150. }
  151. }
  152. return Verify(id, ns)
  153. }