Documentation
¶
Index ¶
- Constants
- Variables
- func AuthMiddleware(validator Validator) gin.HandlerFunc
- func CORSMiddleware(cfg *config.ServerConfig) gin.HandlerFunc
- func ConnIsClosed(sc *SafeConn) bool
- func ErrorHandler() gin.HandlerFunc
- func GetActiveConnectionCount() int
- func GetWSClient(sc *SafeConn) *ws.Client
- func IsWebSocket(c *gin.Context) bool
- func RequestIDMiddleware() gin.HandlerFunc
- func RequireRole(tripModel tripinterfaces.TripModelInterface, requiredRole types.MemberRole) gin.HandlerFunc
- func ValidateTokenWithoutAbort(validator Validator, token string) (string, error)
- func WSJwtAuth(validator Validator) gin.HandlerFunc
- func WSMiddleware(config WSConfig, metrics *WSMetrics) gin.HandlerFunc
- func WSRateLimiter(redisClient *redis.Client, maxConnPerUser int, window time.Duration) gin.HandlerFunc
- type ErrorResponse
- type JWKSCache
- type JWTValidator
- type SafeConn
- func (sc *SafeConn) Close() error
- func (sc *SafeConn) DoneChannel() <-chan struct{}
- func (sc *SafeConn) ReadChannel() <-chan []byte
- func (sc *SafeConn) SendMessage(message []byte) error
- func (sc *SafeConn) WriteControl(messageType int, data []byte, deadline time.Time) error
- func (sc *SafeConn) WriteMessage(messageType int, data []byte) error
- type StringWrapper
- type Validator
- type WSClaims
- type WSConfig
- type WSMetrics
Constants ¶
const ( WebSocketConnectionKey = "wsConnection" UserProfileKey = "userProfile" )
Context keys
const (
// RequestIDKey is the key used to store the request ID in the gin context
RequestIDKey = "request_id"
)
const (
// UserIDKey is the context key for the authenticated user's ID (string).
UserIDKey contextKey = "userID"
)
Defines context keys used within the application middleware and handlers.
Variables ¶
var ( // ErrTokenExpired is returned when JWT validation fails due to expiry. ErrTokenExpired = errors.New("token expired") // ErrTokenInvalid is returned for general token validation failures (signature, format). ErrTokenInvalid = errors.New("token invalid") // ErrTokenMissingClaim is returned if a required claim (like 'sub') is missing. ErrTokenMissingClaim = errors.New("token missing required claim") ErrValidationMethodUnavailable = errors.New("no validation method available for token") // ErrJWKSKeyNotFound is returned if the key specified by 'kid' is not found in JWKS. ErrJWKSKeyNotFound = errors.New("jwks key not found") )
var (
ErrBackpressure = fmt.Errorf("client cannot keep up with message rate")
)
Functions ¶
func AuthMiddleware ¶
func AuthMiddleware(validator Validator) gin.HandlerFunc
AuthMiddleware creates a Gin middleware for authenticating requests using JWT.
func CORSMiddleware ¶
func CORSMiddleware(cfg *config.ServerConfig) gin.HandlerFunc
CORSMiddleware creates a middleware for handling CORS with the given configuration
func ConnIsClosed ¶
func ErrorHandler ¶
func ErrorHandler() gin.HandlerFunc
func GetActiveConnectionCount ¶
func GetActiveConnectionCount() int
func GetWSClient ¶
GetWSClient returns a ws.Client for a given SafeConn
func IsWebSocket ¶
func RequestIDMiddleware ¶
func RequestIDMiddleware() gin.HandlerFunc
RequestIDMiddleware adds a unique request ID to each request
func RequireRole ¶
func RequireRole(tripModel tripinterfaces.TripModelInterface, requiredRole types.MemberRole) gin.HandlerFunc
RequireRole enforces role-based access control for a specific route
func ValidateTokenWithoutAbort ¶
Update ValidateTokenWithoutAbort to accept the interface as well
func WSJwtAuth ¶
func WSJwtAuth(validator Validator) gin.HandlerFunc
WSJwtAuth provides optimized JWT authentication middleware for WebSocket connections
func WSMiddleware ¶
func WSMiddleware(config WSConfig, metrics *WSMetrics) gin.HandlerFunc
func WSRateLimiter ¶
func WSRateLimiter(redisClient *redis.Client, maxConnPerUser int, window time.Duration) gin.HandlerFunc
Types ¶
type ErrorResponse ¶
type JWKSCache ¶
type JWKSCache struct {
// contains filtered or unexported fields
}
JWKSCache is a thread-safe cache for JWKS keys.
func GetJWKSCache ¶
GetJWKSCache initializes and returns a singleton instance of the JWKS cache. Configuration parameters (URL, Anon Key, TTL) must be provided on first call.
type JWTValidator ¶
type JWTValidator struct {
// contains filtered or unexported fields
}
JWTValidator encapsulates JWT validation logic using static secrets and JWKS.
func (*JWTValidator) Validate ¶
func (v *JWTValidator) Validate(tokenString string) (string, error)
Validate parses and validates the token using configured methods. It tries HS256 first (if configured), then JWKS (if configured and 'kid' is present). Returns userID (subject claim) and a specific error (ErrTokenExpired, ErrTokenInvalid, etc.).
type SafeConn ¶
type SafeConn struct { *websocket.Conn UserID string TripID string // contains filtered or unexported fields }
Improve the SafeConn struct to better handle connection state
func NewSafeConn ¶
func (*SafeConn) DoneChannel ¶
func (sc *SafeConn) DoneChannel() <-chan struct{}
DoneChannel returns a channel that is closed when the connection is closed
func (*SafeConn) ReadChannel ¶
ReadChannel returns the read channel for receiving WebSocket messages
func (*SafeConn) SendMessage ¶
SendMessage sends a message through the websocket connection with proper error handling
func (*SafeConn) WriteControl ¶
type StringWrapper ¶
type StringWrapper string
StringWrapper is a simple wrapper for string that implements String() method
func (StringWrapper) String ¶
func (s StringWrapper) String() string
String implements the interface{String() string} required by the JWT validator
type WSClaims ¶
type WSClaims struct { UserID string `json:"sub"` jwt.RegisteredClaims }
Claims represents the JWT claims structure
type WSConfig ¶
type WSConfig struct { AllowedOrigins []string CheckOrigin func(r *http.Request) bool WriteBufferSize int // Default 1024 ReadBufferSize int // Default 1024 MaxMessageSize int64 // Default 512KB WriteWait time.Duration // Time allowed to write a message PongWait time.Duration // Time allowed to read the next pong message PingPeriod time.Duration // Send pings to peer with this period ReauthInterval time.Duration // JWT revalidation interval BufferHighWater int // Backpressure threshold BufferLowWater int // Backpressure release threshold ReconnectBackoff time.Duration // For client reconnect attempts }
func DefaultWSConfig ¶
func DefaultWSConfig() WSConfig
type WSMetrics ¶
type WSMetrics struct { ConnectionsActive prometheus.Gauge MessagesReceived prometheus.Counter MessagesSent prometheus.Counter ErrorsTotal *prometheus.CounterVec // contains filtered or unexported fields }