s1llyw0rdz/model/user.go

38 lines
754 B
Go
Raw Normal View History

2021-11-22 08:05:57 +00:00
package model
import (
"errors"
"golang.org/x/crypto/bcrypt"
"regexp"
"time"
)
type User struct {
Name string
Password string
Hash []byte
CreatedAt time.Time
}
func (u User) Validate() error {
if u.Name == "" {
return errors.New("username is mandatory")
}
if u.Password == "" {
return errors.New("password is mandatory")
}
match, _ := regexp.MatchString("^[a-z0-9-_]+$", u.Name)
if !match {
return errors.New("username should match [a-z0-9-_]")
}
return nil
}
func (u User) HashPassword() ([]byte, error) {
return bcrypt.GenerateFromPassword([]byte(u.Password), bcrypt.MinCost)
}
func (u User) CompareHashToPassword(hash []byte) error {
return bcrypt.CompareHashAndPassword(hash, []byte(u.Password))
}