31 lines
706 B
Go
31 lines
706 B
Go
package httpapi
|
|
|
|
import (
|
|
"crypto/subtle"
|
|
"net/http"
|
|
"strings"
|
|
)
|
|
|
|
func (s *Server) requireAPIToken(path string, r *http.Request) bool {
|
|
if !strings.HasPrefix(path, "/api/v1/") && path != "/api/v1" {
|
|
return true
|
|
}
|
|
expected := strings.TrimSpace(s.cfg.APIAuthToken)
|
|
if expected == "" {
|
|
return true
|
|
}
|
|
got := bearerToken(r.Header.Get("Authorization"))
|
|
if got == "" {
|
|
return false
|
|
}
|
|
return subtle.ConstantTimeCompare([]byte(got), []byte(expected)) == 1
|
|
}
|
|
|
|
func bearerToken(header string) string {
|
|
header = strings.TrimSpace(header)
|
|
if len(header) < len("Bearer ") || !strings.EqualFold(header[:len("Bearer ")], "Bearer ") {
|
|
return ""
|
|
}
|
|
return strings.TrimSpace(header[len("Bearer "):])
|
|
}
|