/
repository_passwordgen.go
117 lines (88 loc) · 2.24 KB
/
repository_passwordgen.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
package persistence
import (
"context"
"encoding/json"
"log"
"github.com/marcos-dev88/go-password-generator/domain/entity"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
)
type repository struct {
mongodb MongoDB
}
func NewRepository(mongodb MongoDB) *repository {
return &repository{mongodb: mongodb}
}
func (r *repository) GetLastTenPasswords() ([]*entity.PasswordGen, error) {
_, table, cntx, err := r.mongodb.GetConn()
if err != nil {
return nil, err
}
pipe := []bson.M{
{
"$limit": 10,
},
}
cursor, err := table.Aggregate(cntx, pipe)
if err != nil {
return nil, err
}
defer func(cursor *mongo.Cursor, ctx context.Context) {
err := cursor.Close(ctx)
if err != nil {
panic(err)
}
}(cursor, cntx)
var passwords []*entity.PasswordGen
for cursor.Next(cntx) {
passEntity := entity.NewPasswordGen("", "", 0, false, false, false)
passBson := bson.M{}
if err = cursor.Decode(&passBson); err != nil {
return nil, err
}
passJson, _ := json.Marshal(passBson)
if err := json.Unmarshal(passJson, &passEntity); err != nil {
return nil, err
}
passwords = append(passwords, passEntity)
}
return passwords, nil
}
func (r *repository) SavePasswordGen(password *entity.PasswordGen) (*entity.PasswordGen, error) {
_, table, cntx, err := r.mongodb.GetConn()
if err != nil {
return nil, err
}
_, err = table.InsertOne(cntx, bson.D{
{Key: "uuid", Value: password.Uuid},
{Key: "length", Value: password.Length},
{Key: "password", Value: password.Password},
{Key: "has_letter", Value: password.HasLetter},
{Key: "has_number", Value: password.HasNumber},
{Key: "has_special_char", Value: password.HasSpecialChar},
})
if err != nil {
return nil, err
}
return password, nil
}
func (r *repository) PasswordExists(password string) (bool, error) {
_, table, cntx, err := r.mongodb.GetConn()
if err != nil {
return false, err
}
cursor, err := table.Find(cntx, bson.M{"password": password})
if err != nil {
return false, err
}
defer func(cursor *mongo.Cursor, ctx context.Context) {
err := cursor.Close(ctx)
if err != nil {
log.Fatalf("Error to close context -> %v", err)
}
}(cursor, cntx)
if cursor.Next(cntx) {
return true, nil
}
return false, nil
}