2016-12-08 18:44:49 +01:00
|
|
|
package models
|
|
|
|
|
2018-08-01 13:13:42 +02:00
|
|
|
import (
|
2018-09-10 09:26:15 +02:00
|
|
|
"strings"
|
|
|
|
|
2018-08-01 13:13:42 +02:00
|
|
|
"golang.org/x/crypto/bcrypt"
|
|
|
|
)
|
|
|
|
|
2016-12-08 18:44:49 +01:00
|
|
|
type User struct {
|
2018-04-25 13:25:34 +02:00
|
|
|
ID int64
|
|
|
|
Email string
|
|
|
|
Password string `json:"-"`
|
2016-12-08 18:44:49 +01:00
|
|
|
}
|
2018-08-01 13:13:42 +02:00
|
|
|
|
2018-09-10 09:26:15 +02:00
|
|
|
// NewUser creates a new User with the given email and password
|
2018-08-01 13:13:42 +02:00
|
|
|
func NewUser(e string, pwd string) User {
|
|
|
|
u := User{
|
2018-09-10 09:26:15 +02:00
|
|
|
Email: strings.ToLower(strings.TrimSpace(e)),
|
2018-08-01 13:13:42 +02:00
|
|
|
}
|
|
|
|
u.SetPassword(pwd)
|
|
|
|
return u
|
|
|
|
}
|
|
|
|
|
2018-09-10 09:26:15 +02:00
|
|
|
// SetPassword sets a brcrypt encrypted password from the given plaintext pwd
|
2018-08-01 13:13:42 +02:00
|
|
|
func (u *User) SetPassword(pwd string) {
|
|
|
|
hash, _ := bcrypt.GenerateFromPassword([]byte(pwd), bcrypt.DefaultCost)
|
|
|
|
u.Password = string(hash)
|
|
|
|
}
|
|
|
|
|
2018-09-10 09:26:15 +02:00
|
|
|
// ComparePassword returns true when the given plaintext password matches the encrypted pwd
|
2018-08-01 13:13:42 +02:00
|
|
|
func (u *User) ComparePassword(pwd string) error {
|
|
|
|
return bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(pwd))
|
|
|
|
}
|