helper

package
v0.5.2 Latest Latest
Warning

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

Go to latest
Published: Oct 16, 2025 License: MIT Imports: 42 Imported by: 0

Documentation

Overview

Package helper provides helper functions for channel registration validation

Package helper contains helper functions

Package helper provides helper functions for manager change validation

Package helper provides helper functions

Index

Constants

View Source
const (
	// APIKeyPrefix is the prefix for all API keys
	APIKeyPrefix = "cserv_"
	// APIKeyRandomBytes is the number of random bytes to generate (32 bytes = 256 bits)
	APIKeyRandomBytes = 32
)
View Source
const (
	// Channel scopes
	ScopeChannelsRead   = "channels:read"
	ScopeChannelsWrite  = "channels:write"
	ScopeChannelsDelete = "channels:delete"

	// User scopes
	ScopeUsersRead   = "users:read"
	ScopeUsersWrite  = "users:write"
	ScopeUsersDelete = "users:delete"

	// Registration scopes
	ScopeRegistrationsRead  = "registrations:read"
	ScopeRegistrationsWrite = "registrations:write"
)

Predefined API key scopes for resource:action based permissions

Variables

This section is empty.

Functions

func AllScopes added in v0.5.2

func AllScopes() []string

AllScopes returns all valid scopes

func CryptoRandomInt added in v0.1.0

func CryptoRandomInt(limit int64) (int64, error)

CryptoRandomInt returns a crypto random integer between 0 and limit, inclusive Copried from https://github.com/go-gitea/gitea/blob/main/modules/util/util.go#L59

func CryptoRandomString added in v0.1.0

func CryptoRandomString(length int64) (string, error)

CryptoRandomString generates a crypto random alphanumerical string, each byte is generated by [0,61] range Copied from https://github.com/go-gitea/gitea/blob/main/modules/util/util.go#L70

func DebugWithTrace added in v0.4.0

func DebugWithTrace(c echo.Context, msg string, args ...any)

DebugWithTrace logs a debug message with trace context.

func ErrorWithTrace added in v0.4.0

func ErrorWithTrace(c echo.Context, msg string, args ...any)

ErrorWithTrace logs an error message with trace context.

func ExtractAPIKey added in v0.5.2

func ExtractAPIKey(c echo.Context) string

ExtractAPIKey extracts the API key from the X-API-Key header

func GenerateAPIKey added in v0.5.2

func GenerateAPIKey() (string, error)

GenerateAPIKey generates a new API key with the standard prefix

func GenerateSecureToken added in v0.1.0

func GenerateSecureToken(length int) string

GenerateSecureToken generates a cryptographically secure random token

func GenerateTOTPQRCode added in v0.2.0

func GenerateTOTPQRCode(username, secret string) (string, error)

GenerateTOTPQRCode generates a QR code for TOTP setup with the UnderNET logo

func GetClaimsFromRefreshToken added in v0.0.4

func GetClaimsFromRefreshToken(refreshToken string) (jwt.MapClaims, error)

GetClaimsFromRefreshToken gets the claims from the refresh token

func GetEchoJWTConfig added in v0.0.4

func GetEchoJWTConfig() echojwt.Config

GetEchoJWTConfig returns the echo JWT config

func GetJWTPublicKey added in v0.0.4

func GetJWTPublicKey() interface{}

GetJWTPublicKey gets the JWT public key

func GetJWTRefreshSigningKey added in v0.0.4

func GetJWTRefreshSigningKey() interface{}

GetJWTRefreshSigningKey gets the JWT refresh signing key

func GetJWTSigningKey added in v0.0.4

func GetJWTSigningKey() interface{}

GetJWTSigningKey gets the JWT signing key

func GetRequestID added in v0.3.0

func GetRequestID(c echo.Context) string

GetRequestID extracts the request ID from the Echo context. Returns "unknown" if no request ID is found.

func GetRequestLogger added in v0.3.0

