validator.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package trojan
  2. import (
  3. "strings"
  4. "sync"
  5. "github.com/xtls/xray-core/common/protocol"
  6. )
  7. // Validator stores valid trojan users.
  8. type Validator struct {
  9. // Considering email's usage here, map + sync.Mutex/RWMutex may have better performance.
  10. email sync.Map
  11. users sync.Map
  12. }
  13. // Add a trojan user, Email must be empty or unique.
  14. func (v *Validator) Add(u *protocol.MemoryUser) error {
  15. if u.Email != "" {
  16. _, loaded := v.email.LoadOrStore(strings.ToLower(u.Email), u)
  17. if loaded {
  18. return newError("User ", u.Email, " already exists.")
  19. }
  20. }
  21. v.users.Store(hexString(u.Account.(*MemoryAccount).Key), u)
  22. return nil
  23. }
  24. // Del a trojan user with a non-empty Email.
  25. func (v *Validator) Del(e string) error {
  26. if e == "" {
  27. return newError("Email must not be empty.")
  28. }
  29. le := strings.ToLower(e)
  30. u, _ := v.email.Load(le)
  31. if u == nil {
  32. return newError("User ", e, " not found.")
  33. }
  34. v.email.Delete(le)
  35. v.users.Delete(hexString(u.(*protocol.MemoryUser).Account.(*MemoryAccount).Key))
  36. return nil
  37. }
  38. // Get a trojan user with hashed key, nil if user doesn't exist.
  39. func (v *Validator) Get(hash string) *protocol.MemoryUser {
  40. u, _ := v.users.Load(hash)
  41. if u != nil {
  42. return u.(*protocol.MemoryUser)
  43. }
  44. return nil
  45. }