-
Notifications
You must be signed in to change notification settings - Fork 0
/
user.go
88 lines (77 loc) · 2.24 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
package main
import (
"context"
"errors"
"fmt"
"log"
"time"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"golang.org/x/crypto/bcrypt"
)
type User struct {
DisplayName string `bson:"display_name"`
UserName string `bson:"user_name"`
Email string `bson:"email"`
Password string `bson:"password"`
CreatedAt time.Time `bson:"created_at"`
UpdatedAt time.Time `bson:"updated_at"`
}
func (db *databaseConfig) createUser(userName, displayName, email, plainPassword string) (User, error) {
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(plainPassword), 10)
if err != nil {
log.Println("err in hashing password ", err)
}
user := User{
UserName: userName,
DisplayName: displayName,
Email: email,
Password: string(hashedPassword),
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
_, err = db.userColl.InsertOne(context.TODO(), user)
if err != nil {
log.Println("error while creating user: ", err)
return User{}, err
}
return user, nil
}
func (db *databaseConfig) getUserByUserName(username string) (User, error) {
filter := bson.D{{Key: "user_name", Value: username}}
var user User
result := db.userColl.FindOne(context.TODO(), filter).Decode(&user)
if result == mongo.ErrNoDocuments {
return User{}, errors.New("username does not exists")
}
return user, nil
}
func (db *databaseConfig) getUserByEmail(email string) (User, error) {
filter := bson.D{{Key: "email", Value: email}}
var user User
result := db.userColl.FindOne(context.TODO(), filter).Decode(&user)
if result == mongo.ErrNoDocuments {
return User{}, errors.New("email does not exists")
}
return user, nil
}
func (db *databaseConfig) getAllUsers() {
cursor, err := db.userColl.Find(context.TODO(), bson.M{})
if err != nil {
log.Println("error in finding users", err)
}
var users []bson.M
if err := cursor.All(context.TODO(), &users); err != nil {
log.Println("error quering users : ", err)
}
for _, user := range users {
fmt.Println(user)
}
}
func (db *databaseConfig) deleteAllUsers() {
result, err := db.userColl.DeleteMany(context.TODO(), bson.M{})
if err != nil {
log.Println("error in deleting users : ", err)
}
log.Println("Documents delete : ", result.DeletedCount)
}