package authser import "github.com/gin-gonic/gin" const requestAuthStateKey = "authser.request-auth-state" // requestAuthState 只在单个 Gin 请求内有效,用来避免多个 SSR 服务重复刷新同一会话。 // freshUser 表示本请求已经从上游取得并写回过的最新用户;suppressAutoAuth // 表示本请求明确不应再自动创建游客(例如用户刚退出或正式账号已过期)。 type requestAuthState struct { freshUser *LoginResp suppressAutoAuth bool } func authState(c *gin.Context) *requestAuthState { if c == nil { return nil } if value, ok := c.Get(requestAuthStateKey); ok { if state, ok := value.(*requestAuthState); ok && state != nil { return state } } state := &requestAuthState{} c.Set(requestAuthStateKey, state) return state } func freshRequestAuthUser(c *gin.Context) *LoginResp { state := authState(c) if state == nil { return nil } return state.freshUser } func rememberRequestAuthUser(c *gin.Context, user *LoginResp) { state := authState(c) if state == nil { return } state.freshUser = user state.suppressAutoAuth = false } func forgetRequestAuthUser(c *gin.Context) { if state := authState(c); state != nil { state.freshUser = nil } } func suppressRequestAutoAuth(c *gin.Context) { if state := authState(c); state != nil { state.suppressAutoAuth = true } } func allowRequestAutoAuth(c *gin.Context) { if state := authState(c); state != nil { state.suppressAutoAuth = false } } func requestAutoAuthSuppressed(c *gin.Context) bool { state := authState(c) return state != nil && state.suppressAutoAuth }