cwbiechotoolkit

package module
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Jan 6, 2026 License: GPL-3.0 Imports: 24 Imported by: 0

README

CWBI Echo Toolkit

cwbi-echo-toolkit is a shared middleware module for Labstack Echo services in the USACE CWBI group. It provides reusable app key auth, JWT-based auth and resource access, DB transaction helpers with table-driven config, and S3-backed static file serving to standardize cross-service infrastructure.

Go Module Documentation

cwbiechotoolkit

import "github.com/usace/cwbi-echo-toolkit"

Index

Variables

var DefaultDatabaseTransaction = ResourceAccessConfig{
    Skipper: DefaultDatabaseSkipper,
}

var (
    DefaultJwtAuthenticateConfig = JwtAuthenticateConfig{
        Skipper: DefaultJwtAuthSkipper,
    }
)

var (
    DefaultResourceAccessConfig = ResourceAccessConfig{
        Skipper: DefaultResourceAcessSkipper,
    }
)

var (
    DefaultS3StaticConfig = S3StaticConfig{
        Skipper: DefaultSkipper,
        Index:   "index.html",
        Prefix:  "/",
    }
)

func DatabaseSetApplicationWithConfig

func DatabaseSetApplicationWithConfig(dbCfg DatabaseTransaction) echo.MiddlewareFunc

DatabaseSetApplicationWithConfig middleware with DatabaseTransation configuration setting DB configurations

func DatabaseTransactionWithConfig

func DatabaseTransactionWithConfig(dbCfg DatabaseTransaction) echo.MiddlewareFunc

DatabaseTransactionWithConfig middleware with DatabaseTransaction configuration determining DB state

func DefaultAppkeySkipper

func DefaultAppkeySkipper(c echo.Context) bool

DefaultAppkeySkipper function returns a boolean for the Appkey Skipper and the value is false.

func DefaultAppkeyValidator

func DefaultAppkeyValidator(appkey string) middleware.KeyAuthValidator

DefaultAppkeyValidator implements Echo middleware.KeyAuthValidator returning boolean and error

Parameters: appkey is the application key like "bearer abcdefghijklmnop123456789"

func DefaultAuthAppkeyConfig

func DefaultAuthAppkeyConfig(appkey string) middleware.KeyAuthConfig

DefaultAuthAppkeyConfig implements Echo middleware.KeyAuthConfig configuration with default values

func DefaultDatabaseSkipper

func DefaultDatabaseSkipper(echo.Context) bool

DefaultDatabaseSkipper returns false which processes the middleware.

func DefaultErrorHandler

func DefaultErrorHandler() middleware.KeyAuthErrorHandler

DefaultErrorHandler implements Echo middleware KeyAuthErrorHandler

func DefaultJwtAuthSkipper

func DefaultJwtAuthSkipper(echo.Context) bool

DefaultJwtAuthSkipper returns false which processes the middleware.

func DefaultResourceAcessSkipper

func DefaultResourceAcessSkipper(echo.Context) bool

DefaultResourceAcessSkipper returns false which processes the middleware.

func DefaultScopeFromContext

func DefaultScopeFromContext(c echo.Context, scopeVariable string) string

DefaultScopeFromContext returns the scope defined by the path parameter

Parameter: scopeVariable is a string, default "symbol" if string is ""

The scope is typically used here as a District office, therefore scopeVariable would be a path parameter 'symbol', 'office', 'code', etc. in the url path.

func DefaultSkipper

func DefaultSkipper(echo.Context) bool

DefaultSkipper returns false which processes the middleware.

func GetPublicKeyFromCwbiRealm

func GetPublicKeyFromCwbiRealm(url string) (string, error)

GetPublicKeyFromCwbiRealm gets the public_key from the KeyCloak CWBI Realm assuming the URL is one of the correct ./auth/realms/cwbi

Parameter: url is the URL as a string

Return: string, error

func GetRsaPublicKey

func GetRsaPublicKey(publicKey string) (*rsa.PublicKey, error)

GetRsaPublicKey jwt ParseRSAPublicKeyFromPEM returning rsa.PublicKey

