small fixes
This commit is contained in:
@@ -59,7 +59,6 @@ func (h *AuthHandler) Join(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
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)
|
||||
@@ -75,7 +74,6 @@ func (h *AuthHandler) Join(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
// В случае успеха возвращаем пустой ответ со статусом 204
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
|
||||
@@ -9,7 +9,6 @@ import (
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
// contextKey - это тип для ключей контекста, чтобы избежать коллизий.
|
||||
type contextKey string
|
||||
|
||||
const UserIDContextKey = contextKey("userID")
|
||||
@@ -24,7 +23,7 @@ func AuthMiddleware(next http.Handler) http.Handler {
|
||||
}
|
||||
|
||||
tokenString := strings.TrimPrefix(authHeader, "Bearer ")
|
||||
if tokenString == authHeader { // Префикс "Bearer " не найден
|
||||
if tokenString == authHeader {
|
||||
http.Error(w, "Invalid token format", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
@@ -36,7 +35,6 @@ func AuthMiddleware(next http.Handler) http.Handler {
|
||||
}
|
||||
|
||||
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
|
||||
// Проверяем, что метод подписи HMAC
|
||||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, jwt.ErrSignatureInvalid
|
||||
}
|
||||
@@ -54,7 +52,6 @@ func AuthMiddleware(next http.Handler) http.Handler {
|
||||
return
|
||||
}
|
||||
|
||||
// Получаем user_id из claims. JWT хранит числа как float64.
|
||||
userIDFloat, ok := claims["user_id"].(float64)
|
||||
if !ok {
|
||||
http.Error(w, "Invalid user_id in token", http.StatusUnauthorized)
|
||||
@@ -62,7 +59,6 @@ func AuthMiddleware(next http.Handler) http.Handler {
|
||||
}
|
||||
userID := int(userIDFloat)
|
||||
|
||||
// Добавляем userID в контекст запроса для использования в хендлере
|
||||
ctx := context.WithValue(r.Context(), UserIDContextKey, userID)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
|
||||
@@ -26,7 +26,6 @@ func (h *ProfileHandler) GetProfile(w http.ResponseWriter, r *http.Request) {
|
||||
profile, err := h.Service.GetSignedProfile(r.Context(), playerUUID)
|
||||
if err != nil {
|
||||
if errors.Is(err, database.ErrUserNotFound) {
|
||||
// Yggdrasil возвращает 204 No Content, если профиль не найден
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
@@ -40,17 +39,15 @@ func (h *ProfileHandler) GetProfile(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
func (h *ProfileHandler) UploadSkin(w http.ResponseWriter, r *http.Request) {
|
||||
// Получаем userID из контекста, который был добавлен middleware
|
||||
userID, ok := r.Context().Value(UserIDContextKey).(int)
|
||||
if !ok {
|
||||
http.Error(w, "Could not get user ID from context", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
// Ограничиваем размер загружаемого файла (например, 16KB)
|
||||
r.ParseMultipartForm(16 << 10) // 16KB
|
||||
r.ParseMultipartForm(256 << 10) // 256KB
|
||||
|
||||
file, header, err := r.FormFile("skin") // "skin" - это имя поля в форме
|
||||
file, header, err := r.FormFile("skin")
|
||||
if err != nil {
|
||||
http.Error(w, "Invalid file upload", http.StatusBadRequest)
|
||||
return
|
||||
@@ -59,7 +56,6 @@ func (h *ProfileHandler) UploadSkin(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
err = h.Service.UpdateUserSkin(r.Context(), userID, file, header)
|
||||
if err != nil {
|
||||
// Можно добавить более детальную обработку ошибок
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -23,20 +23,16 @@ func (h *UserHandler) Register(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
err := h.Service.RegisterNewUser(r.Context(), req)
|
||||
if err != nil {
|
||||
// Определяем, какую ошибку вернуть клиенту
|
||||
switch {
|
||||
case errors.Is(err, database.ErrUserExists):
|
||||
http.Error(w, err.Error(), http.StatusConflict) // 409
|
||||
http.Error(w, err.Error(), http.StatusConflict)
|
||||
case errors.Is(err, core.ErrInvalidUsername), errors.Is(err, core.ErrInvalidEmail), errors.Is(err, core.ErrPasswordTooShort):
|
||||
http.Error(w, err.Error(), http.StatusBadRequest) // 400
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
default:
|
||||
// Логируем внутреннюю ошибку, но не показываем ее клиенту
|
||||
// log.Printf("internal server error: %v", err)
|
||||
http.Error(w, "Internal server error", http.StatusInternalServerError) // 500
|
||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Шаг 11 из ТЗ: Возвращаем 201 Created
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user