Files
pipely/internal/middleware/auth.go
T

47 lines
989 B
Go
Raw Normal View History

2026-07-07 10:29:28 +08:00
package middleware
import (
"net/http"
"strings"
"github.com/gin-gonic/gin"
"onixbyte.com/pipely/internal/auth"
2026-07-07 10:29:28 +08:00
)
func AuthMiddleware(authSvc *auth.Service) gin.HandlerFunc {
return func(c *gin.Context) {
token := extractToken(c)
if token == "" {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Authorisation token is missing"})
2026-07-07 10:29:28 +08:00
return
}
user, err := authSvc.ValidateToken(token)
2026-07-07 10:29:28 +08:00
if err != nil {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Unauthorised: " + err.Error()})
return
}
c.Set("user", user)
c.Next()
}
}
func extractToken(c *gin.Context) string {
// First try the Authorization header
authHeader := c.GetHeader("Authorization")
if authHeader != "" {
parts := strings.SplitN(authHeader, " ", 2)
if len(parts) == 2 && parts[0] == "Bearer" {
return parts[1]
}
}
// Fall back to the cookie set at login
if cookie, err := c.Cookie("pipely_token"); err == nil {
return cookie
}
return ""
}