yao/openapi/oauth/guard.go
Max 4a2106371e Enhance hello world endpoints with query string and post payload logging
- Added functionality to capture and return the raw query string and post payload in the JSON response for both public and protected hello world endpoints.
- Improved response structure to include additional context for debugging and client-side processing.
2025-08-05 09:28:25 +08:00

79 lines
1.6 KiB
Go

package oauth
import (
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/yaoapp/yao/openapi/oauth/types"
)
// Guard is the OAuth guard middleware
func (s *Service) Guard(c *gin.Context) {
// Get the token from the request
token := s.getAccessToken(c)
// Validate the token
if token == "" {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
c.Abort()
return
}
// Validate the token
claims, err := s.VerifyToken(token)
if err != nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid token"})
c.Abort()
return
}
// Auto refresh the token
if claims.ExpiresAt.Before(time.Now()) {
s.tryAutoRefreshToken(c, claims)
}
}
func (s *Service) tryAutoRefreshToken(c *gin.Context, _ *types.TokenClaims) {
refreshToken := s.getRefreshToken(c)
if refreshToken == "" {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
c.Abort()
return
}
// Verify the refresh token
_, err := s.VerifyToken(refreshToken)
if err != nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid token"})
c.Abort()
return
}
// @Todo: Auto refresh the token
}
func (s *Service) getAccessToken(c *gin.Context) string {
token := c.GetHeader("Authorization")
if token == "" {
cookie, err := c.Cookie("__Host-access_token")
if err != nil {
return ""
}
token = cookie
}
return strings.TrimPrefix(token, "Bearer ")
}
func (s *Service) getRefreshToken(c *gin.Context) string {
token := c.GetHeader("Authorization")
if token == "" {
cookie, err := c.Cookie("__Host-refresh_token")
if err != nil {
return ""
}
token = cookie
}
return strings.TrimPrefix(token, "Bearer ")
}