Parameter: publicKey is the public as a string

func GetRsaPublicKeyFromCwbiRealm

func GetRsaPublicKeyFromCwbiRealm(url string) (*rsa.PublicKey, error)

GetRsaPublicKeyFromCwbiRealm gets the public_key from the KeyCloak CWBI Realm assuming the URL is one of the correct ./auth/realms/cwbi

Parameter: url is the URL as a string

Return: *rsa.PublicKey, error

func ResourceAccessWithConfig

func ResourceAccessWithConfig(accessConfig ResourceAccessConfig) echo.MiddlewareFunc

ResourceAccessWithConfig middleware with configuration getting user's role from JWT and checking against defined resource access and roles.

func S3Satic

func S3Satic(S3StaticConfig S3StaticConfig) echo.MiddlewareFunc

S3Satic middleware returning S3StaticWithConfig with Default configurations

func S3StaticWithConfig

func S3StaticWithConfig(staticConfig S3StaticConfig) echo.MiddlewareFunc

S3StaticWithConfig returns S3Static middleware with config See `S3Static()`

func StringArrayMatch

func StringArrayMatch(arr1 []string, arr2 []string) bool

StringArrayMatch checks string arrays for matching values

Return: true if array1 has value in array2 else false

func assignFieldValue

func assignFieldValue(p any, fieldName string, value any) error

assignFieldValue sets a value to the struct field

type AuthorizeCustomClaims

AuthorizeCustomClaims struct defining claims

type AuthorizeCustomClaims struct {
    AuthrorizedParty  string         `json:"azp,omitempty"`
    ResourceAccess    map[string]any `json:"resource_access,omitempty"`
    PreferredUsername string         `json:"preferred_username,omitempty"`
    Name              string         `json:"name,omitempty"`
    GivenName         string         `json:"given_name,omitempty"`
    FamilyName        string         `json:"family_name,omitempty"`
    Subject           string         `json:"sub,omitempty"`
    Audience          []string       `json:"aud,omitempty"`
    // jwt.StandardClaims  // this is for 'aud' that is a string
    jwt.MapClaims // start using this with custom claims
}

type DatabaseTransaction

DatabaseTransaction struct defining needed fields to validate and authorize.

type DatabaseTransaction struct {
    // Skipper defines a function to skip middleware.
    // Returning true skips processing the middleware.
    Skipper func(c echo.Context) bool

    // sql query
    SQL *string

    // Key used in the default query
    // required when SQL not provided
    Key *string

    // Config Application Configuration
    Config *any

    // ConfigFieldName Application Configuration attribute
    ConfigFieldName *string

    // Connection database connection pool
    Connection *pgxpool.Pool
}

type DbConfiguration

DbConfiguration define config for database table configuration.

type DbConfiguration struct {
    ID    uuid.UUID `db:"id" json:"id"`
    Key   string    `db:"key" json:"key"`
    Value string    `db:"value" json:"value"`
    Type  string    `db:"type" json:"type"`
}

type JwtAuthenticateConfig

JwtAuthenticateConfig struct defining configuration fields for validation and authorization

type JwtAuthenticateConfig struct {
    // Skipper defines a function to skip middleware
    // Returning true skips processing the middleware.
    Skipper func(c echo.Context) bool

    // ApplicationKey is the key to validate the application
    ApplicationKey string

    // PublicKeyRaw is the public key to validate the token
    PublicKeyRaw string

    // PublicKey is the public key to validate the token as rsa.PublicKey
    // This is typically set by the middleware
    PublicKey *rsa.PublicKey

    // TokenRoles is the role(s) from the token
    TokenRoles []any

    // SigningMethod is the signing method for the token algorithm
    // Determined from the token
    SigningMethod string
}

func (*JwtAuthenticateConfig) AuthParseWithClaims
func (a *JwtAuthenticateConfig) AuthParseWithClaims() echo.MiddlewareFunc

AuthParseWithClaims middleware with config parsing jwt with claims token lookup is "header:Authorization:Bearer "

type ResourceAccessConfig

ResourceAccessConfig struct defines fields for resources access configuration