func GetRequestLogger(c echo.Context) *slog.Logger

GetRequestLogger returns a slog.Logger that automatically includes the request ID from the Echo context in all log entries. If no request ID is found, it uses "unknown".

func GetScopeDescription added in v0.5.2

func GetScopeDescription(scope string) string

GetScopeDescription returns the description for a given scope

func GetSpanID added in v0.4.0

func GetSpanID(c echo.Context) string

GetSpanID extracts the span ID from the Echo context. Returns empty string if no span ID is found.

func GetTraceID added in v0.4.0

func GetTraceID(c echo.Context) string

GetTraceID extracts the trace ID from the Echo context. Returns empty string if no trace ID is found.

func GetTraceLogger added in v0.4.0

func GetTraceLogger(c echo.Context) *slog.Logger

GetTraceLogger returns a slog.Logger that includes both request ID and trace context information (trace ID, span ID) for complete log correlation.

func HasAllRequiredScopes added in v0.5.2

func HasAllRequiredScopes(userScopes []string, requiredScopes []string) bool

HasAllRequiredScopes checks if userScopes contains all of the requiredScopes

func HasRequiredScope added in v0.5.2

func HasRequiredScope(userScopes []string, requiredScopes []string) bool

HasRequiredScope checks if userScopes contains at least one of the requiredScopes

func HashAPIKey added in v0.5.2

func HashAPIKey(key string) (string, error)

HashAPIKey hashes an API key using SHA-256 for database lookup Note: Since API keys are cryptographically random with high entropy, SHA-256 is sufficient and allows for efficient database lookups.

func InArray added in v0.0.6

func InArray(needle string, haystack []string) bool

func InfoWithTrace added in v0.4.0

func InfoWithTrace(c echo.Context, msg string, args ...any)

InfoWithTrace logs an info message with trace context.

func Int32ToNullableInt32 added in v0.5.2

func Int32ToNullableInt32(i int32) pgtype.Int4

Int32ToNullableInt32 converts int32 to pgtype.Int4

func IsEmailLocked added in v0.4.0

func IsEmailLocked(email string) bool

IsEmailLocked is a simple wrapper around the email validation logic This matches the PHP is_email_locked() function behavior

func IsIPAllowed added in v0.5.2

func IsIPAllowed(ipStr string, allowedCIDRs []string) (bool, error)

IsIPAllowed checks if an IP address is within any of the allowed CIDR ranges

func LogWithTrace added in v0.4.0

func LogWithTrace(c echo.Context, level slog.Level, msg string, args ...any)

LogWithTrace logs a message with automatic trace context correlation. This is a convenience function that creates a trace-aware logger and logs the message.

func NullableInt32ToInt32Ptr added in v0.5.2

func NullableInt32ToInt32Ptr(i pgtype.Int4) *int32

NullableInt32ToInt32Ptr converts pgtype.Int4 to *int32

func NullableTextToString added in v0.5.2

func NullableTextToString(t pgtype.Text) string

NullableTextToString converts pgtype.Text to string

func ParseIPRestrictions added in v0.5.2

func ParseIPRestrictions(data []byte) ([]string, error)

ParseIPRestrictions parses IP restrictions from JSON bytes

func SafeAtoi32 added in v0.0.8

func SafeAtoi32(s string) (int32, error)

SafeAtoi32 converts a string to int32 with bounds checking

func SafeInt32 added in v0.4.0

func SafeInt32(value int) int32

SafeInt32 safely converts int to int32 with bounds checking Returns 0 for overflow conditions, caller should validate the result

func SafeInt32FromInt64 added in v0.4.0

func SafeInt32FromInt64(value int64) int32

SafeInt32FromInt64 safely converts int64 to int32 with bounds checking Returns 0 for overflow conditions, caller should validate the result

func SafeInt64FromInt added in v0.4.0

func SafeInt64FromInt(value int) int64

SafeInt64FromInt safely converts int to int64 with bounds checking This is generally safe on most platforms but included for completeness

func SafeIntFromInt32 added in v0.4.0

func SafeIntFromInt32(value int32) int

SafeIntFromInt32 safely converts int32 to int This is generally safe as int is at least 32 bits on all supported platforms

func SafeIntFromInt64 added in v0.4.0

func SafeIntFromInt64(value int64) int

SafeIntFromInt64 safely converts int64 to int with bounds checking Returns 0 for overflow conditions on 32-bit platforms

func SerializeIPRestrictions added in v0.5.2

func SerializeIPRestrictions(cidrs []string) ([]byte, error)

SerializeIPRestrictions serializes IP restrictions to JSON bytes

func StrPtr2Str

func StrPtr2Str(str *string) string

func StringToNullableText added in v0.5.2

func StringToNullableText(s string) pgtype.Text

StringToNullableText converts a string to pgtype.Text

func ValidateAPIKey added in v0.5.2

func ValidateAPIKey(plain, hash string) bool

ValidateAPIKey compares a plain-text API key to a SHA-256 hash

func ValidateCIDR added in v0.5.2

func ValidateCIDR(cidr string) error

ValidateCIDR validates if a string is a valid CIDR notation

func ValidateCIDRList added in v0.5.2

func ValidateCIDRList(cidrs []string) error

ValidateCIDRList validates a list of CIDR notations

func ValidateScopes added in v0.5.2

func ValidateScopes(scopes []string) error

ValidateScopes checks if all provided scopes are valid

func WarnWithTrace added in v0.4.0

func WarnWithTrace(c echo.Context, msg string, args ...any)

WarnWithTrace logs a warning message with trace context.

Types

type APIKeyContext added in v0.5.2

type APIKeyContext struct {
	ID       int32    // API key ID from database
	Name     string   // API key name
	Scopes   []string // Permission scopes
	IsAPIKey bool     // Always true to identify as API key auth
}

APIKeyContext holds API key authentication context

func GetAPIKeyFromContext added in v0.5.2

func GetAPIKeyFromContext(c echo.Context) *APIKeyContext

GetAPIKeyFromContext extracts API key context from echo context

type AdminBypassInfo added in v0.4.0

type AdminBypassInfo struct {
	UserID      int32  `json:"user_id"`
	AdminLevel  int32  `json:"admin_level"`
	BypassType  string `json:"bypass_type"`
	Details     string `json:"details"`
	ChannelName string `json:"channel_name,omitempty"`
}

AdminBypassInfo contains information about admin bypass actions for audit logging

type ChannelRegistrationRequest added in v0.4.0

type ChannelRegistrationRequest struct {
	ChannelName string   `json:"channel_name" validate:"required,startswith=#,max=255"`
	Description string   `json:"description" validate:"required,max=300"`
	Supporters  []string `json:"supporters" validate:"required,min=1"`
}

ChannelRegistrationRequest represents the channel registration request structure This should match the struct in controllers/channel.go

type ChannelRegistrationValidator added in v0.4.0

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

ChannelRegistrationValidator provides validation for channel registration requests

func NewChannelRegistrationValidator added in v0.4.0

func NewChannelRegistrationValidator(db models.Querier, validator *Validator) *ChannelRegistrationValidator

NewChannelRegistrationValidator creates a new channel registration validator

func (*ChannelRegistrationValidator) ValidateChannelNameAvailability added in v0.4.0

func (v *ChannelRegistrationValidator) ValidateChannelNameAvailability(ctx context.Context, channelName string) error

ValidateChannelNameAvailability checks if the channel name is available

func (*ChannelRegistrationValidator) ValidateChannelNameAvailabilityWithAdminBypass added in v0.4.0

func (v *ChannelRegistrationValidator) ValidateChannelNameAvailabilityWithAdminBypass(
	ctx context.Context,
	channelName string,
	_ int32,
) ([]AdminBypassInfo, error)

