middleware

package
v0.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 16, 2025 License: Apache-2.0 Imports: 33 Imported by: 0

Documentation

Index

Constants

View Source
const (
	WebSocketConnectionKey = "wsConnection"
	UserProfileKey         = "userProfile"
)

Context keys

View Source
const (
	// RequestIDKey is the key used to store the request ID in the gin context
	RequestIDKey = "request_id"
)
View Source
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

View Source
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 is returned if neither HS256 nor JWKS can be attempted.
	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")
)
View Source
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 ConnIsClosed(sc *SafeConn) bool

func ErrorHandler

func ErrorHandler() gin.HandlerFunc

func GetActiveConnectionCount

func GetActiveConnectionCount() int

func GetWSClient

func GetWSClient(sc *SafeConn) *ws.Client

GetWSClient returns a ws.Client for a given SafeConn

func IsWebSocket

func IsWebSocket(c *gin.Context) bool

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

func ValidateTokenWithoutAbort(validator Validator, token string) (string, error)

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 ErrorResponse struct {
	Type    string `json:"type"`
	Message string `json:"message"`
	Details string `json:"details,omitempty"`
	Code    string `json:"code,omitempty"` // For HTTP status code as string
}

type JWKSCache

type JWKSCache struct {
	// contains filtered or unexported fields
}

JWKSCache is a thread-safe cache for JWKS keys.

func GetJWKSCache

func GetJWKSCache(jwksURL, anonKey string, ttl time.Duration) *JWKSCache

GetJWKSCache initializes and returns a singleton instance of the JWKS cache. Configuration parameters (URL, Anon Key, TTL) must be provided on first call.

func (*JWKSCache) GetKey

func (c *JWKSCache) GetKey(kid string) (jwk.Key, error)

GetKey returns a key by its ID (kid), fetching/refreshing the JWKS if necessary.

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 NewSafeConn(conn *websocket.Conn, metrics *WSMetrics, config WSConfig) *SafeConn

func (*SafeConn) Close

func (sc *SafeConn) Close() error

Close safely closes the WebSocket connection and cleans up resources

func (*SafeConn) DoneChannel

func (sc *SafeConn) DoneChannel() <-chan struct{}

DoneChannel returns a channel that is closed when the connection is closed

func (*SafeConn) ReadChannel

func (sc *SafeConn) ReadChannel() <-chan []byte

ReadChannel returns the read channel for receiving WebSocket messages

func (*SafeConn) SendMessage

func (sc *SafeConn) SendMessage(message []byte) error

SendMessage sends a message through the websocket connection with proper error handling

func (*SafeConn) WriteControl

func (sc *SafeConn) WriteControl(messageType int, data []byte, deadline time.Time) error

func (*SafeConn) WriteMessage

func (sc *SafeConn) WriteMessage(messageType int, data []byte) error

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 Validator

type Validator interface {
	Validate(tokenString string) (string, error)
}

Validator defines the interface for validating tokens.

func NewJWTValidator

func NewJWTValidator(cfg *config.Config) (Validator, error)

NewJWTValidator creates a validator instance using application configuration.

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
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL