util

package
v1.11.4 Latest Latest
Warning

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

Go to latest
Published: Dec 8, 2025 License: GPL-3.0 Imports: 30 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ApplyStringField added in v1.11.0

func ApplyStringField(src string, dest *string)

ApplyStringField updates the string pointer `dest` with the value of `src` if `src` is non-empty.

func ByteSize

func ByteSize(bytes uint64) string

ByteSize formats a given number of bytes into a human-readable string representation. If the number is less than 1024, it will be displayed in bytes (e.g., "256B"). Otherwise, the number will be converted into a larger unit (e.g., 1.5KB, 20MB, etc.).

func ComparePasswords

func ComparePasswords(hashPassword string, plainPassword string) (bool, error)

ComparePasswords takes a plain password and creates a hash. Then it compares the hashed passwords and returns true, if both passwords are equal. If an error occurs, the result is false for the compare operation and the error is returned. This function uses constant-time comparison to prevent timing attacks.

func DebugModule

func DebugModule(module definitions.DbgModule, keyvals ...any)

func EscapeLDAPFilter added in v1.10.0

func EscapeLDAPFilter(s string) string

EscapeLDAPFilter escapes a string for safe embedding into an LDAP filter per RFC 4515. It replaces the following characters:

\  -> \\5c
*  -> \\2a
(  -> \\28
)  -> \\29
NUL-> \\00

func FormatDurationMs added in v1.11.0

func FormatDurationMs(d time.Duration) string

FormatDurationMs formats a time.Duration as milliseconds with a fixed precision. The output is always in milliseconds using three fractional digits, e.g., "12.345ms". This ensures consistent latency units across logs regardless of the duration magnitude.

func GetCtxWithDeadlineLDAPModify added in v1.10.0

func GetCtxWithDeadlineLDAPModify() (context.Context, context.CancelFunc)

GetCtxWithDeadlineLDAPModify creates a context with a timeout for LDAP modify operations. Falls back to LDAPSearch timeout when LDAPModify is not configured.

func GetCtxWithDeadlineLDAPSearch added in v1.10.0

func GetCtxWithDeadlineLDAPSearch() (context.Context, context.CancelFunc)

GetCtxWithDeadlineLDAPSearch creates a context with a timeout for LDAP account searches. Parent context is the service context to avoid coupling to HTTP request lifetimes.

func GetCtxWithDeadlineRedisRead added in v1.10.0

func GetCtxWithDeadlineRedisRead(ctx context.Context) (context.Context, context.CancelFunc)

GetCtxWithDeadlineRedisRead creates a context with a timeout derived from the Redis read timeout configuration. If the provided context is nil, it initializes a new context using svcctx.Get(). When configuration is not loaded (e.g., in unit tests), it falls back to a sane default timeout. Returns the derived context and its corresponding cancel function.

func GetCtxWithDeadlineRedisWrite added in v1.10.0

func GetCtxWithDeadlineRedisWrite(ctx context.Context) (context.Context, context.CancelFunc)

GetCtxWithDeadlineRedisWrite creates a context with a timeout derived from the Redis write timeout configuration. If the provided context is nil, it initializes a new context using svcctx.Get(). When configuration is not loaded (e.g., in unit tests), it falls back to a sane default timeout. Returns the derived context and its corresponding cancel function.

func GetHash

func GetHash(value string) string

GetHash creates an SHA-256 hash of a plain text password and returns the first 128 bits.

func IsInNetwork added in v1.2.6

func IsInNetwork(networkList []string, guid, clientIP string) (matchIP bool)

IsInNetwork checks if an IP address is part of a list of networks. It iterates through the networkList and checks each network if it contains the given IP address. The function returns true if there is a match. The function logs any network errors encountered during the process. The function logs the information about checking a network for the given authentication object. The function logs the IP address of the client along with the IP address or network being checked.

func IsSoftWhitelisted added in v1.4.0

func IsSoftWhitelisted(username, clientIP, guid string, softWhitelist config.SoftWhitelist) bool

IsSoftWhitelisted checks whether a given clientIP is in the soft whitelist associated with a username. Returns true if the clientIP matches any networks in the soft whitelist, otherwise false.

