Skip to content

Commit

Permalink
return new errors
Browse files Browse the repository at this point in the history
  • Loading branch information
Qaleka committed Dec 16, 2024
1 parent b923f52 commit bec1089
Show file tree
Hide file tree
Showing 6 changed files with 37 additions and 22 deletions.
2 changes: 1 addition & 1 deletion internal/ads/controller/ads_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -1095,7 +1095,7 @@ func (h *AdHandler) handleError(w http.ResponseWriter, err error, requestID stri
switch err.Error() {
case "ad not found", "ad date not found", "image not found":
statusCode = http.StatusNotFound
case "ad already exists", "RoomsNumber out of range", "not owner of ad":
case "ad already exists", "roomsNumber out of range", "not owner of ad":
statusCode = http.StatusConflict
case "no active session", "missing X-CSRF-Token header",
"invalid JWT token", "user is not host", "session not found", "user ID not found in session":
Expand Down
25 changes: 15 additions & 10 deletions internal/auth/controller/auth_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -807,25 +807,32 @@ func (h *AuthHandler) handleError(w http.ResponseWriter, err error, requestID st
"username and password are required",
"invalid credentials",
"csrf_token already exists",
"Input contains invalid characters",
"Input exceeds character limit",
"Invalid size, type or resolution of image",
"input contains invalid characters",
"input exceeds character limit",
"invalid size, type or resolution of image",
"invalid metadata JSON",
"missing X-CSRF-Token header",
"invalid JWT token",
"invalid type for id in session data",
"invalid type for avatar in session data":
"invalid type for avatar in session data",
"token invalid",
"token expired",
"file type is not allowed, please use (png, jpg, jpeg) types",
"unsupported image format",
"image resolution exceeds maximum allowed size of 2000 x 2000":
statusCode = http.StatusBadRequest

case "user already exists",
"email already exists",
"session already exists",
"already logged in":
"already logged in",
"username or email already exists":
statusCode = http.StatusConflict

case "no active session",
"session not found",
"user ID not found in session":
"user ID not found in session",
"failed to get session id from request cookie":
statusCode = http.StatusUnauthorized

case "user not found",
Expand All @@ -850,11 +857,9 @@ func (h *AuthHandler) handleError(w http.ResponseWriter, err error, requestID st
"failed to get session data",
"failed to refresh csrf token",
"error generating random bytes for session ID",
"failed to get session id from request cookie",
"token parse error",
"token invalid",
"token expired",
"bad sign method":
"bad sign method",
"could not decode image":
statusCode = http.StatusInternalServerError

default:
Expand Down
10 changes: 5 additions & 5 deletions internal/service/validation/validation.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,9 @@ func ValidateName(name string) bool {
}

func ValidateImages(files [][]byte, maxSize int64, allowedMimeTypes []string, maxWidth, maxHeight int) error {
for i, file := range files {
for _, file := range files {
if err := ValidateImage(file, maxSize, allowedMimeTypes, maxWidth, maxHeight); err != nil {
return fmt.Errorf("file at index %d is invalid: %w", i, err)
return err
}
}
return nil
Expand All @@ -56,7 +56,7 @@ func ValidateImage(file []byte, maxSize int64, allowedMimeTypes []string, maxWid
}
}
if !allowed {
return fmt.Errorf("file type %s is not allowed", mimeType)
return errors.New("file type is not allowed, please use (png, jpg, jpeg) types")
}

var img image.Image
Expand All @@ -72,13 +72,13 @@ func ValidateImage(file []byte, maxSize int64, allowedMimeTypes []string, maxWid
return errors.New("unsupported image format")
}
if err != nil {
return fmt.Errorf("could not decode image: %v", err)
return errors.New("could not decode image")
}

width := img.Bounds().Dx()
height := img.Bounds().Dy()
if width > maxWidth || height > maxHeight {
return fmt.Errorf("image resolution exceeds maximum allowed size of %dx%d", maxWidth, maxHeight)
return errors.New("image resolution exceeds maximum allowed size of 2000 x 2000")
}

return nil
Expand Down
8 changes: 4 additions & 4 deletions microservices/ads_service/usecase/ads_usecase.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,12 +103,12 @@ func (uc *adUseCase) CreatePlace(ctx context.Context, place *domain.Ad, files []
const minRooms, maxRooms = 1, 100
if newPlace.RoomsNumber < minRooms || newPlace.RoomsNumber > maxRooms {
logger.AccessLogger.Warn("RoomsNumber out of range", zap.String("request_id", requestID))
return errors.New("RoomsNumber out of range")
return errors.New("roomsNumber out of range")
}

if err := validation.ValidateImages(files, 5<<20, []string{"image/jpeg", "image/png", "image/jpg"}, 2000, 2000); err != nil {
logger.AccessLogger.Warn("Invalid image", zap.String("request_id", requestID), zap.Error(err))
return errors.New("invalid size, type or resolution of image")
return err
}

err := uc.adRepository.CreatePlace(ctx, place, newPlace, userId)
Expand Down Expand Up @@ -147,7 +147,7 @@ func (uc *adUseCase) UpdatePlace(ctx context.Context, place *domain.Ad, adId str
if len(files) > 0 {
if err := validation.ValidateImages(files, 5<<20, []string{"image/jpeg", "image/png", "image/jpg"}, 2000, 2000); err != nil {
logger.AccessLogger.Warn("Invalid image", zap.String("request_id", requestID), zap.Error(err))
return errors.New("invalid size, type or resolution of image")
return err
}
}

Expand Down Expand Up @@ -178,7 +178,7 @@ func (uc *adUseCase) UpdatePlace(ctx context.Context, place *domain.Ad, adId str
const minRooms, maxRooms = 1, 100
if updatedPlace.RoomsNumber < minRooms || updatedPlace.RoomsNumber > maxRooms {
logger.AccessLogger.Warn("RoomsNumber out of range", zap.String("request_id", requestID))
return errors.New("RoomsNumber out of range")
return errors.New("roomsNumber out of range")
}

_, err := uc.adRepository.GetPlaceById(ctx, adId)
Expand Down
12 changes: 11 additions & 1 deletion microservices/auth_service/repository/auth_repository.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"errors"
"go.uber.org/zap"
"gorm.io/gorm"
"strings"
"time"
)

Expand Down Expand Up @@ -82,12 +83,21 @@ func (r *authRepository) PutUser(ctx context.Context, creds *domain.User, userID
duration := time.Since(start).Seconds()
metrics.RepoRequestDuration.WithLabelValues("PutUser").Observe(duration)
}()

if err := r.db.Model(&domain.User{}).Where("UUID = ?", userID).Updates(creds).Error; err != nil {
if strings.Contains(err.Error(), "duplicate key value violates unique constraint") {
logger.DBLogger.Warn("Unique constraint violation", zap.String("request_id", requestID), zap.String("userID", userID), zap.Error(err))
return errors.New("username or email already exists")
}
logger.DBLogger.Error("Error updating user", zap.String("request_id", requestID), zap.String("userID", userID), zap.Error(err))
return errors.New("error updating user")
}
//для булевых false

if err := r.db.Model(&domain.User{}).Where("UUID = ?", userID).Update("isHost", creds.IsHost).Error; err != nil {
if strings.Contains(err.Error(), "duplicate key value violates unique constraint") {
logger.DBLogger.Warn("Unique constraint violation on isHost", zap.String("request_id", requestID), zap.String("userID", userID), zap.Error(err))
return errors.New("username or email already exists")
}
logger.DBLogger.Error("Error updating user", zap.String("request_id", requestID), zap.String("userID", userID), zap.Error(err))
return errors.New("error updating user")
}
Expand Down
2 changes: 1 addition & 1 deletion microservices/auth_service/usecase/auth_usecase.go
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ func (uc *authUseCase) PutUser(ctx context.Context, creds *domain.User, userID s
if avatar != nil {
if err := validation.ValidateImage(avatar, 5<<20, []string{"image/jpeg", "image/png", "image/jpg"}, 2000, 2000); err != nil {
logger.AccessLogger.Warn("Invalid size, type or resolution of image", zap.String("request_id", requestID), zap.Error(err))
return errors.New("invalid size, type or resolution of image")
return err
}
}

Expand Down

0 comments on commit bec1089

Please sign in to comment.