package repository import ( "context" "git.sch9.ru/new_gate/ms-auth/config" "git.sch9.ru/new_gate/ms-auth/internal/models" "git.sch9.ru/new_gate/ms-auth/pkg/utils" "github.com/valkey-io/valkey-go" "go.uber.org/zap" "strconv" "time" ) type valkeyRepository struct { db valkey.Client cfg config.Config logger *zap.Logger } func NewValkeyRepository(db valkey.Client, cfg config.Config, logger *zap.Logger) *valkeyRepository { return &valkeyRepository{ db: db, cfg: cfg, logger: logger, } } const sessionLifetime = time.Minute * 40 func (r *valkeyRepository) CreateSession(ctx context.Context, userId int32) error { session := models.NewSession(userId) resp := r.db.Do(ctx, r.db. B().Set(). Key(strconv.Itoa(int(userId))). Value(*session.Id). Nx(). Exat(time.Now().Add(sessionLifetime)). Build(), ) if err := resp.Error(); err != nil { return utils.ErrInternal } return nil } func (r *valkeyRepository) ReadSessionByToken(ctx context.Context, token string) (*models.Session, error) { session, err := models.Parse(token, r.cfg.JWTSecret) if err != nil { return nil, err } sessionRecord, err := r.ReadSessionByUserId(ctx, *session.UserId) if err != nil { return nil, err } if *session.Id != *sessionRecord.Id { return nil, utils.ErrInternal } return session, err } func (r *valkeyRepository) ReadSessionByUserId(ctx context.Context, userId int32) (*models.Session, error) { resp := r.db.Do(ctx, r.db.B().Get().Key(strconv.Itoa(int(userId))).Build()) if err := resp.Error(); err != nil { return nil, utils.ErrInternal } id, err := resp.ToString() if err != nil { return nil, utils.ErrInternal } return &models.Session{ Id: &id, UserId: &userId, }, err } func (r *valkeyRepository) UpdateSession(ctx context.Context, session *models.Session) error { resp := r.db.Do(ctx, r.db. B().Set(). Key(strconv.Itoa(int(*session.UserId))). Value(*session.Id). Xx(). Exat(time.Now().Add(sessionLifetime)). Build(), ) if err := resp.Error(); err != nil { return utils.ErrInternal } return nil } func (r *valkeyRepository) DeleteSessionByToken(ctx context.Context, token string) error { session, err := models.Parse(token, r.cfg.JWTSecret) if err != nil { return err } err = r.DeleteSessionByUserId(ctx, *session.UserId) if err != nil { return err } return nil } func (r *valkeyRepository) DeleteSessionByUserId(ctx context.Context, userId int32) error { resp := r.db.Do(ctx, r.db. B().Del(). Key(strconv.Itoa(int(userId))). Build(), ) if err := resp.Error(); err != nil { return utils.ErrInternal } return nil }