feat(profile): implement protected skin upload endpoint

This commit is contained in:
2025-06-16 07:20:09 +03:00
parent 9082b21a5d
commit 9c7940a70a
7 changed files with 186 additions and 9 deletions

View File

@@ -0,0 +1,69 @@
package api
import (
"context"
"net/http"
"os"
"strings"
"github.com/golang-jwt/jwt/v5"
)
// contextKey - это тип для ключей контекста, чтобы избежать коллизий.
type contextKey string
const UserIDContextKey = contextKey("userID")
// AuthMiddleware проверяет JWT токен и добавляет user_id в контекст запроса.
func AuthMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
authHeader := r.Header.Get("Authorization")
if authHeader == "" {
http.Error(w, "Authorization header required", http.StatusUnauthorized)
return
}
tokenString := strings.TrimPrefix(authHeader, "Bearer ")
if tokenString == authHeader { // Префикс "Bearer " не найден
http.Error(w, "Invalid token format", http.StatusUnauthorized)
return
}
jwtSecret := []byte(os.Getenv("JWT_SECRET_KEY"))
if len(jwtSecret) == 0 {
http.Error(w, "JWT secret not configured", http.StatusInternalServerError)
return
}
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
// Проверяем, что метод подписи HMAC
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, jwt.ErrSignatureInvalid
}
return jwtSecret, nil
})
if err != nil || !token.Valid {
http.Error(w, "Invalid or expired token", http.StatusUnauthorized)
return
}
claims, ok := token.Claims.(jwt.MapClaims)
if !ok {
http.Error(w, "Invalid token claims", http.StatusUnauthorized)
return
}
// Получаем user_id из claims. JWT хранит числа как float64.
userIDFloat, ok := claims["user_id"].(float64)
if !ok {
http.Error(w, "Invalid user_id in token", http.StatusUnauthorized)
return
}
userID := int(userIDFloat)
// Добавляем userID в контекст запроса для использования в хендлере
ctx := context.WithValue(r.Context(), UserIDContextKey, userID)
next.ServeHTTP(w, r.WithContext(ctx))
})
}

View File

@@ -38,3 +38,32 @@ func (h *ProfileHandler) GetProfile(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(profile)
}
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
file, header, err := r.FormFile("skin") // "skin" - это имя поля в форме
if err != nil {
http.Error(w, "Invalid file upload", http.StatusBadRequest)
return
}
defer file.Close()
err = h.Service.UpdateUserSkin(r.Context(), userID, file, header)
if err != nil {
// Можно добавить более детальную обработку ошибок
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
w.WriteHeader(http.StatusOK)
w.Write([]byte("Skin updated successfully"))
}