rewrite auth provider logic

This commit is contained in:
Hector
2023-06-20 22:15:12 +01:00
parent d31ea4b23c
commit 17fb995928
8 changed files with 100 additions and 51 deletions

29
auth/basic.go Normal file
View File

@ -0,0 +1,29 @@
package auth
import (
"fmt"
"net/http"
)
func NewBasicAuthProvider(username, password string) AuthProvider {
return &basicAuthProvider{
hashedAuth: encodeBasicAuth(username, password),
}
}
type basicAuthProvider struct {
hashedAuth string
}
func (p *basicAuthProvider) IsAllowed(request *http.Request) bool {
username, password, ok := request.BasicAuth()
if !ok {
return false
}
requestAuth := encodeBasicAuth(username, password)
return p.hashedAuth == requestAuth
}
func encodeBasicAuth(username, password string) string {
return HashString(fmt.Sprintf("%s:%s", username, password))
}

View File

@ -5,7 +5,7 @@ import (
"encoding/hex"
)
func Hash(data []byte) []byte {
func hash(data []byte) []byte {
if len(data) == 0 {
return []byte{}
}
@ -14,5 +14,5 @@ func Hash(data []byte) []byte {
}
func HashString(data string) string {
return hex.EncodeToString(Hash([]byte(data)))
return hex.EncodeToString(hash([]byte(data)))
}

34
auth/provider.go Normal file
View File

@ -0,0 +1,34 @@
package auth
import (
"net/http"
)
type AuthProvider interface {
IsAllowed(*http.Request) bool
}
func NewEmptyAuthProvider() AuthProvider {
return &emptyAuthProvider{}
}
type emptyAuthProvider struct {
}
func (p *emptyAuthProvider) IsAllowed(request *http.Request) bool {
return true
}
type compositeAuthProvider struct {
providers []AuthProvider
}
func (p *compositeAuthProvider) IsAllowed(request *http.Request) bool {
for i := 0; i < len(p.providers); i++ {
provider := p.providers[i]
if provider.IsAllowed(request) {
return true
}
}
return false
}