chore: update session and challenge repo -- using Redis for caching session and challenge verifying -- added api handler docs

This commit is contained in:
2025-09-09 13:31:41 +03:30
parent dee9ce2f64
commit 6bf6a8ffc2
20 changed files with 1077 additions and 193 deletions
View File
+80
View File
@@ -0,0 +1,80 @@
package cache
import (
"backend/internal/domain"
"backend/pkg/cache"
"context"
"encoding/json"
"fmt"
"time"
"github.com/redis/go-redis/v9"
)
type ChallengeRepository struct {
redis *cache.Redis
}
func NewChallengeRepository(redis *cache.Redis) domain.ChallengeRepo {
return &ChallengeRepository{
redis: redis,
}
}
func (r *ChallengeRepository) Create(ctx context.Context, pubKey string, challenge *domain.Challenge) error {
key := r.getChallengeKey(pubKey)
challengeData, err := json.Marshal(challenge)
if err != nil {
return fmt.Errorf("failed to marshal challenge: %w", err)
}
ttl := time.Until(challenge.ExpiresAt)
if ttl <= 0 {
return fmt.Errorf("challenge already expired")
}
if err := r.redis.Client().Set(ctx, key, challengeData, ttl).Err(); err != nil {
return fmt.Errorf("failed to store challenge in Redis: %w", err)
}
return nil
}
func (r *ChallengeRepository) GetByPubKey(ctx context.Context, pubKey string) (*domain.Challenge, error) {
key := r.getChallengeKey(pubKey)
result, err := r.redis.Client().Get(ctx, key).Result()
if err != nil {
if err == redis.Nil {
return nil, fmt.Errorf("challenge not found")
}
return nil, fmt.Errorf("failed to get challenge from Redis: %w", err)
}
var challenge domain.Challenge
if err := json.Unmarshal([]byte(result), &challenge); err != nil {
return nil, fmt.Errorf("failed to unmarshal challenge: %w", err)
}
if challenge.IsExpired() {
r.Delete(ctx, pubKey)
return nil, fmt.Errorf("challenge expired")
}
return &challenge, nil
}
func (r *ChallengeRepository) Delete(ctx context.Context, pubKey string) error {
key := r.getChallengeKey(pubKey)
if err := r.redis.Client().Del(ctx, key).Err(); err != nil {
return fmt.Errorf("failed to delete challenge from Redis: %w", err)
}
return nil
}
func (r *ChallengeRepository) getChallengeKey(pubKey string) string {
return fmt.Sprintf("challenge:%s", pubKey)
}
+135
View File
@@ -0,0 +1,135 @@
package cache
import (
"backend/internal/domain"
"backend/pkg/cache"
"context"
"encoding/json"
"fmt"
"time"
"github.com/google/uuid"
"github.com/redis/go-redis/v9"
)
type SessionRepository struct {
redis *cache.Redis
}
func NewSessionRepository(redis *cache.Redis) domain.SessionRepo {
return &SessionRepository{
redis: redis,
}
}
func (r *SessionRepository) Create(ctx context.Context, session *domain.UserSession) error {
key := r.getSessionKey(session.ID)
sessionData, err := json.Marshal(session)
if err != nil {
return fmt.Errorf("failed to marshal session: %w", err)
}
ttl := time.Until(session.ExpiresAt)
if ttl <= 0 {
return fmt.Errorf("session already expired")
}
if err := r.redis.Client().Set(ctx, key, sessionData, ttl).Err(); err != nil {
return fmt.Errorf("failed to store session in Redis: %w", err)
}
userSessionsKey := r.getUserSessionsKey(session.UserID)
if err := r.redis.Client().SAdd(ctx, userSessionsKey, session.ID.String()).Err(); err != nil {
return fmt.Errorf("failed to add session to user sessions set: %w", err)
}
if err := r.redis.Client().Expire(ctx, userSessionsKey, ttl).Err(); err != nil {
return fmt.Errorf("failed to set TTL for user sessions set: %w", err)
}
return nil
}
func (r *SessionRepository) GetByID(ctx context.Context, id uuid.UUID) (*domain.UserSession, error) {
key := r.getSessionKey(id)
result, err := r.redis.Client().Get(ctx, key).Result()
if err != nil {
if err == redis.Nil {
return nil, fmt.Errorf("session not found")
}
return nil, fmt.Errorf("failed to get session from Redis: %w", err)
}
var session domain.UserSession
if err := json.Unmarshal([]byte(result), &session); err != nil {
return nil, fmt.Errorf("failed to unmarshal session: %w", err)
}
if time.Now().After(session.ExpiresAt) {
r.Delete(ctx, id)
return nil, fmt.Errorf("session expired")
}
return &session, nil
}
func (r *SessionRepository) Delete(ctx context.Context, id uuid.UUID) error {
key := r.getSessionKey(id)
session, err := r.GetByID(ctx, id)
if err != nil {
return nil
}
if err := r.redis.Client().Del(ctx, key).Err(); err != nil {
return fmt.Errorf("failed to delete session from Redis: %w", err)
}
userSessionsKey := r.getUserSessionsKey(session.UserID)
if err := r.redis.Client().SRem(ctx, userSessionsKey, id.String()).Err(); err != nil {
return fmt.Errorf("failed to remove session from user sessions set: %w", err)
}
return nil
}
func (r *SessionRepository) GetUserSessions(ctx context.Context, userID uuid.UUID) ([]domain.UserSession, error) {
userSessionsKey := r.getUserSessionsKey(userID)
sessionIDs, err := r.redis.Client().SMembers(ctx, userSessionsKey).Result()
if err != nil {
if err == redis.Nil {
return []domain.UserSession{}, nil
}
return nil, fmt.Errorf("failed to get user sessions from Redis: %w", err)
}
var sessions []domain.UserSession
for _, sessionIDStr := range sessionIDs {
sessionID, err := uuid.Parse(sessionIDStr)
if err != nil {
r.redis.Client().SRem(ctx, userSessionsKey, sessionIDStr)
continue
}
session, err := r.GetByID(ctx, sessionID)
if err != nil {
r.redis.Client().SRem(ctx, userSessionsKey, sessionIDStr)
continue
}
sessions = append(sessions, *session)
}
return sessions, nil
}
func (r *SessionRepository) getSessionKey(sessionID uuid.UUID) string {
return fmt.Sprintf("session:%s", sessionID.String())
}
func (r *SessionRepository) getUserSessionsKey(userID uuid.UUID) string {
return fmt.Sprintf("user_sessions:%s", userID.String())
}
@@ -1,56 +0,0 @@
package storage
import (
"backend/internal/domain"
"backend/internal/repository/storage/types"
"context"
"github.com/google/uuid"
"gorm.io/gorm"
)
type SessionRepository struct {
db *gorm.DB
}
func NewSessionRepository(db *gorm.DB) domain.SessionRepo {
return &SessionRepository{
db: db,
}
}
func (r *SessionRepository) Create(ctx context.Context, session *domain.UserSession) error {
model := types.CastSessionToStorage(*session)
return r.db.WithContext(ctx).Create(&model).Error
}
func (r *SessionRepository) GetByID(ctx context.Context, id uuid.UUID) (*domain.UserSession, error) {
var session types.UserSession
if err := r.db.WithContext(ctx).Preload("User").First(&session, "id = ?", id).Error; err != nil {
return nil, err
}
return types.CastSessionToDomain(session), nil
}
func (r *SessionRepository) Delete(ctx context.Context, id uuid.UUID) error {
var session types.UserSession
if err := r.db.WithContext(ctx).First(&session, "id = ?", id).Error; err != nil {
return err
}
return r.db.WithContext(ctx).Delete(&session).Error
}
func (r *SessionRepository) GetUserSessions(ctx context.Context, userID uuid.UUID) ([]domain.UserSession, error) {
var sessions []types.UserSession
if err := r.db.WithContext(ctx).Preload("User").Find(&sessions, "user_id = ?", userID).Error; err != nil {
return nil, err
}
result := make([]domain.UserSession, len(sessions))
for i, session := range sessions {
result[i] = *types.CastSessionToDomain(session)
}
return result, nil
}
@@ -1,44 +0,0 @@
package types
import (
"backend/internal/domain"
"time"
"github.com/google/uuid"
)
type UserSession struct {
Base
UserID uuid.UUID
User *User
WalletID string
ExpireAt time.Time
}
func CastSessionToStorage(s domain.UserSession) *UserSession {
return &UserSession{
Base: Base{
ID: s.ID,
CreatedAt: s.CreatedAt,
UpdatedAt: s.UpdatedAt,
DeletedAt: s.DeletedAt,
},
UserID: s.UserID,
User: CastUserToStorage(s.User),
WalletID: s.WalletID,
ExpireAt: s.ExpiresAt,
}
}
func CastSessionToDomain(s UserSession) *domain.UserSession {
return &domain.UserSession{
ID: s.ID,
UserID: s.UserID,
User: *CastUserToDomain(*s.User),
WalletID: s.WalletID,
ExpiresAt: s.ExpireAt,
CreatedAt: s.CreatedAt,
UpdatedAt: s.UpdatedAt,
DeletedAt: s.DeletedAt,
}
}