/
user.go
71 lines (61 loc) · 1.8 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
package main
import (
"crypto/hmac"
"crypto/md5"
"encoding/hex"
"io"
"code.google.com/p/go.crypto/bcrypt"
"labix.org/v2/mgo"
"labix.org/v2/mgo/bson"
)
type SessionId struct {
Id bson.ObjectId "_id,omitempty"
Username string
}
// startSession will create a new document in the sessions collection and return the _id
func startSession(session *mgo.Session, username string) (*SessionId, error) {
c := session.DB(database).C(sessions)
sessionId := &SessionId{Id: bson.NewObjectId(), Username: username}
if err := c.Insert(sessionId); err != nil {
return nil, err
}
return sessionId, nil
}
// getSession returns the requested SessionId if it exists
// err == mgo.ErrNotFound if the SessionId does not exist
func getSession(session *mgo.Session, sessionId *SessionId) (result bson.M, err error) {
c := session.DB(database).C(sessions)
err = c.Find(sessionId).One(&result)
return
}
// endSession will end a new user session by deleting it from the sessions table
func endSession(session *mgo.Session, sessionId *SessionId) error {
c := session.DB(database).C(sessions)
err := c.Remove(sessionId)
return err
}
type User struct {
Id string `bson:"_id"`
Password []byte
Email string `bson:",omitempty"`
}
// newUser creates a new user in the database
func newUser(session *mgo.Session, username, password, email string) (*User, error) {
pHash, err := bcrypt.GenerateFromPassword([]byte(password), 10)
if err != nil {
return nil, err
}
user := &User{Id: username, Password: pHash, Email: email}
c := session.DB(database).C(users)
err = c.Insert(user)
return user, err
}
const key = "thisisnotsecret"
func hashStr(s string) (string, error) {
h := hmac.New(md5.New, []byte(key))
_, err := io.WriteString(h, s)
if err != nil {
return "", err
}
return hex.EncodeToString(h.Sum(nil)), nil
}