utils

package
v0.0.0-...-496a76a Latest Latest
Warning

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

Go to latest
Published: Jan 3, 2025 License: Apache-2.0 Imports: 29 Imported by: 0

Documentation

Index

Constants

View Source
const (
	JWTKey        = "jwt"
	JWTExpire     = "jwt_expire"
	JWTTimeOrigin = "jwt_origin"
)

Variables

View Source
var (
	// ErrMissingSecretKey indicates Secret key is required
	ErrMissingSecretKey = errors.New("filed to get secret key")

	// ErrFailedTokenCreation indicates JWT Token failed to create, reason unknown
	ErrFailedTokenCreation = errors.New("failed to create JWT Token")

	// ErrExpiredToken indicates JWT token has expired. Can't refresh.
	ErrExpiredToken = errors.New("failed to get valid token")

	// ErrEmptyAuthHeader can be thrown if authing with a HTTP header, the Auth header needs to be set
	ErrEmptyAuthHeader = errors.New("failed to get auth header")

	// ErrEmptyQueryToken can be thrown if authing with URL Query, the query token variable is empty
	ErrEmptyQueryToken = errors.New("failed to get query token")

	// ErrEmptyCookieToken can be thrown if authing with a cookie, the token cookie is empty
	ErrEmptyCookieToken = errors.New("failed to get cookie token")

	// ErrEmptyParamToken can be thrown if authing with parameter in path, the parameter in path is empty
	ErrEmptyParamToken = errors.New("failed to get parameter token")

	// ErrInvalidSigningAlgorithm indicates signing algorithm is invalid, needs to be HS256, HS384, HS512, RS256, RS384 or RS512
	ErrInvalidSigningAlgorithm = errors.New("failed to get get signing algorithm")

	// ErrNoPrivKeyFile indicates that the given private key is unreadable
	ErrNoPrivKeyFile = errors.New("failed to get private key file")

	// ErrNoPubKeyFile indicates that the given public key is unreadable
	ErrNoPubKeyFile = errors.New("failed to get public key file")

	// ErrInvalidPrivKey indicates that the given private key is invalid
	ErrInvalidPrivKey = errors.New("failed to get private key")

	// ErrInvalidPubKey indicates the the given public key is invalid
	ErrInvalidPubKey = errors.New("failed to get public key")
)
View Source
var ErrPrivateKeyMissing = errors.New("private key is missing")

Functions

func CreateMagicMessage

func CreateMagicMessage(message string) string

func DirExists

func DirExists(path string) bool

DirExists checks dir exists

func FileExists

func FileExists(path string) bool

FileExists checks file exists

func GenerateRandomString

func GenerateRandomString(length int) string

func LoadYAML

func LoadYAML(path string, out interface{}) error

LoadYAML config into out interface, with defaults and validates

func NewTLSConfigClient

func NewTLSConfigClient(c Certificate) (*tls.Config, error)

NewTLSConfigClient loads tls config for client

func NewTLSConfigClientWithPassphrase

func NewTLSConfigClientWithPassphrase(c Certificate) (*tls.Config, error)

NewTLSConfigClientWithPassphrase loads tls config for client with passphrase

func NewTLSConfigServer

func NewTLSConfigServer(c Certificate) (*tls.Config, error)

NewTLSConfigServer loads tls config for server

func ParseCompact

func ParseCompact(signature []byte) (*ecdsa.Signature, error)

func ParseEnv

func ParseEnv(data []byte) ([]byte, error)

ParseEnv parses env

func PathExists

func PathExists(path string) bool

PathExists checks path exists

func PrivateKeyFromString

func PrivateKeyFromString(privateKey string) (*bec.PrivateKey, error)

func SetDefaults

func SetDefaults(ptr interface{}) error

SetDefaults set default values

func SignMessage

func SignMessage(privateKey string, message string, sigRefCompressedKey bool) (string, string, error)

func SignMessageAlter

func SignMessageAlter(privateKey, msg string) ([]byte, []byte)

