Add AI service API token auth
This commit is contained in:
30
internal/httpapi/auth.go
Normal file
30
internal/httpapi/auth.go
Normal file
@@ -0,0 +1,30 @@
|
||||
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 "):])
|
||||
}
|
||||
Reference in New Issue
Block a user