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:
22
internal/pkg/auth/cache.go
Normal file
22
internal/pkg/auth/cache.go
Normal file
@@ -0,0 +1,22 @@
|
||||
package auth
|
||||
|
||||
import "with_you/internal/cache"
|
||||
|
||||
// InvalidatePrincipalCache 失效用户的 Principal 缓存。
|
||||
//
|
||||
// 供角色变更、账户状态变更、登出等场景调用:让 RequireAuth 在下一次请求
|
||||
// 重新从 IDP 加载用户与角色。键定义在本包以避免 service → middleware 的包循环。
|
||||
func InvalidatePrincipalCache(cch cache.Cache, userID string) {
|
||||
if cch == nil || userID == "" {
|
||||
return
|
||||
}
|
||||
cch.Delete(PrincipalCacheKey(userID))
|
||||
}
|
||||
|
||||
// InvalidateSessionCache 失效会话有效性缓存。
|
||||
func InvalidateSessionCache(cch cache.Cache, sessionID string) {
|
||||
if cch == nil || sessionID == "" {
|
||||
return
|
||||
}
|
||||
cch.Delete(SessionCacheKey(sessionID))
|
||||
}
|
||||
116
internal/pkg/auth/principal.go
Normal file
116
internal/pkg/auth/principal.go
Normal file
@@ -0,0 +1,116 @@
|
||||
// Package auth 提供统一的安全状态载体与认证管道。
|
||||
//
|
||||
// Principal 是贯穿 middleware → handler → service 的类型化身份契约,
|
||||
// 取代散落的 c.Set("user_id", ...) 字符串约定,让账户状态/角色/会话在编译期显式可见。
|
||||
package auth
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"with_you/internal/model"
|
||||
)
|
||||
|
||||
const (
|
||||
// ContextKey 是 Principal 在 gin.Context 中的键。
|
||||
// 使用私有类型别名以避免与其他包的字符串键冲突。
|
||||
contextKey principalCtxKey = "auth_principal"
|
||||
)
|
||||
|
||||
type principalCtxKey string
|
||||
|
||||
// Principal 已认证主体
|
||||
//
|
||||
// 由 RequireAuth 中间件一次性组装完成,包含:
|
||||
// - 身份信息(UserID / Username / SessionID)
|
||||
// - 账户状态(Status / VerificationStatus)
|
||||
// - 角色集合(Roles,由 Casbin/App DB 加载)
|
||||
//
|
||||
// 不再由各 handler/service 重复查询数据库,统一由认证管道负责加载与缓存。
|
||||
type Principal struct {
|
||||
UserID string
|
||||
Username string
|
||||
SessionID string
|
||||
Status model.UserStatus
|
||||
VerificationStatus model.VerificationStatus
|
||||
Roles []string
|
||||
TokenID string
|
||||
IsLegacyToken bool // 旧客户端签发的 access token(无 typ/sid),过渡期宽容通过
|
||||
}
|
||||
|
||||
// HasRole 检查主体是否拥有指定角色。
|
||||
func (p *Principal) HasRole(role string) bool {
|
||||
if p == nil {
|
||||
return false
|
||||
}
|
||||
for _, r := range p.Roles {
|
||||
if r == role {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// IsSuperAdmin 是否超级管理员。
|
||||
func (p *Principal) IsSuperAdmin() bool {
|
||||
return p.HasRole(model.RoleSuperAdmin)
|
||||
}
|
||||
|
||||
// IsAdmin 是否管理员(含超级管理员)。
|
||||
func (p *Principal) IsAdmin() bool {
|
||||
return p.HasRole(model.RoleAdmin) || p.IsSuperAdmin()
|
||||
}
|
||||
|
||||
// IsActive 账户状态是否为 active。
|
||||
func (p *Principal) IsActive() bool {
|
||||
return p != nil && p.Status == model.UserStatusActive
|
||||
}
|
||||
|
||||
// IsVerified 是否已通过身份认证。
|
||||
func (p *Principal) IsVerified() bool {
|
||||
return p != nil && p.VerificationStatus == model.VerificationStatusApproved
|
||||
}
|
||||
|
||||
// WithContext 把 Principal 写入 gin.Context。
|
||||
func WithContext(c *gin.Context, p *Principal) {
|
||||
c.Set(string(contextKey), p)
|
||||
// 同时保留 user_id / username 字符串键以兼容存量 handler 调用。
|
||||
c.Set("user_id", p.UserID)
|
||||
c.Set("username", p.Username)
|
||||
}
|
||||
|
||||
// GetPrincipal 从 gin.Context 读取 Principal,返回是否已认证。
|
||||
func GetPrincipal(c *gin.Context) (*Principal, bool) {
|
||||
v, ok := c.Get(string(contextKey))
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
p, ok := v.(*Principal)
|
||||
return p, ok
|
||||
}
|
||||
|
||||
// MustPrincipal 从 gin.Context 读取 Principal,未认证时返回 nil。
|
||||
// 调用方应仅在 RequireAuth 之后使用。
|
||||
func MustPrincipal(c *gin.Context) *Principal {
|
||||
p, _ := GetPrincipal(c)
|
||||
return p
|
||||
}
|
||||
|
||||
// PrincipalCacheKey 返回某用户的 Principal 缓存键。
|
||||
//
|
||||
// 缓存键与 middleware.RequireAuth / InvalidatePrincipalCache 共享,
|
||||
// 定义在本包以避免 service → middleware 的包循环(service 仅需失效键,
|
||||
// middleware 负责读写 Principal 实体)。
|
||||
func PrincipalCacheKey(userID string) string {
|
||||
return "auth:principal:" + userID
|
||||
}
|
||||
|
||||
// SessionCacheKey 返回某会话有效性缓存键。
|
||||
func SessionCacheKey(sessionID string) string {
|
||||
return "auth:session:" + sessionID + ":valid"
|
||||
}
|
||||
|
||||
// CacheKeyPrefix 命名空间前缀,用于按前缀批量失效。
|
||||
const (
|
||||
CacheKeyPrefixPrincipal = "auth:principal:"
|
||||
CacheKeyPrefixSession = "auth:session:"
|
||||
)
|
||||
Reference in New Issue
Block a user