github.com/v2fly/v2ray-core/v4@v4.45.2/proxy/trojan/validator.go (about)

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