97 lines
2.1 KiB
Go
97 lines
2.1 KiB
Go
package repository
|
|
|
|
import (
|
|
"codeword/internal/models"
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"github.com/go-redis/redis/v8"
|
|
"go.mongodb.org/mongo-driver/bson"
|
|
"go.mongodb.org/mongo-driver/mongo"
|
|
"go.mongodb.org/mongo-driver/mongo/readpref"
|
|
"time"
|
|
)
|
|
|
|
type Deps struct {
|
|
Mdb *mongo.Collection
|
|
Rdb *redis.Client
|
|
}
|
|
|
|
type codewordRepository struct {
|
|
mdb *mongo.Collection
|
|
rdb *redis.Client
|
|
}
|
|
|
|
type userRepository struct {
|
|
mdb *mongo.Collection
|
|
}
|
|
|
|
func NewUserRepository(deps Deps) *userRepository {
|
|
|
|
return &userRepository{mdb: deps.Mdb}
|
|
}
|
|
|
|
func NewCodewordRepository(deps Deps) *codewordRepository {
|
|
|
|
return &codewordRepository{mdb: deps.Mdb, rdb: deps.Rdb}
|
|
}
|
|
|
|
func (r *userRepository) FindByEmail(ctx context.Context, email string) (*models.User, error) {
|
|
var user models.User
|
|
|
|
err := r.mdb.FindOne(ctx, bson.M{"email": email}).Decode(&user)
|
|
if err != nil {
|
|
if err == mongo.ErrNoDocuments {
|
|
return nil, nil
|
|
}
|
|
return nil, err
|
|
}
|
|
return &user, nil
|
|
}
|
|
|
|
func (r *codewordRepository) StoreRecoveryRecord(ctx context.Context, userID string, email string, key []byte) error {
|
|
record := models.RecoveryRecord{
|
|
UserID: userID,
|
|
Email: email,
|
|
Key: string(key),
|
|
CreatedAt: time.Now(),
|
|
}
|
|
|
|
_, err := r.mdb.InsertOne(ctx, record)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (r *codewordRepository) InsertToQueue(ctx context.Context, userID string, email string, key []byte) error {
|
|
task := models.RecoveryRecord{
|
|
UserID: userID,
|
|
Email: email,
|
|
Key: string(key),
|
|
CreatedAt: time.Now(),
|
|
}
|
|
|
|
taskBytes, err := json.Marshal(task)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
uniqKey := fmt.Sprintf("needRecovery:%d", time.Now().UnixNano())
|
|
|
|
if err := r.rdb.Set(ctx, uniqKey, taskBytes, 0).Err(); err != nil {
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (r *codewordRepository) GetRecoveryRecord(ctx context.Context, key string) (*models.RestoreRequest, error) {
|
|
return &models.RestoreRequest{UserID: "123", Sign: key, CreatedAt: time.Now()}, nil
|
|
}
|
|
|
|
func (r *codewordRepository) Ping(ctx context.Context) error {
|
|
return r.mdb.Database().Client().Ping(ctx, readpref.Primary())
|
|
}
|