From 56ef5276cee0ad9ddcfff2647d489313c38a1254 Mon Sep 17 00:00:00 2001 From: Geno Date: Tue, 22 Jun 2021 18:17:52 +0200 Subject: [PATCH] web/auth: split password function --- web/auth/lib_password.go | 20 ++++++++++++++++++++ web/auth/models.go | 8 +++----- 2 files changed, 23 insertions(+), 5 deletions(-) create mode 100644 web/auth/lib_password.go diff --git a/web/auth/lib_password.go b/web/auth/lib_password.go new file mode 100644 index 0000000..74a8af2 --- /dev/null +++ b/web/auth/lib_password.go @@ -0,0 +1,20 @@ +package auth + +import ( + "golang.org/x/crypto/bcrypt" +) + +// HashPassword - create new hash of password +func HashPassword(password string) (string, error) { + p, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) + if err != nil { + return "", err + } + return string(p), nil +} + +// ValidatePassword - check if given password is equal to saved hash +func ValidatePassword(hash, password string) bool { + err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)) + return err == nil +} diff --git a/web/auth/models.go b/web/auth/models.go index c1fae55..827a731 100644 --- a/web/auth/models.go +++ b/web/auth/models.go @@ -2,7 +2,6 @@ package auth import ( "github.com/google/uuid" - "golang.org/x/crypto/bcrypt" "gorm.io/gorm" ) @@ -26,18 +25,17 @@ func NewUser(username, password string) (*User, error) { // SetPassword - create new hash of password func (u *User) SetPassword(password string) error { - p, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) + p, err := HashPassword(password) if err != nil { return err } - u.Password = string(p) + u.Password = p return nil } // ValidatePassword - check if given password is equal to saved hash func (u *User) ValidatePassword(password string) bool { - err := bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(password)) - return err == nil + return ValidatePassword(u.Password, password) } // HasPermission interface for middleware check in other models