Files
backend/internal/api/auth_handler.go

81 lines
2.4 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package api
import (
"encoding/json"
"errors"
"log"
"net/http"
"gitea.mrixs.me/minecraft-platform/backend/internal/core"
"gitea.mrixs.me/minecraft-platform/backend/internal/models"
)
type AuthHandler struct {
Service *core.AuthService
}
// YggdrasilError - стандартный формат ошибки для authserver
type YggdrasilError struct {
Error string `json:"error"`
ErrorMessage string `json:"errorMessage"`
}
func (h *AuthHandler) Authenticate(w http.ResponseWriter, r *http.Request) {
var req models.AuthenticateRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
response, err := h.Service.Authenticate(r.Context(), req)
if err != nil {
if errors.Is(err, core.ErrInvalidCredentials) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusForbidden) // 403
json.NewEncoder(w).Encode(YggdrasilError{
Error: "ForbiddenOperationException",
ErrorMessage: "Invalid credentials. Invalid username or password.",
})
return
}
// Другие ошибки - внутренние
log.Printf("internal server error during authentication: %v", err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(response)
}
func (h *AuthHandler) Join(w http.ResponseWriter, r *http.Request) {
var req models.JoinRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
err := h.Service.ValidateJoinRequest(r.Context(), req)
if err != nil {
// Yggdrasil ожидает 403 Forbidden при невалидной сессии
if errors.Is(err, core.ErrInvalidCredentials) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusForbidden)
json.NewEncoder(w).Encode(YggdrasilError{
Error: "ForbiddenOperationException",
ErrorMessage: "Invalid token.",
})
return
}
log.Printf("internal server error during join: %v", err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
// В случае успеха возвращаем пустой ответ со статусом 204
w.WriteHeader(http.StatusNoContent)
}