From 816ea1610ecbb0a94b08285e3eeafcfc79264e08 Mon Sep 17 00:00:00 2001 From: Habib Fatkhul Rohman Date: Wed, 15 Oct 2025 21:14:40 +0700 Subject: [PATCH] Add utility functions for password hashing and data validation --- pkg/utils/conv.go | 25 +++++++++++++++++++++ pkg/utils/validator.go | 49 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 74 insertions(+) create mode 100644 pkg/utils/conv.go create mode 100644 pkg/utils/validator.go diff --git a/pkg/utils/conv.go b/pkg/utils/conv.go new file mode 100644 index 0000000..7b507ad --- /dev/null +++ b/pkg/utils/conv.go @@ -0,0 +1,25 @@ +package utils + +import ( + "strconv" + + "golang.org/x/crypto/bcrypt" +) + +func HashPassword(password string) (string, error) { + bytes, err := bcrypt.GenerateFromPassword([]byte(password), 14) + return string(bytes), err +} + +func CheckPasswordHash(password, hash string) bool { + err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)) + return err == nil +} + +func StringToUint(s string) uint { + id, err := strconv.ParseUint(s, 10, 64) + if err != nil { + return 0 + } + return uint(id) +} diff --git a/pkg/utils/validator.go b/pkg/utils/validator.go new file mode 100644 index 0000000..b852bd1 --- /dev/null +++ b/pkg/utils/validator.go @@ -0,0 +1,49 @@ +package utils + +import ( + "errors" + + "github.com/go-playground/validator/v10" +) + +var validate *validator.Validate + +func init() { + validate = validator.New() +} + +func Validate(data interface{}) error { + var errorMessages []string + + err := validate.Struct(data) + if err != nil { + for _, err := range err.(validator.ValidationErrors) { + switch err.Tag() { + case "required": + errorMessages = append(errorMessages, err.Field()+" is required") + case "email": + errorMessages = append(errorMessages, err.Field()+" must be a valid email") + case "min": + errorMessages = append(errorMessages, err.Field()+" must be at least "+err.Param()+" characters long") + case "max": + errorMessages = append(errorMessages, err.Field()+" must be at most "+err.Param()+" characters long") + default: + errorMessages = append(errorMessages, err.Field()+" is not valid") + } + } + return errors.New("validation failed: " + joinMessages(errorMessages)) + } + + return nil +} + +func joinMessages(messages []string) string { + result := "" + for i, msg := range messages { + if i > 0 { + result += ", " + } + result += msg + } + return result +}