diff --git a/app/lib/auth/auth.go b/app/lib/auth/auth.go new file mode 100644 index 0000000..8832b06 --- /dev/null +++ b/app/lib/auth/auth.go @@ -0,0 +1 @@ +package auth diff --git a/app/lib/auth/passwords.go b/app/lib/auth/passwords.go new file mode 100644 index 0000000..142766c --- /dev/null +++ b/app/lib/auth/passwords.go @@ -0,0 +1,41 @@ +package auth + +import ( + "regexp" + + "golang.org/x/crypto/bcrypt" +) + +// about bcrypt cost: https://docs.laminas.dev/laminas-crypt/password/#bcrypt +// bcrypt cost benchmarks: https://github.com/nsmithuk/bcrypt-cost-go +const BCRYPT_COST = 10 +const MIN_PASSWORD_LENGTH = 10 + +func IsPasswordGoodEnough(password string) bool { + var re *regexp.Regexp + passwordBytes := []byte(password) + + if len(password) < MIN_PASSWORD_LENGTH { + return false + } + re, _ = regexp.Compile("[a-z]") + if re.Find(passwordBytes) == nil { + return false + } + re, _ = regexp.Compile("[A-Z]") + if re.Find(passwordBytes) == nil { + return false + } + re, _ = regexp.Compile("[0-9]") + //lint:ignore S1008 allow early exit instead optimization + if re.Find(passwordBytes) == nil { + return false + } + + return true +} + +func HashPassword(password string, secretKey string) (string, error) { + bytes, err := bcrypt.GenerateFromPassword([]byte(password+secretKey), BCRYPT_COST) + return string(bytes), err +} diff --git a/app/models/user.go b/app/models/user.go index 37d8c11..f232c2e 100644 --- a/app/models/user.go +++ b/app/models/user.go @@ -1,6 +1,8 @@ package models import ( + "iris-test/app/lib/auth" + "iris-test/app/lib/cfg" "time" ) @@ -19,8 +21,12 @@ func (u *User) TableName() string { return "users" } -// func (u *User) SetPassword(password string) (string, error) { -// secretKey := common.Config.Application.SecretKey -// bytes, err := bcrypt.GenerateFromPassword([]byte(password+secretKey), 14) -// return string(bytes), err -// } +func (u *User) SetPassword(password string) error { + secretKey := cfg.Config.Application.SecretKey + hashedPassword, err := auth.HashPassword(password, secretKey) + if err != nil { + return err + } + u.Password = hashedPassword + return nil +} diff --git a/app/templates/pages/user-edit.jet b/app/templates/pages/user-edit.jet index 6ec6931..93a36cc 100644 --- a/app/templates/pages/user-edit.jet +++ b/app/templates/pages/user-edit.jet @@ -20,6 +20,10 @@ +