apiary/models/user.go

33 lines
680 B
Go
Raw Normal View History

2021-04-10 05:58:01 +00:00
package models
import (
"fmt"
"golang.org/x/crypto/bcrypt"
)
var ErrInvalidPassword = fmt.Errorf("invalid password")
type User struct {
Username string `json:"username"`
PasswordHash []byte `json:"passwordHash"`
}
func (u *User) SetPassword(password string) error {
newHash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
return fmt.Errorf("error hashing new password: %w", err)
}
u.PasswordHash = newHash
return nil
}
func (u *User) VerifyPassword(password string) error {
err := bcrypt.CompareHashAndPassword([]byte(u.PasswordHash), []byte(password))
if err != nil {
return ErrInvalidPassword
}
return nil
}