-
Notifications
You must be signed in to change notification settings - Fork 1
/
helpers.go
125 lines (97 loc) · 2.55 KB
/
helpers.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
package gah
import (
"context"
"crypto/rand"
"fmt"
"time"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"golang.org/x/crypto/bcrypt"
)
// TokenGenerator new token generator
func TokenGenerator() string {
b := make([]byte, 32)
rand.Read(b)
return fmt.Sprintf("%x", b)
}
// ComparePasswords check password
func ComparePasswords(hashedPwd string, plainPwd []byte) bool {
// Since we'll be getting the hashed password from the DB it
// will be a string so we'll need to convert it to a byte slice
byteHash := []byte(hashedPwd)
err := bcrypt.CompareHashAndPassword(byteHash, plainPwd)
if err != nil {
return false
}
return true
}
// GetUserByEmail the user receives the e-mail and returns the user.
func GetUserByEmail(email string) (UserStruct, error) {
var user UserStruct
collection := GetCollection()
doc := collection.FindOne(context.TODO(), bson.M{"email": email})
err := doc.Decode(&user)
if err != nil {
return user, err
}
return user, nil
}
// GetUserByID The user receives _id and returns the user.
func GetUserByID(_id interface{}) (UserStruct, error) {
var user UserStruct
collection := GetCollection()
doc := collection.FindOne(context.TODO(), bson.M{"_id": _id})
err := doc.Decode(&user)
if err != nil {
return user, err
}
return user, nil
}
// CreateUser You can insert a new user.
func CreateUser(email string, password string) UserStruct {
pass, _ := bcrypt.GenerateFromPassword([]byte(password), bcrypt.MinCost)
collection := GetCollection()
newUser := &UserRegisterStruct{
Email: email,
Password: string(pass),
CreatedAt: time.Now(),
Tokens: []TokenStruct{},
}
insertResult, _ := collection.InsertOne(context.TODO(), newUser)
user, _ := GetUserByID(insertResult.InsertedID)
return user
}
// InsertHashedLoginToken Add a new auth token to the user's account
func InsertHashedLoginToken(id primitive.ObjectID) string {
collection := GetCollection()
token := TokenGenerator()
newToken := &TokenStruct{
Token: token,
CreatedAt: time.Now(),
}
collection.UpdateOne(context.TODO(),
bson.M{"_id": id},
bson.M{
"$addToSet": bson.M{
"tokens": newToken,
},
},
)
return token
}
// GetUserByToken token and _id returned user struct
func GetUserByToken(id primitive.ObjectID, token string) (UserStruct, error) {
var user UserStruct
collection := GetCollection()
doc := collection.FindOne(context.TODO(),
bson.M{
"_id": id,
"tokens.token": token,
},
)
err := doc.Decode(&user)
if err != nil {
return user, err
}
return user, nil
}