feat: add data validation and structured logging
This commit is contained in:
@@ -8,6 +8,7 @@ import (
|
||||
|
||||
"gitea.mrixs.me/minecraft-platform/backend/internal/core"
|
||||
"gitea.mrixs.me/minecraft-platform/backend/internal/models"
|
||||
"gitea.mrixs.me/minecraft-platform/backend/internal/utils"
|
||||
)
|
||||
|
||||
type AuthHandler struct {
|
||||
@@ -27,6 +28,13 @@ func (h *AuthHandler) Authenticate(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
if validationErrors := utils.ValidateStruct(req); validationErrors != nil {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
json.NewEncoder(w).Encode(validationErrors)
|
||||
return
|
||||
}
|
||||
|
||||
response, err := h.Service.Authenticate(r.Context(), req)
|
||||
if err != nil {
|
||||
if errors.Is(err, core.ErrInvalidCredentials) {
|
||||
@@ -57,6 +65,13 @@ func (h *AuthHandler) Join(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
if validationErrors := utils.ValidateStruct(req); validationErrors != nil {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
json.NewEncoder(w).Encode(validationErrors)
|
||||
return
|
||||
}
|
||||
|
||||
err := h.Service.ValidateJoinRequest(r.Context(), req)
|
||||
if err != nil {
|
||||
if errors.Is(err, core.ErrInvalidCredentials) {
|
||||
@@ -84,6 +99,13 @@ func (h *AuthHandler) Login(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
if validationErrors := utils.ValidateStruct(req); validationErrors != nil {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
json.NewEncoder(w).Encode(validationErrors)
|
||||
return
|
||||
}
|
||||
|
||||
token, user, err := h.Service.LoginUser(r.Context(), req)
|
||||
if err != nil {
|
||||
if errors.Is(err, core.ErrInvalidCredentials) {
|
||||
|
||||
@@ -4,11 +4,13 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
|
||||
"gitea.mrixs.me/minecraft-platform/backend/internal/core"
|
||||
"gitea.mrixs.me/minecraft-platform/backend/internal/database"
|
||||
"gitea.mrixs.me/minecraft-platform/backend/internal/models"
|
||||
"gitea.mrixs.me/minecraft-platform/backend/internal/utils"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
@@ -23,13 +25,18 @@ func (h *UserHandler) Register(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
// --- ДОБАВЛЕНО ЛОГИРОВАНИЕ ---
|
||||
log.Printf("[Handler] Received registration request for username: '%s', email: '%s'", req.Username, req.Email)
|
||||
if validationErrors := utils.ValidateStruct(req); validationErrors != nil {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
json.NewEncoder(w).Encode(validationErrors)
|
||||
return
|
||||
}
|
||||
|
||||
slog.Info("Received registration request", "username", req.Username, "email", req.Email)
|
||||
|
||||
err := h.Service.RegisterNewUser(r.Context(), req)
|
||||
if err != nil {
|
||||
// --- ДОБАВЛЕНО ЛОГИРОВАНИЕ ОШИБКИ ---
|
||||
log.Printf("[Handler] Service returned error: %v", err)
|
||||
slog.Error("Service returned error", "error", err)
|
||||
|
||||
switch {
|
||||
case errors.Is(err, database.ErrUserExists):
|
||||
@@ -42,8 +49,7 @@ func (h *UserHandler) Register(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
// --- ДОБАВЛЕНО ЛОГИРОВАНИЕ УСПЕХА ---
|
||||
log.Printf("[Handler] User '%s' registered successfully.", req.Username)
|
||||
slog.Info("User registered successfully", "username", req.Username)
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
}
|
||||
|
||||
|
||||
@@ -9,8 +9,8 @@ type Agent struct {
|
||||
// AuthenticateRequest - это тело запроса на /authserver/authenticate
|
||||
type AuthenticateRequest struct {
|
||||
Agent Agent `json:"agent"`
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
Username string `json:"username" validate:"required"`
|
||||
Password string `json:"password" validate:"required"`
|
||||
ClientToken string `json:"clientToken"`
|
||||
}
|
||||
|
||||
@@ -70,15 +70,15 @@ type SessionProfileResponse struct {
|
||||
|
||||
// JoinRequest - это тело запроса на /sessionserver/session/minecraft/join
|
||||
type JoinRequest struct {
|
||||
AccessToken string `json:"accessToken"`
|
||||
SelectedProfile string `json:"selectedProfile"` // UUID пользователя без дефисов
|
||||
ServerID string `json:"serverId"`
|
||||
AccessToken string `json:"accessToken" validate:"required"`
|
||||
SelectedProfile string `json:"selectedProfile" validate:"required"` // UUID пользователя без дефисов
|
||||
ServerID string `json:"serverId" validate:"required"`
|
||||
}
|
||||
|
||||
// LoginRequest - это тело запроса на /api/login
|
||||
type LoginRequest struct {
|
||||
Login string `json:"login"`
|
||||
Password string `json:"password"`
|
||||
Login string `json:"login" validate:"required"`
|
||||
Password string `json:"password" validate:"required"`
|
||||
}
|
||||
|
||||
// LoginResponse - это тело успешного ответа с JWT
|
||||
|
||||
@@ -20,9 +20,9 @@ type User struct {
|
||||
|
||||
// RegisterRequest определяет структуру JSON-запроса на регистрацию
|
||||
type RegisterRequest struct {
|
||||
Username string `json:"username"`
|
||||
Email string `json:"email"`
|
||||
Password string `json:"password"`
|
||||
Username string `json:"username" validate:"required,min=3,max=16,alphanum"`
|
||||
Email string `json:"email" validate:"required,email"`
|
||||
Password string `json:"password" validate:"required,min=8"`
|
||||
}
|
||||
type Profile struct {
|
||||
ID int `json:"-"`
|
||||
|
||||
47
internal/utils/validator.go
Normal file
47
internal/utils/validator.go
Normal file
@@ -0,0 +1,47 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/go-playground/validator/v10"
|
||||
)
|
||||
|
||||
var validate *validator.Validate
|
||||
|
||||
func init() {
|
||||
validate = validator.New()
|
||||
}
|
||||
|
||||
// ValidationErrorResponse represents the structure of validation errors returned to the client
|
||||
type ValidationErrorResponse struct {
|
||||
Errors map[string]string `json:"errors"`
|
||||
}
|
||||
|
||||
// ValidateStruct validates a struct based on its tags using go-playground/validator
|
||||
func ValidateStruct(s interface{}) *ValidationErrorResponse {
|
||||
err := validate.Struct(s)
|
||||
if err != nil {
|
||||
var errorsMap = make(map[string]string)
|
||||
for _, err := range err.(validator.ValidationErrors) {
|
||||
// Simpler error messages for now. Can be enhanced with universal-translator.
|
||||
fieldName := strings.ToLower(err.Field())
|
||||
switch err.Tag() {
|
||||
case "required":
|
||||
errorsMap[fieldName] = fmt.Sprintf("Field '%s' is required", fieldName)
|
||||
case "email":
|
||||
errorsMap[fieldName] = fmt.Sprintf("Field '%s' must be a valid email", fieldName)
|
||||
case "min":
|
||||
errorsMap[fieldName] = fmt.Sprintf("Field '%s' must be at least %s characters long", fieldName, err.Param())
|
||||
case "max":
|
||||
errorsMap[fieldName] = fmt.Sprintf("Field '%s' must be at most %s characters long", fieldName, err.Param())
|
||||
case "alphanum":
|
||||
errorsMap[fieldName] = fmt.Sprintf("Field '%s' must contain only alphanumeric characters", fieldName)
|
||||
default:
|
||||
errorsMap[fieldName] = fmt.Sprintf("Field '%s' failed validation on '%s' tag", fieldName, err.Tag())
|
||||
}
|
||||
}
|
||||
return &ValidationErrorResponse{Errors: errorsMap}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user