90 lines
2.1 KiB
Go
90 lines
2.1 KiB
Go
package user
|
|
|
|
import (
|
|
"bytes"
|
|
"image"
|
|
_ "image/jpeg"
|
|
_ "image/png"
|
|
"log/slog"
|
|
"regexp"
|
|
"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
|
|
}
|
|
|
|
func NewValidator() (*Validator, error) {
|
|
emailRegexp := regexp.MustCompile(`^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`)
|
|
loginRegex := regexp.MustCompile(`^[a-zA-Z0-9_-]+$`)
|
|
|
|
return &Validator{emailRegex: emailRegexp, loginRegex: loginRegex}, nil
|
|
}
|
|
|
|
func (v *Validator) VerifyEmail(email string) bool {
|
|
if len(email) < 3 || len(email) > 254 {
|
|
return false
|
|
}
|
|
|
|
return v.emailRegex.MatchString(email)
|
|
}
|
|
|
|
func (v *Validator) VerifyLogin(login string) bool {
|
|
username := strings.TrimSpace(login)
|
|
if len(username) < 3 || len(username) > 30 {
|
|
return false
|
|
}
|
|
if !v.loginRegex.MatchString(username) {
|
|
return false
|
|
}
|
|
|
|
return true
|
|
}
|
|
|
|
func (v *Validator) VerifyPassword(password string) bool {
|
|
if len(password) < 8 || len(password) > 72 {
|
|
return false
|
|
}
|
|
return true
|
|
}
|
|
|
|
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 {
|
|
slog.Error("decode image config", slog.String("op", "validator.VerifyImage"), slog.Any("error", err))
|
|
return err
|
|
}
|
|
|
|
if _, ok := allowedImageFormats[format]; !ok {
|
|
return ErrUnsupportedFormat
|
|
}
|
|
|
|
if cfg.Width > MaxImageWidth || cfg.Height > MaxImageHeight {
|
|
return ErrExceedDimensions
|
|
}
|
|
|
|
return nil
|
|
}
|