-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathuser.go
40 lines (35 loc) · 1.16 KB
/
user.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package model
import (
"errors"
"github.com/jinzhu/gorm"
"golang.org/x/crypto/bcrypt"
)
type User struct {
gorm.Model
Username string `gorm:"unique_index;not null"`
Password string `gorm:"not null"`
Urls []URL `gorm:"foreignkey:user_id"`
}
// NewUser creates a user with username and Hashed password
// returns error if username or password is empty
func NewUser(username, password string) (*User, error) {
if len(password) == 0 || len(username) == 0 {
return nil, errors.New("username of password cannot be empty")
}
pass, _ := HashPassword(password)
return &User{Username: username, Password: pass}, nil
}
// HashPassword generates a hashed string from 'pass'
// returns error if 'pass' is empty
func HashPassword(pass string) (string, error) {
if len(pass) == 0 {
return "", errors.New("password cannot be empty")
}
hash, err := bcrypt.GenerateFromPassword([]byte(pass), bcrypt.DefaultCost)
return string(hash), err
}
// ValidatePassword compares 'pass' with 'users' password
// returns true if their equivalent
func (user *User) ValidatePassword(pass string) bool {
return bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(pass)) == nil
}