captcha.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. package captcha
  2. import (
  3. "bytes"
  4. "os"
  5. "rand"
  6. "time"
  7. crand "crypto/rand"
  8. "github.com/dchest/uniuri"
  9. "io"
  10. "container/list"
  11. "sync"
  12. )
  13. const (
  14. expiration = 2 * 60 // 2 minutes
  15. collectNum = 100 // number of items that triggers collection
  16. )
  17. type expValue struct {
  18. timestamp int64
  19. id string
  20. }
  21. type storage struct {
  22. mu sync.RWMutex
  23. ids map[string][]byte
  24. exp *list.List
  25. // Number of items stored after last collection
  26. colNum int
  27. }
  28. func newStore() *storage {
  29. s := new(storage)
  30. s.ids = make(map[string][]byte)
  31. s.exp = list.New()
  32. return s
  33. }
  34. var store = newStore()
  35. func init() {
  36. rand.Seed(time.Seconds())
  37. }
  38. func randomNumbers() []byte {
  39. n := make([]byte, 6)
  40. if _, err := io.ReadFull(crand.Reader, n); err != nil {
  41. panic(err)
  42. }
  43. for i := range n {
  44. n[i] %= 10
  45. }
  46. return n
  47. }
  48. func New() string {
  49. ns := randomNumbers()
  50. id := uniuri.New()
  51. store.mu.Lock()
  52. defer store.mu.Unlock()
  53. store.ids[id] = ns
  54. store.exp.PushBack(expValue{time.Seconds(), id})
  55. store.colNum++
  56. if store.colNum > collectNum {
  57. Collect()
  58. store.colNum = 0
  59. }
  60. return id
  61. }
  62. func WriteImage(w io.Writer, id string, width, height int) os.Error {
  63. store.mu.RLock()
  64. defer store.mu.RUnlock()
  65. ns, ok := store.ids[id]
  66. if !ok {
  67. return os.NewError("captcha id not found")
  68. }
  69. return NewImage(ns, width, height).PNGEncode(w)
  70. }
  71. func Verify(w io.Writer, id string, ns []byte) bool {
  72. store.mu.Lock()
  73. defer store.mu.Unlock()
  74. realns, ok := store.ids[id]
  75. if !ok {
  76. return false
  77. }
  78. store.ids[id] = nil, false
  79. return bytes.Equal(ns, realns)
  80. }
  81. func Collect() {
  82. now := time.Seconds()
  83. store.mu.Lock()
  84. defer store.mu.Unlock()
  85. for e := store.exp.Front(); e != nil; e = e.Next() {
  86. ev, ok := e.Value.(expValue)
  87. if !ok {
  88. return
  89. }
  90. if ev.timestamp+expiration < now {
  91. store.ids[ev.id] = nil, false
  92. store.exp.Remove(e)
  93. } else {
  94. return
  95. }
  96. }
  97. }