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
- func AllScopes() []string
- func CryptoRandomInt(limit int64) (int64, error)
- func CryptoRandomString(length int64) (string, error)
- func DebugWithTrace(c echo.Context, msg string, args ...any)
- func ErrorWithTrace(c echo.Context, msg string, args ...any)
- func ExtractAPIKey(c echo.Context) string
- func GenerateAPIKey() (string, error)
- func GenerateSecureToken(length int) string
- func GenerateTOTPQRCode(username, secret string) (string, error)
- func GetClaimsFromRefreshToken(refreshToken string) (jwt.MapClaims, error)
- func GetEchoJWTConfig() echojwt.Config
- func GetJWTPublicKey() interface{}
- func GetJWTRefreshSigningKey() interface{}
- func GetJWTSigningKey() interface{}
- func GetRequestID(c echo.Context) string
- func GetRequestLogger(c echo.Context) *slog.Logger
- func GetScopeDescription(scope string) string
- func GetSpanID(c echo.Context) string
- func GetTraceID(c echo.Context) string
- func GetTraceLogger(c echo.Context) *slog.Logger
- func HasAllRequiredScopes(userScopes []string, requiredScopes []string) bool
- func HasRequiredScope(userScopes []string, requiredScopes []string) bool
- func HashAPIKey(key string) (string, error)
- func InArray(needle string, haystack []string) bool
- func InfoWithTrace(c echo.Context, msg string, args ...any)
- func Int32ToNullableInt32(i int32) pgtype.Int4
- func IsEmailLocked(email string) bool
- func IsIPAllowed(ipStr string, allowedCIDRs []string) (bool, error)
- func LogWithTrace(c echo.Context, level slog.Level, msg string, args ...any)
- func NullableInt32ToInt32Ptr(i pgtype.Int4) *int32
- func NullableTextToString(t pgtype.Text) string
- func ParseIPRestrictions(data []byte) ([]string, error)
- func SafeAtoi32(s string) (int32, error)
- func SafeInt32(value int) int32
- func SafeInt32FromInt64(value int64) int32
- func SafeInt64FromInt(value int) int64
- func SafeIntFromInt32(value int32) int
- func SafeIntFromInt64(value int64) int
- func SerializeIPRestrictions(cidrs []string) ([]byte, error)
- func StrPtr2Str(str *string) string
- func StringToNullableText(s string) pgtype.Text
- func ValidateAPIKey(plain, hash string) bool
- func ValidateCIDR(cidr string) error
- func ValidateCIDRList(cidrs []string) error
- func ValidateScopes(scopes []string) error
- func WarnWithTrace(c echo.Context, msg string, args ...any)
- type APIKeyContext
- type AdminBypassInfo
- type ChannelRegistrationRequest
- type ChannelRegistrationValidator
- func (v *ChannelRegistrationValidator) ValidateChannelNameAvailability(ctx context.Context, channelName string) error
- func (v *ChannelRegistrationValidator) ValidateChannelNameAvailabilityWithAdminBypass(ctx context.Context, channelName string, _ int32) ([]AdminBypassInfo, error)
- func (v *ChannelRegistrationValidator) ValidateChannelRegistrationRequest(ctx context.Context, req *ChannelRegistrationRequest, userID int32) error
- func (v *ChannelRegistrationValidator) ValidateChannelRegistrationWithAdminBypass(ctx context.Context, req *ChannelRegistrationRequest, userID int32, _ int32) ([]AdminBypassInfo, error)
- func (v *ChannelRegistrationValidator) ValidatePendingRegistrationsWithAdminBypass(ctx context.Context, userID int32, adminLevel int32) ([]AdminBypassInfo, error)
- func (v *ChannelRegistrationValidator) ValidateUserChannelLimits(ctx context.Context, userID int32) error
- func (v *ChannelRegistrationValidator) ValidateUserChannelLimitsWithAdminBypass(ctx context.Context, userID int32, adminLevel int32) ([]AdminBypassInfo, error)
- func (v *ChannelRegistrationValidator) ValidateUserIRCActivity(ctx context.Context, userID int32) error
- func (v *ChannelRegistrationValidator) ValidateUserIRCActivityWithAdminBypass(ctx context.Context, userID int32, _ int32) ([]AdminBypassInfo, error)
- func (v *ChannelRegistrationValidator) ValidateUserNoregStatus(ctx context.Context, userID int32) error
- func (v *ChannelRegistrationValidator) ValidateUserNoregStatusWithAdminBypass(ctx context.Context, userID int32, _ int32) ([]AdminBypassInfo, error)
- type EmailLockValidator
- func (v *EmailLockValidator) IsEmailLocked(_ context.Context, email string) (bool, error)
- func (v *EmailLockValidator) ValidateSupporterEmailLock(ctx context.Context, supporterUsername string) error
- func (v *EmailLockValidator) ValidateSupporterEmailNotLocked(ctx context.Context, supporterUsername string) error
- func (v *EmailLockValidator) ValidateUserEmailLock(ctx context.Context, userID int32) error
- func (v *EmailLockValidator) ValidateUserEmailNotLocked(ctx context.Context, userID int32) error
- type JwtClaims
- type ManagerChangeValidator
- type TokenDetails
- type ValidationError
- type Validator
Constants ¶
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 )
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 CryptoRandomInt ¶ added in v0.1.0
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
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
DebugWithTrace logs a debug message with trace context.
func ErrorWithTrace ¶ added in v0.4.0
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
GenerateAPIKey generates a new API key with the standard prefix
func GenerateSecureToken ¶ added in v0.1.0
GenerateSecureToken generates a cryptographically secure random token
func GenerateTOTPQRCode ¶ added in v0.2.0
GenerateTOTPQRCode generates a QR code for TOTP setup with the UnderNET logo
func GetClaimsFromRefreshToken ¶ added in v0.0.4
GetClaimsFromRefreshToken gets the claims from the refresh token
func GetEchoJWTConfig ¶ added in v0.0.4
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
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
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
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
HasAllRequiredScopes checks if userScopes contains all of the requiredScopes
func HasRequiredScope ¶ added in v0.5.2
HasRequiredScope checks if userScopes contains at least one of the requiredScopes
func HashAPIKey ¶ added in v0.5.2
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 InfoWithTrace ¶ added in v0.4.0
InfoWithTrace logs an info message with trace context.
func Int32ToNullableInt32 ¶ added in v0.5.2
Int32ToNullableInt32 converts int32 to pgtype.Int4
func IsEmailLocked ¶ added in v0.4.0
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
IsIPAllowed checks if an IP address is within any of the allowed CIDR ranges
func LogWithTrace ¶ added in v0.4.0
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
NullableInt32ToInt32Ptr converts pgtype.Int4 to *int32
func NullableTextToString ¶ added in v0.5.2
NullableTextToString converts pgtype.Text to string
func ParseIPRestrictions ¶ added in v0.5.2
ParseIPRestrictions parses IP restrictions from JSON bytes
func SafeAtoi32 ¶ added in v0.0.8
SafeAtoi32 converts a string to int32 with bounds checking
func SafeInt32 ¶ added in v0.4.0
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
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
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
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
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
SerializeIPRestrictions serializes IP restrictions to JSON bytes
func StrPtr2Str ¶
func StringToNullableText ¶ added in v0.5.2
StringToNullableText converts a string to pgtype.Text
func ValidateAPIKey ¶ added in v0.5.2
ValidateAPIKey compares a plain-text API key to a SHA-256 hash
func ValidateCIDR ¶ added in v0.5.2
ValidateCIDR validates if a string is a valid CIDR notation
func ValidateCIDRList ¶ added in v0.5.2
ValidateCIDRList validates a list of CIDR notations
func ValidateScopes ¶ added in v0.5.2
ValidateScopes checks if all provided scopes are valid
func WarnWithTrace ¶ added in v0.4.0
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
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
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