-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
82 lines (70 loc) · 1.93 KB
/
auth.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
75
76
77
78
79
80
81
82
package main
import (
"encoding/base64"
"net/http"
"strings"
)
// Auth is in what ways we protect the REST endpoints, both in and out
type Auth struct {
Fail bool `json:"fail" yaml:"fail"`
Anonymous bool `json:"anon" yaml:"anon"`
Bearer string `json:"bearer" yaml:"bearer"`
Basic map[string]string `json:"basic" yaml:"basic"`
}
var (
//errAnonymousNotEnabled = stringError("Anonymous is not enabled")
errAuthRequired = stringError("Authorization-header is missing")
errAuthMalformed = stringError("Authorization-header is mal-formed")
invalidAuthBearer = invalidError("Auth-Bearer")
invalidAuthBasic = invalidError("Auth-Basic")
invalidAuthUnknown = stringError("unknown user")
errFail = stringError("forced-fail")
)
// Validate that a request is authorized to pass
func (auth Auth) Validate(r *http.Request) (bool, error) {
if err := auth.VerifyAuthorization(r); err != nil {
return false, err
}
if auth.Fail {
return false, errFail
}
return true, nil
}
// VerifyAuthorization checks the 'Authorization' header, if needed
func (auth Auth) VerifyAuthorization(r *http.Request) error {
// if auth.Bearer == "" && len(auth.Basic) == 0 {
if auth.Anonymous {
return nil
}
// return errAnonymousNotEnabled
// }
header := r.Header.Get("Authorization")
if header == "" {
return errAuthRequired
}
parts := strings.SplitN(header, " ", 2)
if len(parts) != 2 {
return errAuthMalformed
}
switch strings.ToLower(parts[0]) {
case "basic":
decoded, err := base64.StdEncoding.DecodeString(parts[1])
if err != nil {
return invalidAuthBasic
}
creds := strings.SplitN(string(decoded), ":", 2)
if len(creds) == 2 {
if auth.Basic[creds[0]] == creds[1] {
return nil
}
return invalidAuthUnknown
}
return invalidAuthBasic
case "bearer":
if parts[1] == auth.Bearer {
return nil
}
return invalidAuthBearer
}
return errAuthMalformed
}