refactored validation

This commit is contained in:
Alex
2025-03-11 20:46:45 +01:00
parent c8d0904fd7
commit feb8abcc42
3 changed files with 25 additions and 22 deletions

View File

@@ -1,7 +1,6 @@
package validation
import (
"GoMembership/internal/constants"
"GoMembership/internal/models"
"GoMembership/internal/repositories"
"GoMembership/pkg/logger"
@@ -10,6 +9,7 @@ import (
"github.com/go-playground/validator/v10"
passwordvalidator "github.com/wagslane/go-password-validator"
"gorm.io/gorm"
)
var passwordErrorTranslations = map[string]string{
@@ -21,11 +21,15 @@ var passwordErrorTranslations = map[string]string{
"using numbers": "server.validation.numbers",
}
func ValidateUser(sl validator.StructLevel) {
func ValidateUserFactory(db *gorm.DB) validator.StructLevelFunc {
return func(sl validator.StructLevel) {
validateUser(db, sl)
}
}
func validateUser(db *gorm.DB, sl validator.StructLevel) {
user := sl.Current().Interface().(models.User)
isSuper := user.RoleID >= constants.Roles.Admin
isSupporter := user.RoleID == constants.Roles.Supporter
// validate subscriptionModel
if user.Membership.SubscriptionModel.Name == "" {
sl.ReportError(user.Membership.SubscriptionModel.Name, "subscription.name", "name", "required", "")
@@ -38,7 +42,7 @@ func ValidateUser(sl validator.StructLevel) {
user.Membership.SubscriptionModel = *selectedModel
}
}
if isSupporter {
if user.IsSupporter() {
if user.BankAccount.IBAN != "" {
validateBankAccount(sl)
}
@@ -54,9 +58,9 @@ func ValidateUser(sl validator.StructLevel) {
if user.DateOfBirth.After(time.Now().AddDate(-18, 0, 0)) {
sl.ReportError(user.DateOfBirth, "user.user", "user.dateofbirth", "age", "")
}
validateMembership(sl)
validateMembership(db, &user, sl)
if isSuper {
if user.IsAdmin() {
return
}