Spaces:
Runtime error
Runtime error
package auth | |
import ( | |
"errors" | |
"net/http" | |
) | |
type AuthHandler struct { | |
authService *AuthService | |
} | |
func NewAuthHandler(authService *AuthService) *AuthHandler { | |
return &AuthHandler{ | |
authService: authService, | |
} | |
} | |
func (h *AuthHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { | |
if r.Method != http.MethodPost { | |
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) | |
return | |
} | |
apiKey := r.Header.Get("X-API-Key") | |
if apiKey == "" { | |
http.Error(w, "API key required", http.StatusUnauthorized) | |
return | |
} | |
token, err := h.authService.Authenticate(apiKey) | |
if err != nil { | |
if errors.Is(err, ErrInvalidAPIKey) { | |
http.Error(w, "Invalid API key", http.StatusUnauthorized) | |
} else { | |
http.Error(w, "Authentication error", http.StatusInternalServerError) | |
} | |
return | |
} | |
w.Header().Set("Content-Type", "application/json") | |
w.Write([]byte(`{"token":"` + token + `"}`)) | |
} | |