forked from andyhaskell/Slothful-Soda
/
User.go
70 lines (56 loc) · 1.19 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
package main
import (
"encoding/json"
"log"
"golang.org/x/crypto/pbkdf2"
"crypto/sha1"
"encoding/base64"
"crypto/rand"
"io"
)
type User struct {
Id int
Email string `json:"email"`
Username string `json:"username"`
Password string `json:"password"`
Salt []byte `json:"-"`
}
func initUser() *User {
return &User{}
}
// interface used for testing
type iDbMap interface {
Insert(list ...interface{}) error
}
func (user *User) save(DbMap iDbMap) error {
// Generate random salt
salt := make([]byte, 10)
_, err := io.ReadFull(rand.Reader, salt)
if err != nil {
return err
}
user.Salt = salt
hash := pbkdf2.Key([]byte(user.Password), user.Salt, 4096, 32, sha1.New)
user.Password = base64.StdEncoding.EncodeToString(hash)
err = DbMap.Insert(user)
if err != nil {
return err
}
return nil
}
func (user *User) checkPassword(password string) bool {
hash := pbkdf2.Key([]byte(password), user.Salt, 4096, 32, sha1.New)
base64 := base64.StdEncoding.EncodeToString(hash)
if (base64 == user.Password) {
return true
} else {
return false
}
}
func (user *User) JSON() (string) {
json, err := json.Marshal(user)
if (err != nil) {
log.Println(err)
}
return string(json)
}