1
0
mirror of https://github.com/pocketbase/pocketbase.git synced 2025-03-20 06:21:06 +02:00

97 lines
2.1 KiB
Go
Raw Normal View History

2022-07-07 00:19:05 +03:00
package validators
import (
"fmt"
"strings"
2022-08-26 07:00:22 +03:00
"github.com/gabriel-vasile/mimetype"
2022-07-07 00:19:05 +03:00
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/pocketbase/pocketbase/tools/filesystem"
2022-07-07 00:19:05 +03:00
)
2024-09-29 19:23:19 +03:00
// UploadedFileSize checks whether the validated [*filesystem.File]
2022-07-07 00:19:05 +03:00
// size is no more than the provided maxBytes.
//
// Example:
2023-02-23 21:51:42 +02:00
//
2022-07-07 00:19:05 +03:00
// validation.Field(&form.File, validation.By(validators.UploadedFileSize(1000)))
2024-09-29 19:23:19 +03:00
func UploadedFileSize(maxBytes int64) validation.RuleFunc {
2022-07-07 00:19:05 +03:00
return func(value any) error {
2024-09-29 19:23:19 +03:00
v, ok := value.(*filesystem.File)
if !ok {
return ErrUnsupportedValueType
}
2022-07-07 00:19:05 +03:00
if v == nil {
return nil // nothing to validate
}
2024-09-29 19:23:19 +03:00
if v.Size > maxBytes {
return validation.NewError(
"validation_file_size_limit",
2024-11-25 11:28:20 +02:00
"Failed to upload {{.file}} - the maximum allowed file size is {{.maxSize}} bytes.",
2024-09-29 19:23:19 +03:00
).SetParams(map[string]any{
"file": v.OriginalName,
"maxSize": maxBytes,
})
2022-07-07 00:19:05 +03:00
}
return nil
}
}
2024-09-29 19:23:19 +03:00
// UploadedFileMimeType checks whether the validated [*filesystem.File]
2022-07-07 00:19:05 +03:00
// mimetype is within the provided allowed mime types.
//
// Example:
2023-02-23 21:51:42 +02:00
//
// validMimeTypes := []string{"test/plain","image/jpeg"}
2022-07-07 00:19:05 +03:00
// validation.Field(&form.File, validation.By(validators.UploadedFileMimeType(validMimeTypes)))
func UploadedFileMimeType(validTypes []string) validation.RuleFunc {
return func(value any) error {
2024-09-29 19:23:19 +03:00
v, ok := value.(*filesystem.File)
if !ok {
return ErrUnsupportedValueType
}
2022-07-07 00:19:05 +03:00
if v == nil {
return nil // nothing to validate
}
baseErr := validation.NewError(
"validation_invalid_mime_type",
fmt.Sprintf("Failed to upload %q due to unsupported file type.", v.OriginalName),
)
2022-07-07 00:19:05 +03:00
if len(validTypes) == 0 {
return baseErr
2022-07-07 00:19:05 +03:00
}
f, err := v.Reader.Open()
2022-10-30 10:28:14 +02:00
if err != nil {
return baseErr
2022-10-30 10:28:14 +02:00
}
defer f.Close()
filetype, err := mimetype.DetectReader(f)
if err != nil {
return baseErr
2022-10-30 10:28:14 +02:00
}
2022-07-07 00:19:05 +03:00
for _, t := range validTypes {
2022-08-26 07:00:22 +03:00
if filetype.Is(t) {
2022-07-07 00:19:05 +03:00
return nil // valid
}
}
return validation.NewError(
"validation_invalid_mime_type",
fmt.Sprintf(
"%q mime type must be one of: %s.",
v.Name,
strings.Join(validTypes, ", "),
),
)
2022-07-07 00:19:05 +03:00
}
}