authkit initial
This commit is contained in:
parent
5173b0a43d
commit
134393fbca
43 changed files with 5188 additions and 1 deletions
64
extractor.go
Normal file
64
extractor.go
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
package authkit
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Extractor pulls a credential string out of an HTTP request. It returns
|
||||
// (value, true) when a value was found, otherwise ("", false).
|
||||
type Extractor func(r *http.Request) (string, bool)
|
||||
|
||||
// BearerExtractor reads the value following "Bearer " in the Authorization
|
||||
// header. Comparison is case-insensitive on the scheme.
|
||||
func BearerExtractor() Extractor {
|
||||
return func(r *http.Request) (string, bool) {
|
||||
h := r.Header.Get("Authorization")
|
||||
if h == "" {
|
||||
return "", false
|
||||
}
|
||||
const prefix = "bearer "
|
||||
if len(h) <= len(prefix) || !strings.EqualFold(h[:len(prefix)], prefix) {
|
||||
return "", false
|
||||
}
|
||||
v := strings.TrimSpace(h[len(prefix):])
|
||||
if v == "" {
|
||||
return "", false
|
||||
}
|
||||
return v, true
|
||||
}
|
||||
}
|
||||
|
||||
// CookieExtractor reads the named cookie's value.
|
||||
func CookieExtractor(name string) Extractor {
|
||||
return func(r *http.Request) (string, bool) {
|
||||
c, err := r.Cookie(name)
|
||||
if err != nil || c.Value == "" {
|
||||
return "", false
|
||||
}
|
||||
return c.Value, true
|
||||
}
|
||||
}
|
||||
|
||||
// HeaderExtractor reads a custom header verbatim.
|
||||
func HeaderExtractor(name string) Extractor {
|
||||
return func(r *http.Request) (string, bool) {
|
||||
v := strings.TrimSpace(r.Header.Get(name))
|
||||
if v == "" {
|
||||
return "", false
|
||||
}
|
||||
return v, true
|
||||
}
|
||||
}
|
||||
|
||||
// ChainExtractors tries each extractor in order, returning the first hit.
|
||||
func ChainExtractors(es ...Extractor) Extractor {
|
||||
return func(r *http.Request) (string, bool) {
|
||||
for _, e := range es {
|
||||
if v, ok := e(r); ok {
|
||||
return v, true
|
||||
}
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue