apiary/models/user.go
2021-04-10 07:58:01 +02:00

33 lines
680 B
Go

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
}