You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

91 lines
1.7KB

  1. package main
  2. // Queue for pending authentication requests
  3. import (
  4. "math/rand"
  5. "sync"
  6. "time"
  7. "github.com/oklog/ulid"
  8. )
  9. type AuthenticationMap struct {
  10. requestMap map[string]*AuthRequest
  11. app *App
  12. requestMapMutex *sync.RWMutex
  13. }
  14. // Returns empty string when no request by that id is present
  15. func (q *AuthenticationMap) GetRequestByID(ID string) *AuthRequest {
  16. q.requestMapMutex.RLock()
  17. req, ok := q.requestMap[ID]
  18. q.requestMapMutex.RUnlock()
  19. if !ok {
  20. return nil
  21. }
  22. return req
  23. }
  24. func (q *AuthenticationMap) QueueRequest(r *AuthRequest) error {
  25. t := time.Unix(1000000, 0)
  26. entropy := ulid.Monotonic(rand.New(rand.NewSource(t.UnixNano())), 0)
  27. ulidID := ulid.MustNew(ulid.Timestamp(t), entropy)
  28. ID := ulidID.String()
  29. err := r.SetId(ID)
  30. if err != nil {
  31. return err
  32. }
  33. r.Queued = time.Now()
  34. q.requestMapMutex.Lock()
  35. q.requestMap[ID] = r
  36. q.requestMapMutex.Unlock()
  37. (*q.app.Logger).Info("Queued request by id: ", ID)
  38. return nil
  39. }
  40. func (q *AuthenticationMap) Init() {
  41. q.requestMap = make(map[string]*AuthRequest)
  42. q.requestMapMutex = &sync.RWMutex{}
  43. q.startRequestMapCleaner()
  44. }
  45. func (q *AuthenticationMap) startRequestMapCleaner() {
  46. go func() {
  47. for _ = range time.Tick(10 * time.Minute) {
  48. q.requestMapMutex.Lock()
  49. for key, req := range q.requestMap {
  50. // If the request has been queued for more than 30
  51. // minutes, it's time to delete it.
  52. if req.Queued.Add(30 * time.Minute).Before(time.Now()) {
  53. (*q.app.Logger).Info("Deleting inactive request with id: ", req.ID)
  54. req.Cancel()
  55. delete(q.requestMap, key)
  56. }
  57. }
  58. q.requestMapMutex.Unlock()
  59. }
  60. }()
  61. }
  62. func (q *AuthenticationMap) Delete(ID string) {
  63. q.requestMapMutex.Lock()
  64. delete(q.requestMap, ID)
  65. q.requestMapMutex.Unlock()
  66. }