summaryrefslogtreecommitdiff
path: root/internal/middleware/ai_auth.go
blob: 3c04a372765f2eddfd655e9fc6a124a1f715e926 (plain)
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
package middleware

import (
	"net/http"
	"strings"
)

// AIAuthMiddleware validates Bearer token for AI agent access
func AIAuthMiddleware(validToken string) func(http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			// Skip auth if no token configured
			if validToken == "" {
				respondError(w, http.StatusServiceUnavailable, "ai_disabled", "AI agent access not configured")
				return
			}

			authHeader := r.Header.Get("Authorization")

			if authHeader == "" {
				respondError(w, http.StatusUnauthorized, "unauthorized", "Missing Authorization header")
				return
			}

			if !strings.HasPrefix(authHeader, "Bearer ") {
				respondError(w, http.StatusUnauthorized, "unauthorized", "Invalid Authorization header format")
				return
			}

			token := strings.TrimPrefix(authHeader, "Bearer ")
			if token != validToken {
				respondError(w, http.StatusUnauthorized, "unauthorized", "Invalid or missing token")
				return
			}

			next.ServeHTTP(w, r)
		})
	}
}

// respondError sends a JSON error response
func respondError(w http.ResponseWriter, status int, error, message string) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(status)
	w.Write([]byte(`{"error":"` + error + `","message":"` + message + `"}`))
}