func UnmarshalJSON

func UnmarshalJSON(in []byte, out interface{}) error

UnmarshalJSON unmarshals, defaults and validates

func UnmarshalYAML

func UnmarshalYAML(in []byte, out interface{}) error

UnmarshalYAML unmarshals, defaults and validates

func VerifySignature

func VerifySignature(signatureEncoded []byte, publicKey *btcec.PublicKey, messageHash []byte) error

Types

type Certificate

type Certificate struct {
	CA                 string `yaml:"ca" json:"ca"`
	Key                string `yaml:"key" json:"key"`
	Cert               string `yaml:"cert" json:"cert"`
	Name               string `yaml:"name" json:"name"`
	Passphrase         string `yaml:"passphrase" json:"passphrase"`
	InsecureSkipVerify bool   `yaml:"insecureSkipVerify" json:"insecureSkipVerify"` // for client, for test purpose
	tls.ClientAuthType `yaml:"clientAuthType" json:"clientAuthType"`
}

Certificate certificate config for server Name : serverNameOverride, same to CommonName in server.pem if Name == "" , link would not verifies the server's certificate chain and host name AuthType : declares the policy the server will follow for TLS Client Authentication

type JWTConfig

type JWTConfig struct {
	SigningAlgorithm string        `yaml:"sa" json:"sa" default:"HS256"`
	Key              string        `yaml:"key" json:"key" default:"Fiamma.20241111"`
	PrivKeyFile      string        `yaml:"privKeyFile" json:"privKeyFile"`
	PubKeyFile       string        `yaml:"pubKeyFile" json:"pubKeyFile"`
	Timeout          time.Duration `yaml:"timeout" json:"timeout" default:"30m"`
	MaxRefresh       time.Duration `yaml:"maxRefresh" json:"maxRefresh" default:"1h"`
	TokenLookup      string        `yaml:"tokenLookup" json:"tokenLookup" default:"header: jwt, query: jwt, param: jwt, cookie: jwt"`
}

type JWTHelper

type JWTHelper struct {
	// Duration that a jwt token is valid. Optional, defaults to one hour.
	Timeout time.Duration
	// This field allows clients to refresh their token until MaxRefresh has passed.
	// Note that clients can refresh their token in the last moment of MaxRefresh.
	// This means that the maximum validity timespan for a token is TokenTime + MaxRefresh.
	// Optional, defaults to 0 meaning not refreshable.
	MaxRefresh time.Duration

	// TokenLookup is a string in the form of "<source>:<name>" that is used
	// to extract token from the request.
	// Optional. Default value "header:Authorization".
	// Possible values:
	// - "header:<name>"
	// - "query:<name>"
	// - "cookie:<name>"
	TokenLookup string

	// signing algorithm - possible values are HS256, HS384, HS512, RS256, RS384 or RS512
	// Optional, default is HS256.
	SigningAlgorithm string
	// Secret key used for signing. Required.
	Key []byte
	// Private key file for asymmetric algorithms
	PrivKeyFile string
	// Public key file for asymmetric algorithms
	PubKeyFile string
	// contains filtered or unexported fields
}

func NewJWTHelper

func NewJWTHelper(cfg JWTConfig) (*JWTHelper, error)

func (*JWTHelper) CheckExpireAndParse

func (j *JWTHelper) CheckExpireAndParse(c *gin.Context) (map[string]interface{}, error)

func (*JWTHelper) CheckMaxRefreshAndParse

func (j *JWTHelper) CheckMaxRefreshAndParse(c *gin.Context) (map[string]interface{}, error)

func (*JWTHelper) Generate

func (j *JWTHelper) Generate(claims map[string]interface{}) (token string, expire time.Time, err error)

func (*JWTHelper) GetTokenString

func (j *JWTHelper) GetTokenString(c *gin.Context) (string, error)

func (*JWTHelper) Refresh

func (j *JWTHelper) Refresh(c *gin.Context) (string, time.Time, error)

Jump to

Keyboard shortcuts

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