validator.go 1.2 KB

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