type ResourceAccessConfig struct {
    // Skipper defines a function to skip middleware.
    // Returning true skips processing the middleware.
    Skipper func(c echo.Context) bool

    // Roles is the list of roles to authorize
    Roles []string

    // Role separator.
    // Optional.  Default value ""
    RoleSeparator string

    // Typically the office of the user defined in routes
    Scope string

    // Scope Variable
    // Optional.  Default value "symbol"
    ScopeVariable string

    // ScopeFromContext func to get the scope
    // Typically from the route and is most likely an office symbol
    ScopeFromContext func(c echo.Context, scopeVariable string) string

    // Context key.  Use this if jwtAuth sets something different than 'user'
    // Optional.  Default value "user"
    ContextKey string

    // Claims.
    Claims AuthorizeCustomClaims
}

type S3StaticConfig

S3StaticConfig define config for S3Static

type S3StaticConfig struct {
    // Skipper defines a function to skip middleware. Returning true skips processing
    // the middleware.
    Skipper func(c echo.Context) bool

    // Aws Configuration
    // Required.
    AwsConfig aws.Config

    // S3 bucket.
    // Required.
    Bucket string `yaml:"bucket"`

    // Allows you to enable the client to use path-style addressing, i.e.,
    // https://s3.amazonaws.com/BUCKET/KEY . By default, the S3 client will use virtual
    // hosted bucket addressing when possible( https://BUCKET.s3.amazonaws.com/KEY ).
    UsePathStyle bool

    // Prefix limits the response to keys that begin with the specified prefix.
    // Optional. Default value "/"
    Prefix string `yaml:"prefix"`

    // PrefixFunc is a function that returns the prefix to use for the request.
    PrefixFunc func(c echo.Context) string `yaml:"prefixfunc"`

    // IgnoreBase is a regexp to ignore
    // Optional.
    IgnoreBaseRegex string `yaml:"ignorebaseregex"`

    // Index file for serving content.
    // Optional. Default value "index.html".
    Index string `yaml:"index"`
}

func (*S3StaticConfig) IgnoreBase
func (s *S3StaticConfig) IgnoreBase(pin string) (pout string, err error)

IgnoreBase struct method returning a new path using IgnoreBaseRegex

Parameter: pin returns as a string

Generated by gomarkdoc

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DefaultDatabaseTransaction = ResourceAccessConfig{
	Skipper: DefaultDatabaseSkipper,
}
View Source
var (
	DefaultJwtAuthenticateConfig = JwtAuthenticateConfig{
		Skipper: DefaultJwtAuthSkipper,
	}
)
View Source
var (
	DefaultResourceAccessConfig = ResourceAccessConfig{
		Skipper: DefaultResourceAcessSkipper,
	}
)
View Source
var (
	DefaultS3StaticConfig = S3StaticConfig{
		Skipper: DefaultSkipper,
		Index:   "index.html",
		Prefix:  "/",
	}
)

Functions

func DatabaseSetApplicationWithConfig

func DatabaseSetApplicationWithConfig(dbCfg DatabaseTransaction) echo.MiddlewareFunc

DatabaseSetApplicationWithConfig middleware with DatabaseTransation configuration setting DB configurations

func DatabaseTransactionWithConfig

func DatabaseTransactionWithConfig(dbCfg DatabaseTransaction) echo.MiddlewareFunc

DatabaseTransactionWithConfig middleware with DatabaseTransaction configuration determining DB state

func DefaultAppkeySkipper

func DefaultAppkeySkipper(c echo.Context) bool

DefaultAppkeySkipper function returns a boolean for the Appkey Skipper and the value is false.

func DefaultAppkeyValidator

func DefaultAppkeyValidator(appkey string) middleware.KeyAuthValidator

DefaultAppkeyValidator implements Echo middleware.KeyAuthValidator returning boolean and error

Parameters: appkey is the application key like "bearer abcdefghijklmnop123456789"

func DefaultAuthAppkeyConfig

func DefaultAuthAppkeyConfig(appkey string) middleware.KeyAuthConfig

