-
Notifications
You must be signed in to change notification settings - Fork 71
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Refactor the Authenticator interface to a struct
- Loading branch information
1 parent
7ae7420
commit a44c4e2
Showing
3 changed files
with
17 additions
and
25 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,38 +1,30 @@ | ||
package auth | ||
|
||
type Authenticator interface { | ||
Verify(user string, pass string) bool | ||
Users() []string | ||
} | ||
import "github.com/sagernet/sing/common" | ||
|
||
type User struct { | ||
Username string `json:"username"` | ||
Password string `json:"password"` | ||
} | ||
|
||
type inMemoryAuthenticator struct { | ||
storage map[string]string | ||
usernames []string | ||
Username string | ||
Password string | ||
} | ||
|
||
func (au *inMemoryAuthenticator) Verify(username string, password string) bool { | ||
realPass, ok := au.storage[username] | ||
return ok && realPass == password | ||
type Authenticator struct { | ||
userMap map[string][]string | ||
} | ||
|
||
func (au *inMemoryAuthenticator) Users() []string { return au.usernames } | ||
|
||
func NewAuthenticator(users []User) Authenticator { | ||
func NewAuthenticator(users []User) *Authenticator { | ||
if len(users) == 0 { | ||
return nil | ||
} | ||
au := &inMemoryAuthenticator{ | ||
storage: make(map[string]string), | ||
usernames: make([]string, 0, len(users)), | ||
au := &Authenticator{ | ||
userMap: make(map[string][]string), | ||
} | ||
for _, user := range users { | ||
au.storage[user.Username] = user.Password | ||
au.usernames = append(au.usernames, user.Username) | ||
au.userMap[user.Username] = append(au.userMap[user.Username], user.Password) | ||
} | ||
return au | ||
} | ||
|
||
func (au *Authenticator) Verify(username string, password string) bool { | ||
passwordList, ok := au.userMap[username] | ||
return ok && common.Contains(passwordList, password) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters