package middleware import ( "net/http" "starter/backend/internal/handlers" "github.com/gin-contrib/sessions" "github.com/gin-gonic/gin" "github.com/logto-io/go/client" ) // AuthRequired 是 Logto 认证中间件,未认证用户返回 401 func AuthRequired() gin.HandlerFunc { return func(c *gin.Context) { session := sessions.Default(c) logtoClient := client.NewLogtoClient(handlers.GetLogtoConfig(), &handlers.SessionStorage{Session: session}) if !logtoClient.IsAuthenticated() { c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"}) return } c.Next() } }