web/auth: split password function

This commit is contained in:
Geno 2021-06-22 18:17:52 +02:00
parent ea83f78593
commit 56ef5276ce
2 changed files with 23 additions and 5 deletions

20
web/auth/lib_password.go Normal file
View File

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

View File

@ -2,7 +2,6 @@ package auth
import ( import (
"github.com/google/uuid" "github.com/google/uuid"
"golang.org/x/crypto/bcrypt"
"gorm.io/gorm" "gorm.io/gorm"
) )
@ -26,18 +25,17 @@ func NewUser(username, password string) (*User, error) {
// SetPassword - create new hash of password // SetPassword - create new hash of password
func (u *User) SetPassword(password string) error { func (u *User) SetPassword(password string) error {
p, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) p, err := HashPassword(password)
if err != nil { if err != nil {
return err return err
} }
u.Password = string(p) u.Password = p
return nil return nil
} }
// ValidatePassword - check if given password is equal to saved hash // ValidatePassword - check if given password is equal to saved hash
func (u *User) ValidatePassword(password string) bool { func (u *User) ValidatePassword(password string) bool {
err := bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(password)) return ValidatePassword(u.Password, password)
return err == nil
} }
// HasPermission interface for middleware check in other models // HasPermission interface for middleware check in other models