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.

64 lines
1.2 KiB

1 year ago
  1. package auth
  2. import (
  3. "context"
  4. "sync"
  5. "time"
  6. )
  7. type Service struct {
  8. Provider Provider
  9. userListMutex sync.Mutex
  10. userList []UserInfo
  11. userMap map[string]string
  12. userListTime time.Time
  13. key struct{ Stuff uint64 }
  14. key2 struct{ Stuff2 string }
  15. }
  16. func (s *Service) ValidateUser(ctx context.Context, token string) *UserInfo {
  17. return s.Provider.ValidateToken(ctx, token)
  18. }
  19. func (s *Service) AddContextUser(ctx context.Context, user UserInfo) context.Context {
  20. return context.WithValue(ctx, &s.key, &user)
  21. }
  22. func (s *Service) Users(ctx context.Context) ([]UserInfo, map[string]string, error) {
  23. s.userListMutex.Lock()
  24. if time.Since(s.userListTime) < time.Minute {
  25. m := s.userMap
  26. l := s.userList
  27. s.userListMutex.Unlock()
  28. return l, m, nil
  29. }
  30. s.userListMutex.Unlock()
  31. users, err := s.Provider.ListUsers(ctx)
  32. if err != nil {
  33. return nil, nil, err
  34. }
  35. s.userListMutex.Lock()
  36. s.userList = users
  37. s.userMap = make(map[string]string, len(users))
  38. for _, user := range users {
  39. s.userMap[user.ID] = user.Name
  40. }
  41. m := s.userMap
  42. s.userListTime = time.Now()
  43. s.userListMutex.Unlock()
  44. return users, m, nil
  45. }
  46. func (s *Service) GetUser(ctx context.Context) *UserInfo {
  47. v := ctx.Value(&s.key)
  48. if v == nil {
  49. return nil
  50. }
  51. return v.(*UserInfo)
  52. }