// 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:" )