tercul-backend/internal/data/sql/user_session_repository.go

60 lines
1.8 KiB
Go

package repositories
import (
"context"
"errors"
"gorm.io/gorm"
"tercul/internal/models"
"time"
)
// UserSessionRepository defines CRUD methods specific to UserSession.
type UserSessionRepository interface {
BaseRepository[models.UserSession]
GetByToken(ctx context.Context, token string) (*models.UserSession, error)
GetByUserID(ctx context.Context, userID uint) ([]models.UserSession, error)
DeleteExpired(ctx context.Context) error
}
type userSessionRepository struct {
BaseRepository[models.UserSession]
db *gorm.DB
}
// NewUserSessionRepository creates a new UserSessionRepository.
func NewUserSessionRepository(db *gorm.DB) UserSessionRepository {
return &userSessionRepository{
BaseRepository: NewBaseRepositoryImpl[models.UserSession](db),
db: db,
}
}
// GetByToken finds a session by token
func (r *userSessionRepository) GetByToken(ctx context.Context, token string) (*models.UserSession, error) {
var session models.UserSession
if err := r.db.WithContext(ctx).Where("token = ?", token).First(&session).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrEntityNotFound
}
return nil, err
}
return &session, nil
}
// GetByUserID finds sessions by user ID
func (r *userSessionRepository) GetByUserID(ctx context.Context, userID uint) ([]models.UserSession, error) {
var sessions []models.UserSession
if err := r.db.WithContext(ctx).Where("user_id = ?", userID).Find(&sessions).Error; err != nil {
return nil, err
}
return sessions, nil
}
// DeleteExpired deletes expired sessions
func (r *userSessionRepository) DeleteExpired(ctx context.Context) error {
if err := r.db.WithContext(ctx).Where("expires_at < ?", time.Now()).Delete(&models.UserSession{}).Error; err != nil {
return err
}
return nil
}