-
Notifications
You must be signed in to change notification settings - Fork 13
/
checker.go
74 lines (63 loc) · 1.92 KB
/
checker.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package basicauth
import (
"crypto/subtle"
"strings"
"github.com/pkg/errors"
)
// Credentials is a set of credentials with the added functionality of
// decoding.
type Credentials []Credential
// Decode implements the envdecode contract, allowing Credentials to be used in
// config structs.
func (c *Credentials) Decode(repl string) error {
s := strings.Split(repl, ";")
result := make([]Credential, 0, len(s))
for _, part := range s {
cred, err := parseCredential(part)
if err != nil {
return err
}
result = append(result, cred)
}
*c = result
return nil
}
// Credential is a valid username/password pair used to authenticate HTTP
// requests using basic auth.
type Credential struct {
Username string
Password string
}
var errMalformedCredentials = errors.New("malformed credentials")
func parseCredential(credential string) (Credential, error) {
parts := strings.SplitN(credential, ":", 2)
if len(parts) != 2 {
return Credential{}, errMalformedCredentials
} else if parts[0] == "" && parts[1] == "" {
return Credential{}, errMalformedCredentials
}
return Credential{Username: parts[0], Password: parts[1]}, nil
}
// Checker stores a set of valid credentials to be used when authenticating
// HTTP requests using basic auth.
type Checker struct {
credentials []Credential
}
// NewChecker returns a basic auth checker configured to use credentials
// when checking for valid authentication.
func NewChecker(credentials []Credential) *Checker {
return &Checker{
credentials: credentials,
}
}
// Valid is true if username and password represent acceptable credentials.
func (c *Checker) Valid(username, password string) bool {
for _, cred := range c.credentials {
userValid := subtle.ConstantTimeCompare([]byte(cred.Username), []byte(username)) == 1
passwordValid := subtle.ConstantTimeCompare([]byte(cred.Password), []byte(password)) == 1
if userValid && passwordValid {
return true
}
}
return false
}