Wrap up 1.1.0
This commit is contained in:
@@ -1,9 +1,11 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/sirrobot01/decypharr/internal/config"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func (wb *Web) setupMiddleware(next http.Handler) http.Handler {
|
||||
@@ -33,19 +35,51 @@ func (wb *Web) authMiddleware(next http.Handler) http.Handler {
|
||||
return
|
||||
}
|
||||
|
||||
isAPI := wb.isAPIRequest(r)
|
||||
|
||||
if cfg.NeedsAuth() {
|
||||
http.Redirect(w, r, "/register", http.StatusSeeOther)
|
||||
if isAPI {
|
||||
wb.sendJSONError(w, "Authentication setup required", http.StatusUnauthorized)
|
||||
} else {
|
||||
http.Redirect(w, r, "/register", http.StatusSeeOther)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Check for API token first
|
||||
if wb.isValidAPIToken(r) {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
// Fall back to session authentication
|
||||
session, _ := wb.cookie.Get(r, "auth-session")
|
||||
auth, ok := session.Values["authenticated"].(bool)
|
||||
|
||||
if !ok || !auth {
|
||||
http.Redirect(w, r, "/login", http.StatusSeeOther)
|
||||
if isAPI {
|
||||
wb.sendJSONError(w, "Authentication required. Please provide a valid API token in the Authorization header (Bearer <token>) or authenticate via session cookies.", http.StatusUnauthorized)
|
||||
} else {
|
||||
http.Redirect(w, r, "/login", http.StatusSeeOther)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
// isAPIRequest checks if the request is for an API endpoint
|
||||
func (wb *Web) isAPIRequest(r *http.Request) bool {
|
||||
return strings.HasPrefix(r.URL.Path, "/api/")
|
||||
}
|
||||
|
||||
// sendJSONError sends a JSON error response
|
||||
func (wb *Web) sendJSONError(w http.ResponseWriter, message string, statusCode int) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(statusCode)
|
||||
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"error": message,
|
||||
"status": statusCode,
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user