feat(auth): implement session-based token management with revocation support
Add Session model, SessionService, and SessionRepository to track user login sessions and enable token revocation on auth-critical events. - Introduce explicit TokenType (access/refresh) in JWT claims to prevent refresh token misuse via access token endpoints - Add SessionID field to JWT claims, enabling stateless JWT validation against revoked sessions - Replace legacy Auth middleware with RequireAuth/OptionalAuth pipeline that validates token type, account status, and session validity - Implement session revocation on password change, reset, user ban/inactive, and explicit logout - Add Principal cache with active invalidation for banned/role-changed users - Fix IDOR vulnerability: GetMessagesByCursor now validates currentUserID is conversation participant via GetParticipantStrict - Add group member visibility checks: announcements, group info, member list now require group membership - Simplify Casbin policy: remove g grouping, use r.sub == p.sub matcher with globMatch; user_roles table is single source of truth for roles - Add migration logic to clean legacy casbin g rules and migrate old p rules from path-style to admin/<domain> resource naming
This commit is contained in:
@@ -26,6 +26,10 @@ type MessageRepository interface {
|
||||
GetMessagesBeforeSeq(conversationID string, beforeSeq int64, limit int) ([]*model.Message, error)
|
||||
GetConversationParticipants(conversationID string) ([]*model.ConversationParticipant, error)
|
||||
GetParticipant(conversationID string, userID string) (*model.ConversationParticipant, error)
|
||||
// GetParticipantStrict 纯查询:返回用户在某会话中的参与者记录。
|
||||
// 不存在时返回 gorm.ErrRecordNotFound,**不会**创建记录。
|
||||
// 用于鉴权场景(如校验非会话参与者不能读取消息),避免 GetParticipant 的自动创建副作用造成鉴权绕过。
|
||||
GetParticipantStrict(conversationID string, userID string) (*model.ConversationParticipant, error)
|
||||
UpdateLastReadSeq(conversationID string, userID string, lastReadSeq int64) error
|
||||
UpdatePinned(conversationID string, userID string, isPinned bool) error
|
||||
UpdateNotificationMuted(conversationID string, userID string, notificationMuted bool) error
|
||||
@@ -253,6 +257,10 @@ func (r *messageRepository) GetConversationParticipants(conversationID string) (
|
||||
|
||||
// GetParticipant 获取用户在会话中的参与者信息
|
||||
// userID 参数为 string 类型(UUID格式),与JWT中user_id保持一致
|
||||
//
|
||||
// 注意:本方法在参与者记录不存在但会话存在时会**自动创建**参与者记录。
|
||||
// 该副作用适用于"确保参与者存在"的写路径;鉴权/读取路径应改用 GetParticipantStrict,
|
||||
// 否则非参与者的查询会被静默升级为成员(鉴权绕过)。
|
||||
func (r *messageRepository) GetParticipant(conversationID string, userID string) (*model.ConversationParticipant, error) {
|
||||
var participant model.ConversationParticipant
|
||||
err := r.db.Where("conversation_id = ? AND user_id = ?", conversationID, userID).First(&participant).Error
|
||||
@@ -278,6 +286,17 @@ func (r *messageRepository) GetParticipant(conversationID string, userID string)
|
||||
return &participant, nil
|
||||
}
|
||||
|
||||
// GetParticipantStrict 纯查询参与者记录,不存在即返回 gorm.ErrRecordNotFound,不创建。
|
||||
//
|
||||
// 用于鉴权:避免 GetParticipant 的"自动创建"副作用把非成员静默升级为成员。
|
||||
func (r *messageRepository) GetParticipantStrict(conversationID string, userID string) (*model.ConversationParticipant, error) {
|
||||
var participant model.ConversationParticipant
|
||||
if err := r.db.Where("conversation_id = ? AND user_id = ?", conversationID, userID).First(&participant).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &participant, nil
|
||||
}
|
||||
|
||||
// UpdateLastReadSeq 更新已读位置(防回退:仅当新值大于当前值时才更新)
|
||||
// userID 参数为 string 类型(UUID格式),与JWT中user_id保持一致
|
||||
func (r *messageRepository) UpdateLastReadSeq(conversationID string, userID string, lastReadSeq int64) error {
|
||||
|
||||
90
internal/repository/session_repo.go
Normal file
90
internal/repository/session_repo.go
Normal file
@@ -0,0 +1,90 @@
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user