middleware

Imports

Imports #

"fmt"
"time"
"github.com/golang-jwt/jwt/v5"
"advent2024/web/config"
"advent2024/web/weberrors"
"context"
"errors"
"fmt"
"log"
"net/http"
"os"
"strings"
"text/template"
"time"
"github.com/google/uuid"
"golang.org/x/time/rate"
"encoding/json"
"errors"

Constants & Variables

ContextConfig const #

Context Keys

const ContextConfig contextKey = "config"

ContextKeyLogger const #

Context Keys

const ContextKeyLogger contextKey = "logger"

ContextKeyRequestID const #

Context Keys

const ContextKeyRequestID contextKey = "requestID"

ContextKeyTemplates const #

Context Keys

const ContextKeyTemplates contextKey = "uploadTemplate"

Type Aliases

contextKey type #

Context key type

type contextKey string

Interfaces

OAuthResponse interface #

Interface for OAuth Response

type OAuthResponse interface {
error
Token() (string, error)
IsError() bool
}

Structs

OAuthGithubError struct #

Error reply from Github

type OAuthGithubError struct {
Err string `json:"error"`
ErrDescription string `json:"error_description"`
ErrURI string `json:"error_uri"`
}

OAuthGithubOK struct #

Success reply from Github

type OAuthGithubOK struct {
AccessToken string `json:"access_token"`
Scope string `json:"scope"`
TokenType string `json:"token_type"`
}

OAuthGithubReply struct #

Combined reply from Github

type OAuthGithubReply struct {
Response *OAuthGithubOK
Err *OAuthGithubError
}

loggingResponseWriter struct #

Logger to capture status code and written bytes

type loggingResponseWriter struct {
http.ResponseWriter
statusCode int
bytesWritten int
}

Functions

AuthenticationMiddleware function #

Checks user authentication

func AuthenticationMiddleware() (func(http.Handler) http.Handler)

Chain function #

Chains Middlewares

func Chain(h http.Handler, mws ...func(http.Handler) http.Handler) http.Handler

Error method #

Error interface implementation for Error component of the Reply

func (e OAuthGithubError) Error() string

Error method #

Error interface implementation for Reply

func (r OAuthGithubReply) Error() string

GenerateJWT function #

Generates JWT token. Accepts provider name, token, secret to use for encoding and validity period. Returns string representation of the Token.

func GenerateJWT(provider string, jwtSecret []byte, validityPeriod time.Duration) (string, error)

GetConfig function #

Gets Configuration from context TODO: provide default configuration if missing? Similar to logger?

func GetConfig(r *http.Request) (*config.Config, bool)

GetLogger function #

Gets logger from context or provides a default one

func GetLogger(r *http.Request) *log.Logger

IsError method #

Checks if Response is Error

func (r OAuthGithubReply) IsError() bool

LoggingMiddleware function #

Logs return code, written bytes and duration of the request Generates unique request ID TODO: separate middleware with stat tracking? Logs are prefixed with timestamp and project name

func LoggingMiddleware(logger *log.Logger) (func(http.Handler) http.Handler)

NewLogger function #

Creates new longer based on the configuration TODO: add more options

func NewLogger(c *config.Config) *log.Logger

ParseToken function #

Parses JWT token

func ParseToken(tokenStr string, jwtSecret []byte) (*jwt.Token, error)

RateLimitMiddleware function #

Rate Limits the request to Handler

func RateLimitMiddleware(tokenRate int, burst int) (func(http.Handler) http.Handler)

RecoveryMiddleware function #

Recovers from panics within the Handler chain

func RecoveryMiddleware() (func(http.Handler) http.Handler)

Token method #

Returns token

func (r OAuthGithubReply) Token() (string, error)

TokenValid function #

Checks if token is valid

func TokenValid(token *jwt.Token) bool

UnmarshalJSON method #

Unmarshal GitHub Response. Checks if the response is error or success and populates correct field of the struct.

func (r *OAuthGithubReply) UnmarshalJSON(data []byte) error

WithConfig function #

Injects configuration to Handler chain

func WithConfig(cfg *config.Config) (func(http.Handler) http.Handler)

WithTemplate function #

Specifies templates to be used by the Handler

func WithTemplate(template *template.Template) (func(http.Handler) http.Handler)

Write method #

Writes the response and saves the amount of bytes

func (lrw *loggingResponseWriter) Write(b []byte) (int, error)

WriteHeader method #

Writes header and saves the code

func (lrw *loggingResponseWriter) WriteHeader(code int)

clientIP function #

Extracts client IP from the request X-Real-Ip header > X-Forwarded-For header > src IP of request

func clientIP(r *http.Request) string