/
mongoDBClient.go
87 lines (68 loc) 路 2.01 KB
/
mongoDBClient.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
package database
import (
"context"
"encoding/base64"
"fmt"
"github.com/franpog859/cleanaux-backend/auth-service/internal/model"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
const (
mongoDBServiceURI = "mongodb://mongo-database-internal:27017"
databaseName = "users"
collectionName = "basicauth"
)
// Client interface
type Client interface {
GetAuthorizedUsers(string, string) ([]model.User, error)
}
type client struct {
collection *mongo.Collection
}
// NewClient provides Client interface
func NewClient() (Client, error) {
clientOptions := options.Client().ApplyURI(mongoDBServiceURI)
mongoDBClient, err := mongo.Connect(context.TODO(), clientOptions)
if err != nil {
return nil, fmt.Errorf("failed to connect MongoDB client: %v", err)
}
collection := mongoDBClient.Database(databaseName).Collection(collectionName)
return &client{
collection: collection,
}, nil
}
func (c *client) GetAuthorizedUsers(username, password string) ([]model.User, error) {
encodedPassword := base64.StdEncoding.EncodeToString([]byte(password))
filter := bson.M{
"username": username,
"password": encodedPassword,
}
cursor, err := c.collection.Find(context.TODO(), filter, nil)
if err != nil {
return nil, fmt.Errorf("failed to find users in collection: %v", err)
}
defer cursor.Close(context.TODO())
users, err := getUsersFromCursor(cursor)
if err != nil {
return nil, err
}
return users, nil
}
func getUsersFromCursor(cursor *mongo.Cursor) ([]model.User, error) {
var results []model.User
for cursor.Next(context.TODO()) {
var user model.User
err := cursor.Decode(&user)
if err != nil {
return nil, fmt.Errorf("failed to decode user from cursor: %v", err)
}
decodedPassword, _ := base64.StdEncoding.DecodeString(user.Password)
user.Password = string(decodedPassword)
results = append(results, user)
}
if err := cursor.Err(); err != nil {
return nil, fmt.Errorf("cursor error: %v", err)
}
return results, nil
}