-
Notifications
You must be signed in to change notification settings - Fork 0
/
crud.go
105 lines (81 loc) · 2.27 KB
/
crud.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
package adminmodel
import (
"context"
"errors"
"fmt"
"github.com/google/uuid"
"github.com/khofesh/simple-go-api/common"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"golang.org/x/crypto/bcrypt"
)
// HashPassword ...
func (u *Model) HashPassword(password string) error {
if len(password) == 0 {
return errors.New("Password cannot be empty")
}
bytePassword := []byte(password)
passwordHash, _ := bcrypt.GenerateFromPassword(bytePassword, bcrypt.DefaultCost)
u.Password = string(passwordHash)
return nil
}
// CheckPassword ...
func (u *Model) CheckPassword(password string) error {
bytePassword := []byte(password)
byteHashedPassword := []byte(u.Password)
return bcrypt.CompareHashAndPassword(byteHashedPassword, bytePassword)
}
// GenerateEmployeeID ...
func (u *Model) GenerateEmployeeID() {
u.EmployeeID = uuid.Must(uuid.NewRandom()).String()
}
// CreateAdmin ...
func (u *Model) CreateAdmin() error {
coll := common.GetCollection("simple", "admins")
if val, _ := coll.CountDocuments(context.TODO(), bson.M{"email": u.Email}); val != 0 {
return errors.New("Email already exists")
}
// set PasswordConfirmation to empty string
u.PasswordConfirmation = ""
idxMod := mongo.IndexModel{
Keys: bson.M{"email": 1}, Options: options.Index().SetUnique(true),
}
names, err := coll.Indexes().CreateOne(context.TODO(), idxMod)
if err != nil {
return err
}
fmt.Printf("created indexes %v\n", names)
_, err = coll.InsertOne(context.TODO(), u)
if err != nil {
return err
}
return nil
}
// UpdateAdmin ...
func (u *Model) UpdateAdmin(update bson.M) error {
coll := common.GetCollection("simple", "admins")
_, err := coll.UpdateOne(context.TODO(), bson.M{"email": u.Email}, update)
if err != nil {
return err
}
return nil
}
// DeleteAdmin ...
func DeleteAdmin(filter bson.M) error {
coll := common.GetCollection("simple", "admins")
_, err := coll.DeleteOne(context.TODO(), filter)
if err != nil {
return err
}
return nil
}
// FindOneAdmin ...
func FindOneAdmin(filter bson.M) (Model, error) {
var result Model
coll := common.GetCollection("simple", "admins")
if err := coll.FindOne(context.TODO(), filter).Decode(&result); err != nil {
return result, err
}
return result, nil
}