func NewDNSResolver added in v1.1.3

func NewDNSResolver() (resolver *net.Resolver)

NewDNSResolver creates a new DNS resolver based on the configured settings.

func NewHTTPClient added in v1.3.0

func NewHTTPClient() *http.Client

NewHTTPClient creates and returns a new http.Client with a timeout of 60 seconds and custom TLS configurations.

func PreparePassword

func PreparePassword(password string) string

func ProcessXForwardedFor added in v1.2.7

func ProcessXForwardedFor(ctx *gin.Context, clientIP, clientPort *string, xssl *string)

ProcessXForwardedFor processes the X-Forwarded-For header in the given Gin context, extracting the forwarded address and updating the client IP and port accordingly. If the forwarded address is not empty, the function checks if the client IP is in the list of trusted proxies. If it is not, a warning message is logged and the function returns. If the client IP is in the list of trusted proxies, the function logs the matching of the client IP with the forwarded address and updates the client IP to the forwarded address. If the forwarded address contains multiple IP addresses separated by a comma, the first IP address is used as the client IP. The client port is set to "N/A".

func ProtoErrToFields

func ProtoErrToFields(err error) (fields []zap.Field)

func RemoveCRLFFromQueryOrFilter

func RemoveCRLFFromQueryOrFilter(value string, sep string) string

func ResolveIPAddress

func ResolveIPAddress(ctx context.Context, address string) (hostname string)

ResolveIPAddress returns the hostname for a given IP address.

func ValidateUsername

func ValidateUsername(username string) bool

ValidateUsername validates the given username against the usernamePattern regular expression. It takes a string username as input and returns a boolean value representing whether the username is valid or not. The usernamePattern regular expression allows any character except "(", ")", "{", SP, CTL, "%", "*", "\", except empty string. The function returns true if the username matches the pattern, and false otherwise.

func WithNotAvailable

func WithNotAvailable(value string) string

WithNotAvailable returns a default "not available" string if the given value is an empty string.

Types

type CryptPassword

type CryptPassword struct {
	definitions.Algorithm
	definitions.PasswordOption
	Password string
	Salt     []byte
}

CryptPassword is a container for an encrypted password typically used in SQL fields.

func (*CryptPassword) Generate

func (c *CryptPassword) Generate(plainPassword string, salt []byte, alg definitions.Algorithm, pwOption definitions.PasswordOption) (
	string, error,
)

Generate creates the encrypted form of a plain text password. It sets the Algorithm, PasswordOption, Salt, and Password fields of the CryptPassword struct and returns the generated password string.

func (*CryptPassword) GetParameters

func (c *CryptPassword) GetParameters(cryptedPassword string) (
	salt []byte, alg definitions.Algorithm, pwOption definitions.PasswordOption, err error,
)

GetParameters splits an encoded password into its components. It extracts the salt, algorithm, and password option from the crypted password and sets the corresponding fields in the CryptPassword struct.

type MacroSource

type MacroSource struct {
	Username    string
	XLocalIP    string
	XPort       string
	ClientIP    string
	XClientPort string
	TOTPSecret  string
	Protocol    config.Protocol
}

MacroSource holds all values that might be used in macros.

func (*MacroSource) ReplaceMacros

func (m *MacroSource) ReplaceMacros(source string) (dest string)

ReplaceMacros replaces several macros with values found in the Authentication object.

%Modifiers{long variables}

Modifiers: (Optional): L - Lower U - Upper

R - Reverse the string T - Trim the string

Long variavles: user - full username, i.e. localpart@domain.tld username - the local part of {user}, if user has a domain part, else user and username are the same domain - the domain part of {user}. Empty string, if {user} did not contain a domain part service - The service name, i.e. imap, pop3, lmtp local_ip - local IP address local_port - local port remote_ip - remote client IP address remote_port - remote client port.

type RedisLogger

type RedisLogger struct{}

RedisLogger implements the interface redis.Logging

func (*RedisLogger) Printf

func (r *RedisLogger) Printf(_ context.Context, format string, values ...any)

Printf implements the printf function from Redis.

Jump to

Keyboard shortcuts

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