captcha.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package captcha
  2. import (
  3. "bytes"
  4. "crypto/rand"
  5. "github.com/dchest/uniuri"
  6. "io"
  7. "os"
  8. )
  9. // Standard number of numbers in captcha
  10. const StdLength = 6
  11. var globalStore = newStore()
  12. // randomNumbers return a byte slice of the given length containing random
  13. // numbers in range 0-9.
  14. func randomNumbers(length int) []byte {
  15. n := make([]byte, length)
  16. if _, err := io.ReadFull(rand.Reader, n); err != nil {
  17. panic(err)
  18. }
  19. for i := range n {
  20. n[i] %= 10
  21. }
  22. return n
  23. }
  24. // New creates a new captcha of the given length, saves it in the internal
  25. // storage, and returns its id.
  26. func New(length int) (id string) {
  27. id = uniuri.New()
  28. globalStore.saveCaptcha(id, randomNumbers(length))
  29. return
  30. }
  31. // Reload generates new numbers for the given captcha id. This function does
  32. // nothing if there is no captcha with the given id.
  33. //
  34. // After calling this function, the image presented to a user must be refreshed
  35. // to show the new captcha (WriteImage will write the new one).
  36. func Reload(id string) {
  37. oldns := globalStore.getNumbers(id)
  38. if oldns == nil {
  39. return
  40. }
  41. globalStore.saveCaptcha(id, randomNumbers(len(oldns)))
  42. }
  43. // WriteImage writes PNG-encoded captcha image of the given width and height
  44. // with the given captcha id into the io.Writer.
  45. func WriteImage(w io.Writer, id string, width, height int) os.Error {
  46. ns := globalStore.getNumbers(id)
  47. if ns == nil {
  48. return os.NewError("captcha id not found")
  49. }
  50. return NewImage(ns, width, height).PNGEncode(w)
  51. }
  52. // Verify returns true if the given numbers are the numbers that were used to
  53. // create the given captcha id.
  54. //
  55. // The function deletes the captcha with the given id from the internal
  56. // storage, so that the same captcha can't be verified anymore.
  57. func Verify(id string, numbers []byte) bool {
  58. realns := globalStore.getNumbersClear(id)
  59. if realns == nil {
  60. return false
  61. }
  62. return bytes.Equal(numbers, realns)
  63. }
  64. // Collect deletes expired and used captchas from the internal
  65. // storage. It is called automatically by New function every CollectNum
  66. // generated captchas, but still exported to enable freeing memory manually if
  67. // needed.
  68. //
  69. // Collection is launched in a new goroutine, so this function returns
  70. // immediately.
  71. func Collect() {
  72. go globalStore.collect()
  73. }