Add utility functions for password hashing and data validation

This commit is contained in:
Habib Fatkhul Rohman 2025-10-15 21:14:40 +07:00
parent 1b490d8770
commit 816ea1610e
2 changed files with 74 additions and 0 deletions

25
pkg/utils/conv.go Normal file
View File

@ -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)
}

49
pkg/utils/validator.go Normal file
View File

@ -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
}