validator.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. // +build !confonly
  2. package trojan
  3. import (
  4. "strings"
  5. "sync"
  6. "v2ray.com/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 newError("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 newError("Email must not be empty.")
  29. }
  30. le := strings.ToLower(e)
  31. u, _ := v.email.Load(le)
  32. if u == nil {
  33. return newError("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. }