DefaultAuthAppkeyConfig implements Echo middleware.KeyAuthConfig configuration with default values

func DefaultDatabaseSkipper

func DefaultDatabaseSkipper(echo.Context) bool

DefaultDatabaseSkipper returns false which processes the middleware.

func DefaultErrorHandler

func DefaultErrorHandler() middleware.KeyAuthErrorHandler

DefaultErrorHandler implements Echo middleware KeyAuthErrorHandler

func DefaultJwtAuthSkipper

func DefaultJwtAuthSkipper(echo.Context) bool

DefaultJwtAuthSkipper returns false which processes the middleware.

func DefaultResourceAcessSkipper

func DefaultResourceAcessSkipper(echo.Context) bool

DefaultResourceAcessSkipper returns false which processes the middleware.

func DefaultScopeFromContext

func DefaultScopeFromContext(c echo.Context, scopeVariable string) string

DefaultScopeFromContext returns the scope defined by the path parameter

Parameter: scopeVariable is a string, default "symbol" if string is ""

The scope is typically used here as a District office, therefore scopeVariable would be a path parameter 'symbol', 'office', 'code', etc. in the url path.

func DefaultSkipper

func DefaultSkipper(echo.Context) bool

DefaultSkipper returns false which processes the middleware.

func GetPublicKeyFromCwbiRealm added in v1.0.1

func GetPublicKeyFromCwbiRealm(url string) (string, error)

GetPublicKeyFromCwbiRealm gets the public_key from the KeyCloak CWBI Realm assuming the URL is one of the correct ./auth/realms/cwbi

Parameter: url is the URL as a string

Return: string, error

func GetRsaPublicKey added in v1.0.1

func GetRsaPublicKey(publicKey string) (*rsa.PublicKey, error)

GetRsaPublicKey jwt ParseRSAPublicKeyFromPEM returning rsa.PublicKey

Parameter: publicKey is the public as a string

func GetRsaPublicKeyFromCwbiRealm added in v1.0.1

func GetRsaPublicKeyFromCwbiRealm(url string) (*rsa.PublicKey, error)

GetRsaPublicKeyFromCwbiRealm gets the public_key from the KeyCloak CWBI Realm assuming the URL is one of the correct ./auth/realms/cwbi

Parameter: url is the URL as a string

Return: *rsa.PublicKey, error

func ResourceAccessWithConfig

func ResourceAccessWithConfig(accessConfig ResourceAccessConfig) echo.MiddlewareFunc

ResourceAccessWithConfig middleware with configuration getting user's role from JWT and checking against defined resource access and roles.

func S3Satic

func S3Satic(S3StaticConfig S3StaticConfig) echo.MiddlewareFunc

S3Satic middleware returning S3StaticWithConfig with Default configurations

func S3StaticWithConfig

func S3StaticWithConfig(staticConfig S3StaticConfig) echo.MiddlewareFunc

S3StaticWithConfig returns S3Static middleware with config See `S3Static()`

func StringArrayMatch added in v1.0.1

func StringArrayMatch(arr1 []string, arr2 []string) bool

StringArrayMatch checks string arrays for matching values

Return: true if array1 has value in array2 else false

Types

type AuthorizeCustomClaims

type AuthorizeCustomClaims struct {
	AuthrorizedParty  string         `json:"azp,omitempty"`
	ResourceAccess    map[string]any `json:"resource_access,omitempty"`
	PreferredUsername string         `json:"preferred_username,omitempty"`
	Name              string         `json:"name,omitempty"`
	GivenName         string         `json:"given_name,omitempty"`
	FamilyName        string         `json:"family_name,omitempty"`
	Subject           string         `json:"sub,omitempty"`
	Audience          []string       `json:"aud,omitempty"`
	// jwt.StandardClaims  // this is for 'aud' that is a string
	jwt.MapClaims // start using this with custom claims
}

AuthorizeCustomClaims struct defining claims

type DatabaseTransaction

