Files
backend/internal/repository/session_repo.go

90 lines
3.0 KiB
Go
Raw Normal View History

package repository
import (
"context"
"time"
"with_you/internal/model"
"gorm.io/gorm"
)
// SessionRepository 会话仓储接口
//
// 用于支持令牌撤销:登出/封禁按会话或用户撤销refresh token 轮换按 hash 反查。
type SessionRepository interface {
Create(ctx context.Context, session *model.Session) error
GetByID(ctx context.Context, id string) (*model.Session, error)
GetByRefreshTokenHash(ctx context.Context, hash string) (*model.Session, error)
Update(ctx context.Context, session *model.Session) error
Revoke(ctx context.Context, id string) error
RevokeAllByUser(ctx context.Context, userID string) error
RevokeByRefreshTokenHash(ctx context.Context, hash string) error
DeleteExpired(ctx context.Context, before time.Time) error
}
type sessionRepository struct {
db *gorm.DB
}
// NewSessionRepository 创建会话仓储。
func NewSessionRepository(db *gorm.DB) SessionRepository {
return &sessionRepository{db: db}
}
func (r *sessionRepository) Create(ctx context.Context, session *model.Session) error {
return r.db.WithContext(ctx).Create(session).Error
}
func (r *sessionRepository) GetByID(ctx context.Context, id string) (*model.Session, error) {
var s model.Session
if err := r.db.WithContext(ctx).Where("id = ?", id).First(&s).Error; err != nil {
return nil, err
}
return &s, nil
}
func (r *sessionRepository) GetByRefreshTokenHash(ctx context.Context, hash string) (*model.Session, error) {
var s model.Session
if err := r.db.WithContext(ctx).Where("refresh_token_hash = ?", hash).First(&s).Error; err != nil {
return nil, err
}
return &s, nil
}
func (r *sessionRepository) Update(ctx context.Context, session *model.Session) error {
// 仅更新业务关心的列,避免 Save 全字段写回在并发 Rotate 下覆盖 RevokedAt 等字段造成 lost update。
return r.db.WithContext(ctx).Model(&model.Session{}).
Where("id = ?", session.ID).
Updates(map[string]interface{}{
"last_used_at": session.LastUsedAt,
"refresh_token_hash": session.RefreshTokenHash,
}).Error
}
func (r *sessionRepository) Revoke(ctx context.Context, id string) error {
now := time.Now()
return r.db.WithContext(ctx).Model(&model.Session{}).
Where("id = ? AND revoked_at IS NULL", id).
Update("revoked_at", now).Error
}
func (r *sessionRepository) RevokeAllByUser(ctx context.Context, userID string) error {
now := time.Now()
return r.db.WithContext(ctx).Model(&model.Session{}).
Where("user_id = ? AND revoked_at IS NULL", userID).
Update("revoked_at", now).Error
}
func (r *sessionRepository) RevokeByRefreshTokenHash(ctx context.Context, hash string) error {
now := time.Now()
return r.db.WithContext(ctx).Model(&model.Session{}).
Where("refresh_token_hash = ? AND revoked_at IS NULL", hash).
Update("revoked_at", now).Error
}
func (r *sessionRepository) DeleteExpired(ctx context.Context, before time.Time) error {
return r.db.WithContext(ctx).
Where("expires_at < ? OR revoked_at IS NOT NULL", before).
Delete(&model.Session{}).Error
}