From 44c1f56e9f6288848e431ee68abeb053137cd120 Mon Sep 17 00:00:00 2001 From: Yanislav Igonin Date: Sun, 10 Oct 2021 10:41:36 +0300 Subject: [PATCH] feat: add files size check --- controllers/threads_controller.go | 17 +++++++++++++++++ repositories/structs.go | 1 + utils/utils.go | 17 +++++++++++++++++ 3 files changed, 35 insertions(+) diff --git a/controllers/threads_controller.go b/controllers/threads_controller.go index 784f3a4..a7fde5e 100644 --- a/controllers/threads_controller.go +++ b/controllers/threads_controller.go @@ -125,6 +125,14 @@ func CreateThread(c *gin.Context) { } filesInRequest := form.File["files"] + isFilesSizesNotToBig := Utils.CheckFilesSize(filesInRequest) + if !isFilesSizesNotToBig { + errorHtmlData := Repositories.BadRequestHtmlData{ + Message: Repositories.InvalidFileSizeMessage, + } + c.HTML(http.StatusInternalServerError, "400.html", errorHtmlData) + return + } conn, err := Db.Pool.Acquire(context.TODO()) if err != nil { @@ -249,6 +257,15 @@ func UpdateThread(c *gin.Context) { } filesInRequest := form.File["files"] + isFilesSizesNotToBig := Utils.CheckFilesSize(filesInRequest) + if !isFilesSizesNotToBig { + errorHtmlData := Repositories.BadRequestHtmlData{ + Message: Repositories.InvalidFileSizeMessage, + } + c.HTML(http.StatusInternalServerError, "400.html", errorHtmlData) + return + } + isSageField := form.Value["sage"] var isSageString string if len(isSageField) != 0 { diff --git a/repositories/structs.go b/repositories/structs.go index b3c5e4e..541f08f 100644 --- a/repositories/structs.go +++ b/repositories/structs.go @@ -59,3 +59,4 @@ type BadRequestHtmlData struct { var InvalidTitleOrTextErrorMessage = "TITLE OR TEXT SHOULD NOT BE EMPTY" var InvalidCaptchaErrorMessage = "INVALID CAPTCHA" +var InvalidFileSizeMessage = "FILE SIZE EXCIDED (3MB PER FILE)" diff --git a/utils/utils.go b/utils/utils.go index b407a20..96901bf 100644 --- a/utils/utils.go +++ b/utils/utils.go @@ -5,6 +5,7 @@ import ( "image" "image/jpeg" "image/png" + "mime/multipart" "os" "path/filepath" "strconv" @@ -13,6 +14,7 @@ import ( ) var UPLOADS_DIR_PATH = "uploads" +var FILE_SIZE_IN_BYTES = 3145728 // 3MB // Check dir existence. func CheckIfFolderExists(path string) bool { @@ -63,12 +65,27 @@ func CreateThreadFolder(postID int) error { return nil } +// TODO: add files length check func ValidatePost(title, text string) bool { return (title == "" && text != "") || (title != "" && text == "") || (title != "" && text != "") } +func CheckFilesSize(files []*multipart.FileHeader) bool { + for _, file := range files { + if file.Size > int64(FILE_SIZE_IN_BYTES) { + return false + } + } + + return true +} + +// func CheckFilesExt(){ + +// } + func MakeImageThumbnail(originalPath, ext string, threadID, fileID int) (*image.NRGBA, error) { img, err := imaging.Open(originalPath, imaging.AutoOrientation(true)) if err != nil {