Fix image formats and size, add feedback
This commit is contained in:
1 parent
feaab7e4e2
commit
fef1abade8
11 files changed
+192
-12
No files matched your search
@@ -7,5 +7,6 @@ var (
|
||||
ErrNotFound = errors.New("user not found")
|
||||
ErrUnsupportedFormat = errors.New("not supported format")
|
||||
ErrExceedDimensions = errors.New("image exceeds max dimenstions")
|
||||
ErrImageTooLarge = errors.New("image exceeds max size")
|
||||
ErrInvalidPassword = errors.New("invalid password")
|
||||
)
|
||||
@@ -9,9 +9,14 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
MaxImageWidth = 1024
|
||||
MaxImageHeight = 1024
|
||||
PasswordCost = 14
|
||||
// MaxImageWidth and MaxImageHeight cap the dimensions of an uploaded
|
||||
// avatar.
|
||||
MaxImageWidth = 2048
|
||||
MaxImageHeight = 2048
|
||||
// MaxImageSize is the maximum accepted avatar upload size in bytes
|
||||
// (4 MiB).
|
||||
MaxImageSize = 4 << 20
|
||||
PasswordCost = 14
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
|
||||
@@ -10,6 +10,22 @@ import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
// allowedImageFormats maps the image formats returned by image.DecodeConfig
|
||||
// (derived from the file content, not the extension) to the MIME types the
|
||||
// frontend advertises in the file picker. JPEG files may carry either a .jpg
|
||||
// or a .jpeg extension; both decode to the "jpeg" format and are accepted.
|
||||
var allowedImageFormats = map[string]string{
|
||||
"jpeg": "image/jpeg",
|
||||
"png": "image/png",
|
||||
}
|
||||
|
||||
// AllowedAvatarMIMETypes returns the MIME types accepted for avatars. The
|
||||
// "image/jpg" alias is included so file pickers that treat ".jpg" as a
|
||||
// distinct type still allow the upload.
|
||||
func AllowedAvatarMIMETypes() []string {
|
||||
return []string{"image/jpeg", "image/jpg", "image/png"}
|
||||
}
|
||||
|
||||
type Validator struct {
|
||||
emailRegex *regexp.Regexp
|
||||
loginRegex *regexp.Regexp
|
||||
@@ -50,6 +66,10 @@ func (v *Validator) VerifyPassword(password string) bool {
|
||||
}
|
||||
|
||||
func (v *Validator) VerifyImage(data []byte) error {
|
||||
if len(data) > MaxImageSize {
|
||||
return ErrImageTooLarge
|
||||
}
|
||||
|
||||
r := bytes.NewReader(data)
|
||||
cfg, format, err := image.DecodeConfig(r)
|
||||
if err != nil {
|
||||
@@ -57,9 +77,7 @@ func (v *Validator) VerifyImage(data []byte) error {
|
||||
return err
|
||||
}
|
||||
|
||||
switch format {
|
||||
case "jpeg", "png":
|
||||
default:
|
||||
if _, ok := allowedImageFormats[format]; !ok {
|
||||
return ErrUnsupportedFormat
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user