ValidateChannelNameAvailabilityWithAdminBypass validates channel name availability (no admin bypass)

func (*ChannelRegistrationValidator) ValidateChannelRegistrationRequest added in v0.4.0

func (v *ChannelRegistrationValidator) ValidateChannelRegistrationRequest(
	ctx context.Context,
	req *ChannelRegistrationRequest,
	userID int32,
) error

ValidateChannelRegistrationRequest performs comprehensive validation of a channel registration request

func (*ChannelRegistrationValidator) ValidateChannelRegistrationWithAdminBypass added in v0.4.0

func (v *ChannelRegistrationValidator) ValidateChannelRegistrationWithAdminBypass(
	ctx context.Context,
	req *ChannelRegistrationRequest,
	userID int32,
	_ int32,
) ([]AdminBypassInfo, error)

ValidateChannelRegistrationWithAdminBypass performs comprehensive validation with admin bypass capabilities

func (*ChannelRegistrationValidator) ValidatePendingRegistrationsWithAdminBypass added in v0.4.0

func (v *ChannelRegistrationValidator) ValidatePendingRegistrationsWithAdminBypass(
	ctx context.Context,
	userID int32,
	adminLevel int32,
) ([]AdminBypassInfo, error)

ValidatePendingRegistrationsWithAdminBypass validates pending registrations with admin bypass

func (*ChannelRegistrationValidator) ValidateUserChannelLimits added in v0.4.0

func (v *ChannelRegistrationValidator) ValidateUserChannelLimits(ctx context.Context, userID int32) error

ValidateUserChannelLimits validates if the user can register another channel

func (*ChannelRegistrationValidator) ValidateUserChannelLimitsWithAdminBypass added in v0.4.0

func (v *ChannelRegistrationValidator) ValidateUserChannelLimitsWithAdminBypass(
	ctx context.Context,
	userID int32,
	adminLevel int32,
) ([]AdminBypassInfo, error)

ValidateUserChannelLimitsWithAdminBypass validates channel limits with admin bypass for multiple channels

func (*ChannelRegistrationValidator) ValidateUserIRCActivity added in v0.4.0

func (v *ChannelRegistrationValidator) ValidateUserIRCActivity(ctx context.Context, userID int32) error

ValidateUserIRCActivity validates if the user meets IRC activity requirements

func (*ChannelRegistrationValidator) ValidateUserIRCActivityWithAdminBypass added in v0.4.0

func (v *ChannelRegistrationValidator) ValidateUserIRCActivityWithAdminBypass(
	ctx context.Context,
	userID int32,
	_ int32,
) ([]AdminBypassInfo, error)

ValidateUserIRCActivityWithAdminBypass validates IRC activity requirements (no admin bypass)

func (*ChannelRegistrationValidator) ValidateUserNoregStatus added in v0.4.0

func (v *ChannelRegistrationValidator) ValidateUserNoregStatus(ctx context.Context, userID int32) error

ValidateUserNoregStatus checks if the user has NOREG restrictions

func (*ChannelRegistrationValidator) ValidateUserNoregStatusWithAdminBypass added in v0.4.0

func (v *ChannelRegistrationValidator) ValidateUserNoregStatusWithAdminBypass(
	ctx context.Context,
	userID int32,
	_ int32,
) ([]AdminBypassInfo, error)

ValidateUserNoregStatusWithAdminBypass validates user NOREG status (no admin bypass allowed)

type EmailLockValidator added in v0.4.0

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

EmailLockValidator handles email lock validation

func NewEmailLockValidator added in v0.4.0

func NewEmailLockValidator(db models.Querier) *EmailLockValidator

NewEmailLockValidator creates a new email lock validator

func (*EmailLockValidator) IsEmailLocked added in v0.4.0

func (v *EmailLockValidator) IsEmailLocked(_ context.Context, email string) (bool, error)

IsEmailLocked checks if an email address is locked for channel registration This matches the PHP is_email_locked($LOCK_REGPROC, $email) function