type DatabaseTransaction struct {
	// Skipper defines a function to skip middleware.
	// Returning true skips processing the middleware.
	Skipper func(c echo.Context) bool

	// sql query
	SQL *string

	// Key used in the default query
	// required when SQL not provided
	Key *string

	// Config Application Configuration
	Config *any

	// ConfigFieldName Application Configuration attribute
	ConfigFieldName *string

	// Connection database connection pool
	Connection *pgxpool.Pool
}

DatabaseTransaction struct defining needed fields to validate and authorize.

type DbConfiguration added in v1.0.2

type DbConfiguration struct {
	ID    uuid.UUID `db:"id" json:"id"`
	Key   string    `db:"key" json:"key"`
	Value string    `db:"value" json:"value"`
	Type  string    `db:"type" json:"type"`
}

DbConfiguration define config for database table configuration.

type JwtAuthenticateConfig

type JwtAuthenticateConfig struct {
	// Skipper defines a function to skip middleware
	// Returning true skips processing the middleware.
	Skipper func(c echo.Context) bool

	// ApplicationKey is the key to validate the application
	ApplicationKey string

	// PublicKeyRaw is the public key to validate the token
	PublicKeyRaw string

	// PublicKey is the public key to validate the token as rsa.PublicKey
	// This is typically set by the middleware
	PublicKey *rsa.PublicKey

	// TokenRoles is the role(s) from the token
	TokenRoles []any

	// SigningMethod is the signing method for the token algorithm
	// Determined from the token
	SigningMethod string
}

JwtAuthenticateConfig struct defining configuration fields for validation and authorization

func (*JwtAuthenticateConfig) AuthParseWithClaims

func (a *JwtAuthenticateConfig) AuthParseWithClaims() echo.MiddlewareFunc

AuthParseWithClaims middleware with config parsing jwt with claims token lookup is "header:Authorization:Bearer "

type ResourceAccessConfig

type ResourceAccessConfig struct {
	// Skipper defines a function to skip middleware.
	// Returning true skips processing the middleware.
	Skipper func(c echo.Context) bool

	// Roles is the list of roles to authorize
	Roles []string

	// Role separator.
	// Optional.  Default value ""
	RoleSeparator string

	// Typically the office of the user defined in routes
	Scope string

	// Scope Variable
	// Optional.  Default value "symbol"
	ScopeVariable string

	// ScopeFromContext func to get the scope
	// Typically from the route and is most likely an office symbol
	ScopeFromContext func(c echo.Context, scopeVariable string) string

	// Context key.  Use this if jwtAuth sets something different than 'user'
	// Optional.  Default value "user"
	ContextKey string

	// Claims.
	Claims AuthorizeCustomClaims
}

ResourceAccessConfig struct defines fields for resources access configuration

type S3StaticConfig

type S3StaticConfig struct {
	// Skipper defines a function to skip middleware. Returning true skips processing
	// the middleware.
	Skipper func(c echo.Context) bool

	// Aws Configuration
	// Required.
	AwsConfig aws.Config

	// S3 bucket.
	// Required.
	Bucket string `yaml:"bucket"`

	// Allows you to enable the client to use path-style addressing, i.e.,
	// https://s3.amazonaws.com/BUCKET/KEY . By default, the S3 client will use virtual
	// hosted bucket addressing when possible( https://BUCKET.s3.amazonaws.com/KEY ).
	UsePathStyle bool

	// Prefix limits the response to keys that begin with the specified prefix.
	// Optional. Default value "/"
	Prefix string `yaml:"prefix"`

	// PrefixFunc is a function that returns the prefix to use for the request.
	PrefixFunc func(c echo.Context) string `yaml:"prefixfunc"`

	// IgnoreBase is a regexp to ignore
	// Optional.
	IgnoreBaseRegex string `yaml:"ignorebaseregex"`

	// Index file for serving content.
	// Optional. Default value "index.html".
	Index string `yaml:"index"`
}

S3StaticConfig define config for S3Static

func (*S3StaticConfig) IgnoreBase

func (s *S3StaticConfig) IgnoreBase(pin string) (pout string, err error)

IgnoreBase struct method returning a new path using IgnoreBaseRegex

Parameter: pin returns as a string

Jump to

Keyboard shortcuts

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