Files
pipely/internal/middleware/auth.go
T

35 lines
823 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) {
authHeader := c.GetHeader("Authorization")
if authHeader == "" {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Authorisation header is missing"})
return
}
parts := strings.SplitN(authHeader, " ", 2)
if !(len(parts) == 2 && parts[0] == "Bearer") {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Invalid authorisation format"})
return
}
user, err := authSvc.ValidateToken(parts[1])
if err != nil {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Unauthorised: " + err.Error()})
return
}
c.Set("user", user)
c.Next()
}
}