2019-06-27 17:04:25 +08:00
|
|
|
package auth
|
|
|
|
|
|
|
|
import (
|
2023-09-02 16:54:35 +08:00
|
|
|
"github.com/puzpuzpuz/xsync/v2"
|
2019-06-27 17:04:25 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
type Authenticator interface {
|
|
|
|
Verify(user string, pass string) bool
|
|
|
|
Users() []string
|
|
|
|
}
|
|
|
|
|
|
|
|
type AuthUser struct {
|
|
|
|
User string
|
|
|
|
Pass string
|
|
|
|
}
|
|
|
|
|
|
|
|
type inMemoryAuthenticator struct {
|
2023-09-02 16:54:35 +08:00
|
|
|
storage *xsync.MapOf[string, string]
|
2019-06-27 17:04:25 +08:00
|
|
|
usernames []string
|
|
|
|
}
|
|
|
|
|
|
|
|
func (au *inMemoryAuthenticator) Verify(user string, pass string) bool {
|
|
|
|
realPass, ok := au.storage.Load(user)
|
|
|
|
return ok && realPass == pass
|
|
|
|
}
|
|
|
|
|
|
|
|
func (au *inMemoryAuthenticator) Users() []string { return au.usernames }
|
|
|
|
|
|
|
|
func NewAuthenticator(users []AuthUser) Authenticator {
|
|
|
|
if len(users) == 0 {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2023-09-02 16:54:35 +08:00
|
|
|
au := &inMemoryAuthenticator{storage: xsync.NewMapOf[string]()}
|
2019-06-27 17:04:25 +08:00
|
|
|
for _, user := range users {
|
|
|
|
au.storage.Store(user.User, user.Pass)
|
|
|
|
}
|
|
|
|
usernames := make([]string, 0, len(users))
|
2023-09-02 16:54:35 +08:00
|
|
|
au.storage.Range(func(key string, value string) bool {
|
|
|
|
usernames = append(usernames, key)
|
2019-06-27 17:04:25 +08:00
|
|
|
return true
|
|
|
|
})
|
|
|
|
au.usernames = usernames
|
|
|
|
|
|
|
|
return au
|
|
|
|
}
|