validator.go 1.3 KB

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