validator.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package trojan
  2. import (
  3. "strings"
  4. "sync"
  5. "github.com/xtls/xray-core/common/errors"
  6. "github.com/xtls/xray-core/common/protocol"
  7. )
  8. // Validator stores valid trojan users.
  9. type Validator struct {
  10. // Considering email's usage here, map + sync.Mutex/RWMutex may have better performance.
  11. email sync.Map
  12. users sync.Map
  13. }
  14. // Add a trojan user, Email must be empty or unique.
  15. func (v *Validator) Add(u *protocol.MemoryUser) error {
  16. if u.Email != "" {
  17. _, loaded := v.email.LoadOrStore(strings.ToLower(u.Email), u)
  18. if loaded {
  19. return errors.New("User ", u.Email, " already exists.")
  20. }
  21. }
  22. v.users.Store(hexString(u.Account.(*MemoryAccount).Key), u)
  23. return nil
  24. }
  25. // Del a trojan user with a non-empty Email.
  26. func (v *Validator) Del(e string) error {
  27. if e == "" {
  28. return errors.New("Email must not be empty.")
  29. }
  30. le := strings.ToLower(e)
  31. u, _ := v.email.Load(le)
  32. if u == nil {
  33. return errors.New("User ", e, " not found.")
  34. }
  35. v.email.Delete(le)
  36. v.users.Delete(hexString(u.(*protocol.MemoryUser).Account.(*MemoryAccount).Key))
  37. return nil
  38. }
  39. // Get a trojan user with hashed key, nil if user doesn't exist.
  40. func (v *Validator) Get(hash string) *protocol.MemoryUser {
  41. u, _ := v.users.Load(hash)
  42. if u != nil {
  43. return u.(*protocol.MemoryUser)
  44. }
  45. return nil
  46. }
  47. // Get a trojan user with hashed key, nil if user doesn't exist.
  48. func (v *Validator) GetByEmail(email string) *protocol.MemoryUser {
  49. u, _ := v.email.Load(email)
  50. if u != nil {
  51. return u.(*protocol.MemoryUser)
  52. }
  53. return nil
  54. }
  55. // Get all users
  56. func (v *Validator) GetAll() []*protocol.MemoryUser {
  57. var u = make([]*protocol.MemoryUser, 0, 100)
  58. v.email.Range(func(key, value interface{}) bool {
  59. u = append(u, value.(*protocol.MemoryUser))
  60. return true
  61. })
  62. return u
  63. }
  64. // Get users count
  65. func (v *Validator) GetCount() int64 {
  66. var c int64 = 0
  67. v.email.Range(func(key, value interface{}) bool {
  68. c++
  69. return true
  70. })
  71. return c
  72. }