71 lines
1.4 KiB
Go
71 lines
1.4 KiB
Go
package user
|
|||
|
|
|
||
|
|
import (
|
||
|
|
"bytes"
|
||
|
|
"image"
|
||
|
|
_ "image/jpeg"
|
||
|
|
_ "image/png"
|
||
|
|
"log/slog"
|
||
|
|
"regexp"
|
||
|
|
"strings"
|
||
|
|
)
|
||
|
|
|
||
|
|
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 {
|
||
|
|
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
|
||
|
|
}
|
||
|
|
|
||
|
|
switch format {
|
||
|
|
case "jpeg", "png":
|
||
|
|
default:
|
||
|
|
return ErrUnsupportedFormat
|
||
|
|
}
|
||
|
|
|
||
|
|
if cfg.Width > MaxImageWidth || cfg.Height > MaxImageHeight {
|
||
|
|
return ErrExceedDimensions
|
||
|
|
}
|
||
|
|
|
||
|
|
return nil
|
||
|
|
}
|