forked from brianstarke/dogfort
-
Notifications
You must be signed in to change notification settings - Fork 0
/
user.go
162 lines (127 loc) · 3.49 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
package domain
import (
"encoding/hex"
"fmt"
"strings"
"time"
"crypto/md5"
"code.google.com/p/go.crypto/bcrypt"
"github.com/dgrijalva/jwt-go"
"github.com/nu7hatch/gouuid"
"labix.org/v2/mgo"
"labix.org/v2/mgo/bson"
)
type UserUid string
type User struct {
Uid UserUid `json:"uid"`
Email string `json:"email"`
Username string `json:"username"`
PasswordHash string `json:"passwordHash,omitempty"`
GravatarHash string `json:"gravatarHash"`
}
type NewUser struct {
Email string `binding:"required"`
Username string `binding:"required"`
Password string `binding:"required"`
}
type AuthenticationRequest struct {
Username string `binding:"required"`
Password string `binding:"required"`
}
type UserDomain struct {
Collection *mgo.Collection
}
/*
Creates a User from a NewUser struct. Returns the new user's UID
*/
func (ud UserDomain) CreateUser(newUser *NewUser) (*UserUid, error) {
// check to see if this user already exists
n, err := ud.Collection.Find(bson.M{"$or": []bson.M{bson.M{"email": newUser.Email}, bson.M{"username": newUser.Username}}}).Count()
if err != nil {
return nil, err
}
if n > 0 {
return nil, fmt.Errorf("A user already exists with that username or email")
}
// create our own UID (ignore Mongo ObjectId)
uid, err := uuid.NewV4()
if err != nil {
return nil, err
}
// generate password hash
b, err := bcrypt.GenerateFromPassword([]byte(newUser.Password), 10)
if err != nil {
return nil, err
}
user := User{}
user.Uid = UserUid(uid.String())
user.Email = newUser.Email
user.Username = newUser.Username
user.PasswordHash = string(b)
user.GravatarHash = getGravatarHash(&newUser.Email)
err = ud.Collection.Insert(&user)
if err != nil {
return nil, err
} else {
return &user.Uid, nil
}
}
/*
Attempts to authenticate a user and returns a JWT if successful
*/
func (ud UserDomain) Authenticate(ar *AuthenticationRequest) (*string, error) {
u := User{}
err := ud.Collection.Find(bson.M{"username": ar.Username}).One(&u)
if err != nil {
return nil, err
}
// check password against hash
err = bcrypt.CompareHashAndPassword([]byte(u.PasswordHash), []byte(ar.Password))
if err != nil {
return nil, fmt.Errorf("Invalid password for %s", ar.Username)
}
token := jwt.New(jwt.GetSigningMethod("HS256"))
token.Header["user_id"] = u.Uid
token.Claims["iat"] = time.Now().Unix()
token.Claims["exp"] = time.Now().Add(time.Hour * 24).Unix()
// TODO! move this signing key to .env (and maybe use rsa key)
tokenString, err := token.SignedString([]byte("dogfort"))
if err != nil {
return nil, err
} else {
return &tokenString, nil
}
}
func (ud UserDomain) UserByUid(uid UserUid) (*User, error) {
u := User{}
err := ud.Collection.Find(bson.M{"uid": uid}).One(&u)
if err != nil {
return nil, err
} else {
u.PasswordHash = "" // wipe this before sending it anywhere front end
return &u, nil
}
}
func getGravatarHash(email *string) string {
hasher := md5.New()
hasher.Write([]byte(strings.ToLower(*email)))
return hex.EncodeToString(hasher.Sum(nil))
}
/*
Parses a token, returns user id if valid
*/
func getUserUidFromToken(token string) (*UserUid, error) {
t, err := jwt.Parse(token, func(token *jwt.Token) ([]byte, error) {
return []byte("dogfort"), nil
})
if err != nil {
return nil, fmt.Errorf("error parsing token: %s", err.Error())
} else {
if t.Valid {
uid := UserUid(t.Header["user_id"].(string))
return &uid, nil
} else {
return nil, fmt.Errorf("token is not valid: %s", err.Error())
}
}
}