This repository has been archived by the owner on Dec 13, 2017. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathuser.go
78 lines (67 loc) · 2.1 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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package shopy
import (
"crypto/rand"
"encoding/hex"
"io"
"golang.org/x/crypto/scrypt"
)
// User contains the information of an User
type User struct {
ID int `db:"id"`
FirstName string `db:"first_name"`
LastName string `db:"last_name"`
Email string `db:"email"`
Address NullString `db:"address"`
Invites int `db:"invites"`
Credit int `db:"credit"`
Confirmed bool `db:"confirmed"`
Admin bool `db:"admin"`
Referral string `db:"referral"`
Referrer NullInt64 `db:"referrer"`
PasswordSalt string `db:"password_salt" json:"-"`
PasswordHash string `db:"password_hash" json:"-"`
Deactivated bool `db:"deactivated"`
}
// CheckPassword checks if the password of the user is correct
func (u *User) CheckPassword(password string) (bool, error) {
// Decodes the hexadecimal salt into a []byte
salt, err := hex.DecodeString(u.PasswordSalt)
if err != nil {
return false, err
}
// Makes an hash from the password and salt
hash, err := scrypt.Key([]byte(password), salt, 1<<14, 8, 1, passwordHashBytes)
if err != nil {
return false, err
}
return (hex.EncodeToString(hash) == u.PasswordHash), nil
}
// SetPassword generates the salt and the hash of the user password
func (u *User) SetPassword(password string) error {
// Generates a random salt
salt := make([]byte, passwordSaltBytes)
_, err := io.ReadFull(rand.Reader, salt)
if err != nil {
return err
}
// Creates the hash from the salt and password
hash, err := scrypt.Key([]byte(password), salt, 1<<14, 8, 1, passwordHashBytes)
if err != nil {
return err
}
// Stores the hash and salt in hexadecimal form
u.PasswordSalt = hex.EncodeToString(salt)
u.PasswordHash = hex.EncodeToString(hash)
return nil
}
// UserService ...
type UserService interface {
Get(id int) (*User, error)
GetByEmail(email string) (*User, error)
GetByReferral(referral string) (*User, error)
Gets(first, limit int, order string) ([]*User, error)
Total() (int, error)
Create(u *User) error
Update(u *User, fields ...string) error
Delete(id int) error
}