Files
mygo/internal/repository/session.go
T
ld a18f96912d feat(repository): refactor query/mutation ports with capability-safe
interfaces

- refactor: split UserRepository into AuthUserRepository and
  AdminUserRepository capabilities
- refactor: split SessionRepository into AuthSessionRepository and
  repository-owned CLI/admin methods
- refactor: replace generic Repository Update/Delete with
  operation-specific params and ownership predicates
- refactor: replace CredentialRepository generic CRUD with
  passkey-specific methods
- refactor: replace FileRepository generic Create/Update/Delete with
  UploadedFileParams, DirectoryParams, and owned soft-delete
- refactor: remove repository fields from WebApp struct; repositories
  are now composition-time wiring only
- feat: add domain error kinds ErrParentNotFound, ErrParentNotDir,
  ErrDirectoryNotEmpty, ErrInvalidMove
- feat: add CredentialTypeAppPasskey constant
- feat: add testutil.SetUserAdmin for test fixture setup that bypasses
  production service ports
- test: add architecture test banning GORM Save in repository package
- test: add capability interface contract tests ensuring each service
  receives the minimal interface
- test: add blockingStorage helper for concurrent promotion tests
- test: add preserved DSN parameter test for sqliteImmediateDSN
- docs: update architecture decisions with repository write rules and
  capability separation
- docs: update roadmap to clarify atomic single-use refresh sessions
- docs: add -race test target to development docs
2026-07-16 12:24:36 +08:00

135 lines
3.9 KiB
Go

package repository
import (
"context"
"errors"
"time"
"gorm.io/gorm"
"gorm.io/gorm/clause"
"github.com/dhao2001/mygo/internal/model"
)
// RefreshSessionParams contains the fields persisted for a refresh session.
type RefreshSessionParams struct {
ID string
UserID string
TokenHash string
ExpiresAt time.Time
}
// AuthSessionRepository exposes only session operations required by AuthService.
type AuthSessionRepository interface {
CreateRefreshSession(ctx context.Context, params RefreshSessionParams) error
ConsumeRefreshSession(ctx context.Context, tokenHash string) (*model.Session, error)
RevokeRefreshSession(ctx context.Context, tokenHash string) error
}
// SessionRepository is the composition-time union of session capabilities.
type SessionRepository interface {
AuthSessionRepository
FindByID(ctx context.Context, id string) (*model.Session, error)
FindByTokenHash(ctx context.Context, tokenHash string) (*model.Session, error)
DeleteSessionsByUserID(ctx context.Context, userID string) error
DeleteExpiredSessions(ctx context.Context) (int64, error)
}
type sessionRepository struct {
db *gorm.DB
}
// NewSessionRepository creates a SessionRepository backed by GORM.
func NewSessionRepository(db *gorm.DB) SessionRepository {
return &sessionRepository{db: db}
}
func (r *sessionRepository) CreateRefreshSession(ctx context.Context, params RefreshSessionParams) error {
session := &model.Session{
ID: params.ID,
UserID: params.UserID,
TokenHash: params.TokenHash,
ExpiresAt: params.ExpiresAt,
}
result := r.db.WithContext(ctx).Create(session)
if result.Error != nil {
if isDuplicateKeyError(result.Error) {
return model.ErrDuplicate
}
return result.Error
}
return nil
}
func (r *sessionRepository) FindByID(ctx context.Context, id string) (*model.Session, error) {
var session model.Session
result := r.db.WithContext(ctx).First(&session, "id = ?", id)
if errors.Is(result.Error, gorm.ErrRecordNotFound) {
return nil, model.ErrNotFound
}
if result.Error != nil {
return nil, result.Error
}
return &session, nil
}
func (r *sessionRepository) FindByTokenHash(ctx context.Context, tokenHash string) (*model.Session, error) {
var session model.Session
result := r.db.WithContext(ctx).First(&session, "token_hash = ?", tokenHash)
if errors.Is(result.Error, gorm.ErrRecordNotFound) {
return nil, model.ErrNotFound
}
if result.Error != nil {
return nil, result.Error
}
return &session, nil
}
func (r *sessionRepository) ConsumeRefreshSession(ctx context.Context, tokenHash string) (*model.Session, error) {
var consumed model.Session
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
result := tx.Clauses(clause.Locking{Strength: clause.LockingStrengthUpdate}).
First(&consumed, "token_hash = ?", tokenHash)
if errors.Is(result.Error, gorm.ErrRecordNotFound) {
return model.ErrNotFound
}
if result.Error != nil {
return result.Error
}
result = tx.Delete(&model.Session{}, "id = ?", consumed.ID)
if result.Error != nil {
return result.Error
}
if result.RowsAffected == 0 {
return model.ErrNotFound
}
return nil
})
if err != nil {
return nil, err
}
return &consumed, nil
}
func (r *sessionRepository) RevokeRefreshSession(ctx context.Context, tokenHash string) error {
result := r.db.WithContext(ctx).Delete(&model.Session{}, "token_hash = ?", tokenHash)
return result.Error
}
func (r *sessionRepository) DeleteSessionsByUserID(ctx context.Context, userID string) error {
result := r.db.WithContext(ctx).Delete(&model.Session{}, "user_id = ?", userID)
if result.Error != nil {
return result.Error
}
return nil
}
func (r *sessionRepository) DeleteExpiredSessions(ctx context.Context) (int64, error) {
result := r.db.WithContext(ctx).Delete(&model.Session{}, "expires_at < ?", time.Now())
if result.Error != nil {
return 0, result.Error
}
return result.RowsAffected, nil
}