2020-09-26 11:31:24 -04:00
|
|
|
package trojan
|
|
|
|
|
|
|
|
import (
|
2020-10-22 00:01:26 -04:00
|
|
|
"strings"
|
2020-09-26 11:31:24 -04:00
|
|
|
"sync"
|
|
|
|
|
|
|
|
"v2ray.com/core/common/protocol"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Validator stores valid trojan users
|
|
|
|
type Validator struct {
|
2020-10-22 00:01:26 -04:00
|
|
|
// Considering email's usage here, map + sync.Mutex/RWMutex may have better performance.
|
|
|
|
email sync.Map
|
2020-09-26 11:31:24 -04:00
|
|
|
users sync.Map
|
|
|
|
}
|
|
|
|
|
|
|
|
// Add a trojan user
|
|
|
|
func (v *Validator) Add(u *protocol.MemoryUser) error {
|
2020-10-22 00:01:26 -04:00
|
|
|
if u.Email != "" {
|
|
|
|
_, loaded := v.email.LoadOrStore(strings.ToLower(u.Email), u)
|
|
|
|
if loaded {
|
|
|
|
return newError("User ", u.Email, " already exists.")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
v.users.Store(hexString(u.Account.(*MemoryAccount).Key), u)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Del a trojan user
|
|
|
|
func (v *Validator) Del(e string) error {
|
|
|
|
if e == "" {
|
|
|
|
return newError("Email must not be empty.")
|
|
|
|
}
|
|
|
|
le := strings.ToLower(e)
|
|
|
|
u, _ := v.email.Load(le)
|
|
|
|
if u == nil {
|
|
|
|
return newError("User ", e, " not found.")
|
|
|
|
}
|
|
|
|
v.email.Delete(le)
|
|
|
|
v.users.Delete(hexString(u.(*protocol.MemoryUser).Account.(*MemoryAccount).Key))
|
2020-09-26 11:31:24 -04:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Get user with hashed key, nil if user doesn't exist.
|
|
|
|
func (v *Validator) Get(hash string) *protocol.MemoryUser {
|
|
|
|
u, _ := v.users.Load(hash)
|
|
|
|
if u != nil {
|
|
|
|
return u.(*protocol.MemoryUser)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|