func (*EmailLockValidator) ValidateSupporterEmailLock added in v0.4.0

func (v *EmailLockValidator) ValidateSupporterEmailLock(ctx context.Context, supporterUsername string) error

ValidateSupporterEmailLock checks if a supporter's email is locked

func (*EmailLockValidator) ValidateSupporterEmailNotLocked added in v0.4.0

func (v *EmailLockValidator) ValidateSupporterEmailNotLocked(ctx context.Context, supporterUsername string) error

ValidateSupporterEmailNotLocked validates that a supporter's email is not locked

func (*EmailLockValidator) ValidateUserEmailLock added in v0.4.0

func (v *EmailLockValidator) ValidateUserEmailLock(ctx context.Context, userID int32) error

ValidateUserEmailLock checks if the user's email is locked

func (*EmailLockValidator) ValidateUserEmailNotLocked added in v0.4.0

func (v *EmailLockValidator) ValidateUserEmailNotLocked(ctx context.Context, userID int32) error

ValidateUserEmailNotLocked validates that a user's email is not locked

type JwtClaims

type JwtClaims struct {
	UserID      int32  `json:"user_id"`
	Username    string `json:"username"`
	RefreshUUID string `json:"refresh_uuid"` // If 2FA is enabled, this will be false until the user has authenticated with TOTPa
	Scope       string `json:"scope,omitempty"`
	Adm         int32  `json:"adm,omitempty"`
	jwt.RegisteredClaims
}

JwtClaims defines the default claims for JWT

func GetClaimsFromContext

func GetClaimsFromContext(c echo.Context) *JwtClaims

GetClaimsFromContext gets the JWT claims from the echo context

func (*JwtClaims) HasScope added in v0.0.6

func (c *JwtClaims) HasScope(scope string) bool

type ManagerChangeValidator added in v0.4.1

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

ManagerChangeValidator provides validation for manager change requests

func NewManagerChangeValidator added in v0.4.1

func NewManagerChangeValidator(db models.ServiceInterface) *ManagerChangeValidator

NewManagerChangeValidator creates a new manager change validator

func (*ManagerChangeValidator) ValidateManagerChangeBusinessRules added in v0.4.1

func (v *ManagerChangeValidator) ValidateManagerChangeBusinessRules(
	ctx context.Context,
	channelID int32,
	userID int32,
	newManagerUsername string,
	changeType string,
) error

ValidateManagerChangeBusinessRules performs comprehensive validation of a manager change request

type TokenDetails

type TokenDetails struct {
	AccessToken  string
	RefreshToken string
	RefreshUUID  string
	AtExpires    *jwt.NumericDate
	RtExpires    *jwt.NumericDate
}

TokenDetails defines the details of the tokens

func GenerateToken

func GenerateToken(claims *JwtClaims, t time.Time) (*TokenDetails, error)

GenerateToken generates a JWT token

type ValidationError added in v0.4.0

type ValidationError struct {
	Code    string      `json:"code"`
	Message string      `json:"message"`
	Details interface{} `json:"details,omitempty"`
}

ValidationError represents a validation error with structured details

func (*ValidationError) Error added in v0.4.0

func (v *ValidationError) Error() string

func (*ValidationError) GetCode added in v0.4.0

func (v *ValidationError) GetCode() string

GetCode returns the error code

func (*ValidationError) GetDetails added in v0.4.0

func (v *ValidationError) GetDetails() interface{}

GetDetails returns the error details

func (*ValidationError) GetMessage added in v0.4.0

func (v *ValidationError) GetMessage() string

GetMessage returns the error message

type Validator added in v0.0.2

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

Validator is a wrapper around the validator package

func NewValidator added in v0.0.2

func NewValidator() *Validator

NewValidator returns a new Validator

func (*Validator) Validate added in v0.0.2

func (v *Validator) Validate(i interface{}) error

Validate validates a struct based on the tags

Jump to

Keyboard shortcuts

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