86 lines
2.1 KiB
Go
86 lines
2.1 KiB
Go
package repository
|
||
|
||
import (
|
||
"codeword/internal/models"
|
||
"context"
|
||
"encoding/json"
|
||
"github.com/go-redis/redis/v8"
|
||
"go.mongodb.org/mongo-driver/bson"
|
||
"go.mongodb.org/mongo-driver/bson/primitive"
|
||
"go.mongodb.org/mongo-driver/mongo"
|
||
"go.mongodb.org/mongo-driver/mongo/readpref"
|
||
"time"
|
||
)
|
||
|
||
type codewordRepository struct {
|
||
mdb *mongo.Collection
|
||
rdb *redis.Client
|
||
}
|
||
|
||
func NewCodewordRepository(deps Deps) *codewordRepository {
|
||
|
||
return &codewordRepository{mdb: deps.Mdb, rdb: deps.Rdb}
|
||
}
|
||
|
||
// сохраняем полученные данные о пользователе и подписи в бд
|
||
func (r *codewordRepository) StoreRecoveryRecord(ctx context.Context, userID, email, key, url string) (string, error) {
|
||
newID := primitive.NewObjectID()
|
||
signID := key + newID.Hex()
|
||
record := models.RestoreRequest{
|
||
ID: newID,
|
||
UserID: userID,
|
||
Email: email,
|
||
Sign: key,
|
||
SignUrl: url,
|
||
SignID: signID,
|
||
CreatedAt: time.Now(),
|
||
}
|
||
|
||
_, err := r.mdb.InsertOne(ctx, record)
|
||
if err != nil {
|
||
return "", err
|
||
}
|
||
|
||
return newID.Hex(), nil
|
||
}
|
||
|
||
// добавляем в очередь данные для отправки на почту в редис
|
||
func (r *codewordRepository) InsertToQueue(ctx context.Context, userID string, email string, singWithID string, id string) error {
|
||
task := models.RecoveryRecord{
|
||
ID: id,
|
||
UserID: userID,
|
||
Email: email,
|
||
Key: singWithID,
|
||
}
|
||
|
||
taskBytes, err := json.Marshal(task)
|
||
if err != nil {
|
||
return err
|
||
}
|
||
|
||
if err := r.rdb.LPush(ctx, "recoveryQueue", taskBytes).Err(); err != nil {
|
||
return err
|
||
}
|
||
|
||
return nil
|
||
}
|
||
|
||
// получаем данные юзера по подписи
|
||
func (r *codewordRepository) GetRecoveryRecord(ctx context.Context, key string) (*models.RestoreRequest, error) {
|
||
var restoreRequest models.RestoreRequest
|
||
|
||
filter := bson.M{"sign_id": key}
|
||
|
||
err := r.mdb.FindOne(ctx, filter).Decode(&restoreRequest)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
|
||
return &restoreRequest, nil
|
||
}
|
||
|
||
// пингует в монгу чтобы проверить подключение
|
||
func (r *codewordRepository) Ping(ctx context.Context) error {
|
||
return r.mdb.Database().Client().Ping(ctx, readpref.Primary())
|
||
}
|