feat(http): add server and auth middleware
All checks were successful
build / Go-Build (pull_request) Successful in 55s
build / Go-Build (push) Successful in 33s

This commit is contained in:
2026-01-23 11:17:58 +01:00
parent 812a19e129
commit e9a3e807ec
2 changed files with 53 additions and 3 deletions

View File

@@ -0,0 +1,40 @@
package auth
import (
"log"
"net/http"
"strings"
"tomatentum.net/svg-templater/internal/database"
)
func AuthMiddleware(next http.Handler) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
valid, err := validateAuthHeader(r)
if err != nil {
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
log.Println("Database Query for token validation failed.\n", r)
return
}
if valid {
next.ServeHTTP(w, r)
} else {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
}
})
}
// Accepts ("Authorization": "BEARER <TOKEN>"), returns database error if query failed
func validateAuthHeader(r *http.Request) (bool, error) {
header := strings.Split(r.Header.Get("Authorization"), " ")
if len(header) < 2 {
return false, nil
}
token := header[1]
if len(strings.TrimSpace(token)) < 1 {
return false, nil
}
return database.ValidateTokenCache(token)
}