From 8319afc7eae6f1accc479700c7bbed2221afcf45 Mon Sep 17 00:00:00 2001 From: Nikolai Papin Date: Sat, 5 Jul 2025 03:08:00 +0300 Subject: [PATCH] refactor/fix: now using pgx errors for postgres error checking instead of trying to look up the error code; feat: implemented working custom validation; fix: authservice begin/complete registration --- backend/cmd/main.go | 11 ++-- backend/go.mod | 6 +-- backend/go.sum | 6 +-- backend/internal/middleware/request.go | 12 +++++ backend/internal/models/auth.go | 6 +-- backend/internal/services/auth.go | 12 ++--- backend/internal/validation/custom.go | 52 +++++++++++++++++++ .../postgres.go => validation/setup.go} | 28 ++++------ backend/internal/validation/validator.go | 32 ++++++++++++ 9 files changed, 126 insertions(+), 39 deletions(-) create mode 100644 backend/internal/validation/custom.go rename backend/internal/{errors/postgres.go => validation/setup.go} (75%) create mode 100644 backend/internal/validation/validator.go diff --git a/backend/cmd/main.go b/backend/cmd/main.go index b1c1b82..8bf69dd 100644 --- a/backend/cmd/main.go +++ b/backend/cmd/main.go @@ -1,17 +1,17 @@ // Copyright (c) 2025 Nikolai Papin -// +// // This file is part of Easywish -// +// // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. -// +// // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See // the GNU General Public License for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program. If not, see . @@ -46,6 +46,7 @@ import ( "easywish/internal/logger" "easywish/internal/routes" "easywish/internal/services" + "easywish/internal/validation" swaggerfiles "github.com/swaggo/files" ginSwagger "github.com/swaggo/gin-swagger" @@ -65,6 +66,8 @@ func main() { ), database.Module, services.Module, + validation.Module, + controllers.Module, routes.Module, diff --git a/backend/go.mod b/backend/go.mod index d39f64b..101d557 100644 --- a/backend/go.mod +++ b/backend/go.mod @@ -4,10 +4,10 @@ go 1.24.3 require ( github.com/gin-gonic/gin v1.10.1 + github.com/go-playground/validator/v10 v10.27.0 github.com/golang-jwt/jwt/v5 v5.2.2 github.com/jackc/pgx/v5 v5.7.5 github.com/spf13/viper v1.20.1 - github.com/stretchr/testify v1.10.0 github.com/swaggo/files v1.0.1 github.com/swaggo/gin-swagger v1.6.0 github.com/swaggo/swag v1.16.4 @@ -20,7 +20,6 @@ require ( github.com/bytedance/sonic v1.13.3 // indirect github.com/bytedance/sonic/loader v0.2.4 // indirect github.com/cloudwego/base64x v0.1.5 // indirect - github.com/davecgh/go-spew v1.1.1 // indirect github.com/fsnotify/fsnotify v1.9.0 // indirect github.com/gabriel-vasile/mimetype v1.4.9 // indirect github.com/gin-contrib/sse v1.1.0 // indirect @@ -30,10 +29,8 @@ require ( github.com/go-openapi/swag v0.23.1 // indirect github.com/go-playground/locales v0.14.1 // indirect github.com/go-playground/universal-translator v0.18.1 // indirect - github.com/go-playground/validator/v10 v10.26.0 // indirect github.com/go-viper/mapstructure/v2 v2.2.1 // indirect github.com/goccy/go-json v0.10.5 // indirect - github.com/jackc/pgerrcode v0.0.0-20240316143900-6e2875d9b438 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect github.com/jackc/puddle/v2 v2.2.2 // indirect @@ -46,7 +43,6 @@ require ( github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect github.com/pelletier/go-toml/v2 v2.2.4 // indirect - github.com/pmezard/go-difflib v1.0.0 // indirect github.com/sagikazarmark/locafero v0.9.0 // indirect github.com/sourcegraph/conc v0.3.0 // indirect github.com/spf13/afero v1.14.0 // indirect diff --git a/backend/go.sum b/backend/go.sum index 2fc218c..abd3a18 100644 --- a/backend/go.sum +++ b/backend/go.sum @@ -37,8 +37,8 @@ github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/o github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= -github.com/go-playground/validator/v10 v10.26.0 h1:SP05Nqhjcvz81uJaRfEV0YBSSSGMc/iMaVtFbr3Sw2k= -github.com/go-playground/validator/v10 v10.26.0/go.mod h1:I5QpIEbmr8On7W0TktmJAumgzX4CA1XNl4ZmDuVHKKo= +github.com/go-playground/validator/v10 v10.27.0 h1:w8+XrWVMhGkxOaaowyKH35gFydVHOvC0/uWoy2Fzwn4= +github.com/go-playground/validator/v10 v10.27.0/go.mod h1:I5QpIEbmr8On7W0TktmJAumgzX4CA1XNl4ZmDuVHKKo= github.com/go-viper/mapstructure/v2 v2.2.1 h1:ZAaOCxANMuZx5RCeg0mBdEZk7DZasvvZIxtHqx8aGss= github.com/go-viper/mapstructure/v2 v2.2.1/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4= @@ -48,8 +48,6 @@ github.com/golang-jwt/jwt/v5 v5.2.2/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVI github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= -github.com/jackc/pgerrcode v0.0.0-20240316143900-6e2875d9b438 h1:Dj0L5fhJ9F82ZJyVOmBx6msDp/kfd1t9GRfny/mfJA0= -github.com/jackc/pgerrcode v0.0.0-20240316143900-6e2875d9b438/go.mod h1:a/s9Lp5W7n/DD0VrVoyJ00FbP2ytTPDVOivvn2bMlds= github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= diff --git a/backend/internal/middleware/request.go b/backend/internal/middleware/request.go index d7a57e4..2665b20 100644 --- a/backend/internal/middleware/request.go +++ b/backend/internal/middleware/request.go @@ -19,9 +19,12 @@ package middleware import ( "easywish/internal/utils/enums" + "easywish/internal/validation" + "fmt" "net/http" "github.com/gin-gonic/gin" + "github.com/go-playground/validator/v10" ) type UserInfo struct { @@ -87,6 +90,15 @@ func RequestMiddleware[T any](role enums.Role) gin.HandlerFunc { return } + validate := validation.NewValidator() + + if err := validate.Struct(body); err != nil { + errorList := err.(validator.ValidationErrors) + c.String(http.StatusBadRequest, fmt.Sprintf("Validation error: %s", errorList)) + + return + } + request := Request[T]{ User: *userInfo, Body: body, diff --git a/backend/internal/models/auth.go b/backend/internal/models/auth.go index 5532009..f0a7b2f 100644 --- a/backend/internal/models/auth.go +++ b/backend/internal/models/auth.go @@ -23,13 +23,13 @@ type Tokens struct { } type RegistrationBeginRequest struct { - Username string `json:"username" binding:"required,min=3,max=20"` + Username string `json:"username" binding:"required,min=3,max=20" validate:"username"` Email *string `json:"email" binding:"email"` Password string `json:"password" binding:"required"` // TODO: password checking } type RegistrationCompleteRequest struct { - Username string `json:"username" binding:"required,min=3,max=20"` + Username string `json:"username" binding:"required,min=3,max=20" validate:"username"` VerificationCode string `json:"verification_code" binding:"required"` Name string `json:"name" binding:"required,max=75"` Birthday *string `json:"birthday"` @@ -41,7 +41,7 @@ type RegistrationCompleteResponse struct { } type LoginRequest struct { - Username string `json:"username" binding:"required,min=3,max=20"` + Username string `json:"username" binding:"required,min=3,max=20" validate:"username"` Password string `json:"password" binding:"required,max=100"` TOTP *string `json:"totp"` } diff --git a/backend/internal/services/auth.go b/backend/internal/services/auth.go index 7682a93..c5ce2a6 100644 --- a/backend/internal/services/auth.go +++ b/backend/internal/services/auth.go @@ -23,8 +23,8 @@ import ( "easywish/internal/models" "easywish/internal/utils" "easywish/internal/utils/enums" + "errors" - "github.com/jackc/pgerrcode" "github.com/jackc/pgx/v5" "go.uber.org/zap" ) @@ -57,7 +57,7 @@ func (a *authServiceImpl) RegistrationBegin(request models.RegistrationBeginRequ if user, err = db.TXQueries.CreateUser(db.CTX, request.Username); err != nil { - if errs.IsPgErr(err, pgerrcode.UniqueViolation) { + if errors.Is(err, pgx.ErrNoRows) { a.log.Warn( "Attempted registration for a taken username", zap.String("username", request.Username), @@ -69,13 +69,13 @@ func (a *authServiceImpl) RegistrationBegin(request models.RegistrationBeginRequ return false, errs.ErrServerError } - if _, err := db.TXQueries.GetUserByEmail(db.CTX, *request.Email); err == nil { + if _, emailerr := db.TXQueries.GetUserByEmail(db.CTX, *request.Email); emailerr == nil { a.log.Warn( "Attempted registration for a taken email", zap.String("email", *request.Email)) return false, errs.ErrEmailTaken - } else if !errs.IsPgErr(err, pgerrcode.NoData) { + } else if !errors.Is(emailerr, pgx.ErrNoRows) { a.log.Error( "Failed to check if email is not taken", zap.String("email", *request.Email), @@ -139,7 +139,7 @@ func (a *authServiceImpl) RegistrationComplete(request models.RegistrationComple user, err = db.TXQueries.GetUserByUsername(db.CTX, request.Username) if err != nil { - if errs.IsPgErr(err, pgerrcode.NoData) { + if errors.Is(err, pgx.ErrNoRows) { a.log.Warn( "Could not find user attempting to complete registration with given username", zap.String("username", request.Username), @@ -161,7 +161,7 @@ func (a *authServiceImpl) RegistrationComplete(request models.RegistrationComple }) if err != nil { - if errs.IsPgErr(err, pgerrcode.NoData) { + if errors.Is(err, pgx.ErrNoRows) { a.log.Warn( "User supplied unexistent confirmation code for completing registration", zap.String("username", user.Username), diff --git a/backend/internal/validation/custom.go b/backend/internal/validation/custom.go new file mode 100644 index 0000000..678b1ec --- /dev/null +++ b/backend/internal/validation/custom.go @@ -0,0 +1,52 @@ +// Copyright (c) 2025 Nikolai Papin +// +// This file is part of Easywish +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See +// the GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +package validation + +import ( + "regexp" + + "github.com/go-playground/validator/v10" +) + +type CustomValidatorHandler struct { + Function func(fl validator.FieldLevel) bool + FieldName string +} + +func GetCustomHandlers() []CustomValidatorHandler { + + handlers := []CustomValidatorHandler{ + + { + FieldName: "username", + Function: func(fl validator.FieldLevel) bool { + username := fl.Field().String() + return regexp.MustCompile(`^[a-zA-Z0-9_]{3,20}$`).MatchString(username) + }}, + + { + FieldName: "name", + Function: func(fl validator.FieldLevel) bool { + username := fl.Field().String() + return regexp.MustCompile(`^[.]{1,75}$`).MatchString(username) + }}, + + } + + return handlers +} diff --git a/backend/internal/errors/postgres.go b/backend/internal/validation/setup.go similarity index 75% rename from backend/internal/errors/postgres.go rename to backend/internal/validation/setup.go index e18a39d..0cf7548 100644 --- a/backend/internal/errors/postgres.go +++ b/backend/internal/validation/setup.go @@ -1,34 +1,28 @@ // Copyright (c) 2025 Nikolai Papin -// +// // This file is part of Easywish -// +// // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. -// +// // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See // the GNU General Public License for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program. If not, see . -package errors +package validation import ( - "errors" - - "github.com/jackc/pgx/v5/pgconn" + "go.uber.org/fx" ) -func IsPgErr(err error, code string) bool { - var pgErr *pgconn.PgError - if errors.As(err, &pgErr) { - if pgErr.Code == code { - return true - } - } - return false -} +var Module = fx.Module("validation", + fx.Provide( + NewValidator, + ), +) diff --git a/backend/internal/validation/validator.go b/backend/internal/validation/validator.go new file mode 100644 index 0000000..fe10899 --- /dev/null +++ b/backend/internal/validation/validator.go @@ -0,0 +1,32 @@ +// Copyright (c) 2025 Nikolai Papin +// +// This file is part of Easywish +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See +// the GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +package validation + +import ( + "github.com/go-playground/validator/v10" +) + +func NewValidator() *validator.Validate { + v := validator.New() + + for _, handler := range GetCustomHandlers() { + v.RegisterValidation(handler.FieldName, handler.Function) + } + + return v +}