fix(session): scope session access by user
This commit is contained in:
@@ -2,9 +2,11 @@ package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
stderrors "errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
apperrors "github.com/Tencent/WeKnora/internal/errors"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"gorm.io/gorm"
|
||||
@@ -15,6 +17,14 @@ type sessionRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func applySessionUserScope(db *gorm.DB, userID string) *gorm.DB {
|
||||
if userID == "" {
|
||||
return db
|
||||
}
|
||||
// Empty user_id rows are legacy/API-created tenant-level sessions.
|
||||
return db.Where("(user_id = ? OR user_id IS NULL OR user_id = '')", userID)
|
||||
}
|
||||
|
||||
// NewSessionRepository creates a new session repository instance
|
||||
func NewSessionRepository(db *gorm.DB) interfaces.SessionRepository {
|
||||
return &sessionRepository{db: db}
|
||||
@@ -32,19 +42,28 @@ func (r *sessionRepository) Create(ctx context.Context, session *types.Session)
|
||||
}
|
||||
|
||||
// Get retrieves a session by ID
|
||||
func (r *sessionRepository) Get(ctx context.Context, tenantID uint64, id string) (*types.Session, error) {
|
||||
func (r *sessionRepository) Get(ctx context.Context, tenantID uint64, userID string, id string) (*types.Session, error) {
|
||||
var session types.Session
|
||||
err := r.db.WithContext(ctx).Where("tenant_id = ?", tenantID).First(&session, "id = ?", id).Error
|
||||
err := applySessionUserScope(
|
||||
r.db.WithContext(ctx).Where("tenant_id = ? AND id = ?", tenantID, id),
|
||||
userID,
|
||||
).First(&session).Error
|
||||
if err != nil {
|
||||
if stderrors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, apperrors.ErrSessionNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &session, nil
|
||||
}
|
||||
|
||||
// GetByTenantID retrieves all sessions for a tenant
|
||||
func (r *sessionRepository) GetByTenantID(ctx context.Context, tenantID uint64) ([]*types.Session, error) {
|
||||
func (r *sessionRepository) GetByTenantID(ctx context.Context, tenantID uint64, userID string) ([]*types.Session, error) {
|
||||
var sessions []*types.Session
|
||||
err := r.db.WithContext(ctx).Where("tenant_id = ?", tenantID).Order("updated_at DESC").Find(&sessions).Error
|
||||
err := applySessionUserScope(
|
||||
r.db.WithContext(ctx).Where("tenant_id = ?", tenantID),
|
||||
userID,
|
||||
).Order("updated_at DESC").Find(&sessions).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -53,20 +72,26 @@ func (r *sessionRepository) GetByTenantID(ctx context.Context, tenantID uint64)
|
||||
|
||||
// GetPagedByTenantID retrieves sessions for a tenant with pagination
|
||||
func (r *sessionRepository) GetPagedByTenantID(
|
||||
ctx context.Context, tenantID uint64, page *types.Pagination,
|
||||
ctx context.Context, tenantID uint64, userID string, page *types.Pagination,
|
||||
) ([]*types.Session, int64, error) {
|
||||
var sessions []*types.Session
|
||||
var total int64
|
||||
|
||||
// First query the total count
|
||||
err := r.db.WithContext(ctx).Model(&types.Session{}).Where("tenant_id = ?", tenantID).Count(&total).Error
|
||||
baseQ := applySessionUserScope(
|
||||
r.db.WithContext(ctx).Model(&types.Session{}).Where("tenant_id = ?", tenantID),
|
||||
userID,
|
||||
)
|
||||
err := baseQ.Count(&total).Error
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
// Then query the paginated data
|
||||
err = r.db.WithContext(ctx).
|
||||
Where("tenant_id = ?", tenantID).
|
||||
err = applySessionUserScope(
|
||||
r.db.WithContext(ctx).Where("tenant_id = ?", tenantID),
|
||||
userID,
|
||||
).
|
||||
Order("updated_at DESC").
|
||||
Offset(page.Offset()).
|
||||
Limit(page.Limit()).
|
||||
@@ -201,32 +226,45 @@ func (r *sessionRepository) SetPinned(
|
||||
}
|
||||
|
||||
// Update updates a session
|
||||
func (r *sessionRepository) Update(ctx context.Context, session *types.Session) error {
|
||||
func (r *sessionRepository) Update(ctx context.Context, session *types.Session, userID string) (int64, error) {
|
||||
session.UpdatedAt = time.Now()
|
||||
return r.db.WithContext(ctx).
|
||||
res := applySessionUserScope(r.db.WithContext(ctx).
|
||||
Model(&types.Session{}).
|
||||
Where("tenant_id = ? AND id = ?", session.TenantID, session.ID).
|
||||
Where("tenant_id = ? AND id = ?", session.TenantID, session.ID), userID).
|
||||
Updates(map[string]interface{}{
|
||||
"title": session.Title,
|
||||
"description": session.Description,
|
||||
"updated_at": session.UpdatedAt,
|
||||
}).Error
|
||||
})
|
||||
return res.RowsAffected, res.Error
|
||||
}
|
||||
|
||||
// Delete deletes a session
|
||||
func (r *sessionRepository) Delete(ctx context.Context, tenantID uint64, id string) error {
|
||||
return r.db.WithContext(ctx).Where("tenant_id = ?", tenantID).Delete(&types.Session{}, "id = ?", id).Error
|
||||
func (r *sessionRepository) Delete(ctx context.Context, tenantID uint64, userID string, id string) (int64, error) {
|
||||
res := applySessionUserScope(
|
||||
r.db.WithContext(ctx).Where("tenant_id = ? AND id = ?", tenantID, id),
|
||||
userID,
|
||||
).Delete(&types.Session{})
|
||||
return res.RowsAffected, res.Error
|
||||
}
|
||||
|
||||
// BatchDelete deletes multiple sessions by IDs
|
||||
func (r *sessionRepository) BatchDelete(ctx context.Context, tenantID uint64, ids []string) error {
|
||||
func (r *sessionRepository) BatchDelete(ctx context.Context, tenantID uint64, userID string, ids []string) (int64, error) {
|
||||
if len(ids) == 0 {
|
||||
return nil
|
||||
return 0, nil
|
||||
}
|
||||
return r.db.WithContext(ctx).Where("tenant_id = ? AND id IN ?", tenantID, ids).Delete(&types.Session{}).Error
|
||||
res := applySessionUserScope(
|
||||
r.db.WithContext(ctx).Where("tenant_id = ? AND id IN ?", tenantID, ids),
|
||||
userID,
|
||||
).Delete(&types.Session{})
|
||||
return res.RowsAffected, res.Error
|
||||
}
|
||||
|
||||
// DeleteAllByTenantID deletes all sessions for a tenant
|
||||
func (r *sessionRepository) DeleteAllByTenantID(ctx context.Context, tenantID uint64) error {
|
||||
return r.db.WithContext(ctx).Where("tenant_id = ?", tenantID).Delete(&types.Session{}).Error
|
||||
func (r *sessionRepository) DeleteAllByTenantID(ctx context.Context, tenantID uint64, userID string) (int64, error) {
|
||||
res := applySessionUserScope(
|
||||
r.db.WithContext(ctx).Where("tenant_id = ?", tenantID),
|
||||
userID,
|
||||
).Delete(&types.Session{})
|
||||
return res.RowsAffected, res.Error
|
||||
}
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
apperrors "github.com/Tencent/WeKnora/internal/errors"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func newSessionRepositoryForTest(t *testing.T) (interfaces.SessionRepository, *gorm.DB) {
|
||||
t.Helper()
|
||||
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, db.AutoMigrate(&types.Session{}))
|
||||
|
||||
return NewSessionRepository(db), db
|
||||
}
|
||||
|
||||
func createSessionForTest(t *testing.T, db *gorm.DB, tenantID uint64, userID string) *types.Session {
|
||||
t.Helper()
|
||||
|
||||
session := &types.Session{
|
||||
TenantID: tenantID,
|
||||
UserID: userID,
|
||||
Title: userID + " session",
|
||||
}
|
||||
if userID == "" {
|
||||
session.Title = "legacy tenant session"
|
||||
}
|
||||
require.NoError(t, db.Create(session).Error)
|
||||
|
||||
return session
|
||||
}
|
||||
|
||||
func countActiveSessionsForTest(t *testing.T, db *gorm.DB, id string) int64 {
|
||||
t.Helper()
|
||||
|
||||
var count int64
|
||||
require.NoError(t, db.Model(&types.Session{}).Where("id = ?", id).Count(&count).Error)
|
||||
return count
|
||||
}
|
||||
|
||||
func sessionIDsForTest(sessions []*types.Session) []string {
|
||||
ids := make([]string, 0, len(sessions))
|
||||
for _, session := range sessions {
|
||||
ids = append(ids, session.ID)
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
func TestSessionRepositoryGetAndListHonorUserScope(t *testing.T) {
|
||||
repo, db := newSessionRepositoryForTest(t)
|
||||
ctx := context.Background()
|
||||
aliceSession := createSessionForTest(t, db, 1, "alice")
|
||||
bobSession := createSessionForTest(t, db, 1, "bob")
|
||||
legacySession := createSessionForTest(t, db, 1, "")
|
||||
_ = createSessionForTest(t, db, 2, "bob")
|
||||
|
||||
_, err := repo.Get(ctx, 1, "bob", aliceSession.ID)
|
||||
require.ErrorIs(t, err, apperrors.ErrSessionNotFound)
|
||||
|
||||
got, err := repo.Get(ctx, 1, "bob", bobSession.ID)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, bobSession.ID, got.ID)
|
||||
|
||||
got, err = repo.Get(ctx, 1, "bob", legacySession.ID)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, legacySession.ID, got.ID)
|
||||
|
||||
sessions, err := repo.GetByTenantID(ctx, 1, "bob")
|
||||
require.NoError(t, err)
|
||||
require.ElementsMatch(t, []string{bobSession.ID, legacySession.ID}, sessionIDsForTest(sessions))
|
||||
|
||||
paged, total, err := repo.GetPagedByTenantID(ctx, 1, "bob", &types.Pagination{Page: 1, PageSize: 10})
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, 2, total)
|
||||
require.ElementsMatch(t, []string{bobSession.ID, legacySession.ID}, sessionIDsForTest(paged))
|
||||
}
|
||||
|
||||
func TestSessionRepositoryUpdateHonorsUserScope(t *testing.T) {
|
||||
repo, db := newSessionRepositoryForTest(t)
|
||||
ctx := context.Background()
|
||||
aliceSession := createSessionForTest(t, db, 1, "alice")
|
||||
|
||||
rows, err := repo.Update(ctx, &types.Session{
|
||||
ID: aliceSession.ID,
|
||||
TenantID: aliceSession.TenantID,
|
||||
Title: "bob update attempt",
|
||||
}, "bob")
|
||||
require.NoError(t, err)
|
||||
require.Zero(t, rows)
|
||||
|
||||
var unchanged types.Session
|
||||
require.NoError(t, db.First(&unchanged, "id = ?", aliceSession.ID).Error)
|
||||
require.Equal(t, aliceSession.Title, unchanged.Title)
|
||||
|
||||
rows, err = repo.Update(ctx, &types.Session{
|
||||
ID: aliceSession.ID,
|
||||
TenantID: aliceSession.TenantID,
|
||||
Title: "alice updated session",
|
||||
}, "alice")
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, 1, rows)
|
||||
|
||||
var changed types.Session
|
||||
require.NoError(t, db.First(&changed, "id = ?", aliceSession.ID).Error)
|
||||
require.Equal(t, "alice updated session", changed.Title)
|
||||
}
|
||||
|
||||
func TestSessionRepositoryDeleteHonorsUserScope(t *testing.T) {
|
||||
repo, db := newSessionRepositoryForTest(t)
|
||||
ctx := context.Background()
|
||||
aliceSession := createSessionForTest(t, db, 1, "alice")
|
||||
bobSession := createSessionForTest(t, db, 1, "bob")
|
||||
|
||||
rows, err := repo.Delete(ctx, 1, "bob", aliceSession.ID)
|
||||
require.NoError(t, err)
|
||||
require.Zero(t, rows)
|
||||
require.EqualValues(t, 1, countActiveSessionsForTest(t, db, aliceSession.ID))
|
||||
|
||||
rows, err = repo.Delete(ctx, 1, "bob", bobSession.ID)
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, 1, rows)
|
||||
require.Zero(t, countActiveSessionsForTest(t, db, bobSession.ID))
|
||||
}
|
||||
|
||||
func TestSessionRepositoryBatchDeleteHonorsUserScope(t *testing.T) {
|
||||
repo, db := newSessionRepositoryForTest(t)
|
||||
ctx := context.Background()
|
||||
aliceSession := createSessionForTest(t, db, 1, "alice")
|
||||
bobSession := createSessionForTest(t, db, 1, "bob")
|
||||
legacySession := createSessionForTest(t, db, 1, "")
|
||||
|
||||
rows, err := repo.BatchDelete(ctx, 1, "bob", []string{aliceSession.ID, bobSession.ID, legacySession.ID})
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, 2, rows)
|
||||
require.EqualValues(t, 1, countActiveSessionsForTest(t, db, aliceSession.ID))
|
||||
require.Zero(t, countActiveSessionsForTest(t, db, bobSession.ID))
|
||||
require.Zero(t, countActiveSessionsForTest(t, db, legacySession.ID))
|
||||
}
|
||||
|
||||
func TestSessionRepositoryDeleteAllHonorsUserScope(t *testing.T) {
|
||||
repo, db := newSessionRepositoryForTest(t)
|
||||
ctx := context.Background()
|
||||
aliceSession := createSessionForTest(t, db, 1, "alice")
|
||||
bobSession := createSessionForTest(t, db, 1, "bob")
|
||||
legacySession := createSessionForTest(t, db, 1, "")
|
||||
otherTenantSession := createSessionForTest(t, db, 2, "bob")
|
||||
|
||||
rows, err := repo.DeleteAllByTenantID(ctx, 1, "bob")
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, 2, rows)
|
||||
require.EqualValues(t, 1, countActiveSessionsForTest(t, db, aliceSession.ID))
|
||||
require.Zero(t, countActiveSessionsForTest(t, db, bobSession.ID))
|
||||
require.Zero(t, countActiveSessionsForTest(t, db, legacySession.ID))
|
||||
require.EqualValues(t, 1, countActiveSessionsForTest(t, db, otherTenantSession.ID))
|
||||
}
|
||||
Reference in New Issue
Block a user