controllers

package
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Feb 14, 2026 License: MIT Imports: 47 Imported by: 0

Documentation

Overview

Package controllers provides the controllers for the API

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AssertJSONResponse added in v0.3.0

func AssertJSONResponse(t *testing.T, recorder *httptest.ResponseRecorder, expectedStatus int, expectedData interface{})

AssertJSONResponse asserts the JSON response matches expected data

func BenchmarkEndpoint added in v0.3.0

func BenchmarkEndpoint(b *testing.B, setup func() (*TestServer, *http.Request))

BenchmarkEndpoint provides a standardized way to benchmark endpoints

func CreateMaliciousPayloads added in v0.3.0

func CreateMaliciousPayloads() []string

CreateMaliciousPayloads returns common malicious input payloads for security testing

func GenerateRandomString added in v0.3.0

func GenerateRandomString(length int) string

GenerateRandomString generates a random string of specified length

Types

type APITestHelper added in v0.3.0

type APITestHelper struct {
	Server  *TestServer
	Client  *http.Client
	BaseURL string
	Headers map[string]string
}

APITestHelper provides utilities for API endpoint testing

func NewAPITestHelper added in v0.3.0

func NewAPITestHelper(t *testing.T) *APITestHelper

NewAPITestHelper creates a new API test helper

func (*APITestHelper) AssertErrorResponse added in v0.3.0

func (h *APITestHelper) AssertErrorResponse(t *testing.T, recorder *httptest.ResponseRecorder, expectedStatus int, expectedMessage string)

AssertErrorResponse asserts that a response contains an error with expected status and message

func (*APITestHelper) MakeRequest added in v0.3.0

func (h *APITestHelper) MakeRequest(method, path string, body interface{}) (*httptest.ResponseRecorder, error)

MakeRequest makes an HTTP request with common test setup

func (*APITestHelper) SetAuthToken added in v0.3.0

func (h *APITestHelper) SetAuthToken(token string)

SetAuthToken sets the authorization token for subsequent requests

type ActivateTOTPRequest added in v0.2.0

type ActivateTOTPRequest struct {
	OTPCode string `json:"otp_code" validate:"required,len=6,numeric" extensions:"x-order=0"`
}

ActivateTOTPRequest defines the request payload for 2FA activation

type AddMemberRequest added in v0.3.0

type AddMemberRequest struct {
	UserID      int64 `json:"user_id"      validate:"required"`
	AccessLevel int   `json:"access_level" validate:"required,min=1,max=499"`
}

AddMemberRequest represents the request body for adding a member to a channel

type AddMemberResponse added in v0.3.0

type AddMemberResponse struct {
	ChannelID   int32  `json:"channel_id"`
	UserID      int64  `json:"user_id"`
	AccessLevel int    `json:"access_level"`
	AddedAt     int32  `json:"added_at"`
	Message     string `json:"message"`
}

AddMemberResponse represents the response for adding a member to a channel

type AttackVector added in v0.3.0

type AttackVector struct {
	Name        string
	Payload     string
	Method      string
	Endpoint    string
	Description string
	Expected    SecurityExpectation
}

AttackVector represents a security attack scenario

type AuthenticationController

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

AuthenticationController is the controller for the authentication routes

func NewAuthenticationController

func NewAuthenticationController(
	s models.Querier,
	rdb *redis.Client,
	t func() time.Time,
) *AuthenticationController

NewAuthenticationController returns a new AuthenticationController

func (*AuthenticationController) Login

Login godoc @Summary Login @Description Authenticates a user and returns an authentication token, which can be a JWT token or a state token. @Description If the user has enabled multi-factor authentication (MFA), a state token will be returned instead of a JWT token. @Description The state token is used in conjunction with the OTP (one-time password) to retrieve the actual JWT token. @Description To obtain the JWT token, the state token and OTP must be sent to the `/authn/verify_factor` endpoint. @Tags auth @Accept json @Produce json @Param data body loginRequest true "Login request" @Success 200 {object} LoginResponse @Failure 401 {object} errors.ErrorResponse "Invalid username or password" @Router /login [post]

func (*AuthenticationController) Logout

func (ctr *AuthenticationController) Logout(c echo.Context) error

Logout godoc @Summary Logout @Description Logs out the user by deleting the refresh token from the database. If `{logout_all: true}` is posted, @Description all refresh tokens for the user will be deleted, invalidating all refresh tokens. @Tags auth @Accept json @Produce json @Param data body logoutRequest true "Logout request" @Success 200 {string} string "Logged out" @Failure 401 {object} errors.ErrorResponse "Unauthorized" @Security JWTBearerToken @Router /logout [post]

func (*AuthenticationController) RefreshToken

func (ctr *AuthenticationController) RefreshToken(c echo.Context) error

RefreshToken godoc @Summary Refresh JWT token @Description Refreshes the JWT token using the refresh token stored in the client's cookie. @Tags auth @Accept json @Produce json @Success 200 {object} LoginResponse @Failure 400 {object} errors.ErrorResponse "Bad request" @Failure 401 {object} errors.ErrorResponse "Unauthorized" @Router /authn/refresh [post]

func (*AuthenticationController) RequestPasswordReset added in v0.3.0

func (ctr *AuthenticationController) RequestPasswordReset(c echo.Context) error

RequestPasswordReset godoc @Summary Request Password Reset @Description Initiates a password reset process by sending a reset link to the user's email address. @Description This endpoint always returns 200 OK regardless of whether the email exists to prevent email enumeration attacks. @Description If the email exists in the system, a password reset email will be sent. @Tags auth @Accept json @Produce json @Param data body passwordResetRequest true "Password reset request" @Success 200 {object} passwordResetResponse @Failure 400 {object} errors.ErrorResponse "Bad request" @Failure 500 {object} errors.ErrorResponse "Internal server error" @Router /forgot-password [post]

func (*AuthenticationController) ResetPassword added in v0.3.0

func (ctr *AuthenticationController) ResetPassword(c echo.Context) error

ResetPassword godoc @Summary Reset Password @Description Resets a user's password using a valid password reset token received via email. @Description The token must be valid, not expired, and not previously used. @Tags auth @Accept json @Produce json @Param data body resetPasswordRequest true "Password reset data" @Success 200 {object} resetPasswordResponse @Failure 400 {object} errors.ErrorResponse "Bad request" @Failure 401 {object} errors.ErrorResponse "Invalid or expired token" @Failure 500 {object} errors.ErrorResponse "Internal server error" @Router /reset-password [post]

func (*AuthenticationController) VerifyFactor added in v0.0.2

func (ctr *AuthenticationController) VerifyFactor(c echo.Context) error

VerifyFactor is used to verify the user factor (OTP) @Summary Verify MFA factor @Description Verifies the user's MFA factor and returns a JWT token if successful. @Description Accepts either a 6-digit TOTP code or a backup code (format: abcde-12345). @Description The state token, returned from `/login` if the user has TOTP enabled, is used in conjunction with @Description the OTP (TOTP code or backup code) to retrieve the actual JWT token. @Description When a backup code is used, it is automatically consumed and cannot be reused. @Tags auth @Accept json @Produce json @Param data body factorRequest true "State token and OTP" @Success 200 {object} LoginResponse @Failure 400 {object} errors.ErrorResponse "Bad request" @Failure 401 {object} errors.ErrorResponse "Unauthorized" @Router /authn/factor_verify [post]

type ChangePasswordRequest added in v0.2.0

type ChangePasswordRequest struct {
	CurrentPassword string `json:"current_password" validate:"required,max=72"              extensions:"x-order=0"`
	NewPassword     string `json:"new_password"     validate:"required,min=10,max=72"       extensions:"x-order=1"`
	ConfirmPassword string `json:"confirm_password" validate:"required,eqfield=NewPassword" extensions:"x-order=2"`
}

ChangePasswordRequest defines the request payload for changing password

type ChannelController

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

func (*ChannelController) AddChannelMember added in v0.3.0

func (ctr *ChannelController) AddChannelMember(c echo.Context) error

AddChannelMember handles adding a new member to a channel @Summary Add a member to a channel @Description Add a new member to a channel with specified access level and proper validation @Tags channels @Accept json @Produce json @Param id path int true "Channel ID" @Param request body AddMemberRequest true "Member addition request" @Success 201 {object} AddMemberResponse @Failure 400 {string} string "Invalid request data" @Failure 401 {string} string "Authorization information is missing or invalid" @Failure 403 {string} string "Insufficient permissions" @Failure 404 {string} string "Channel or user not found" @Failure 409 {string} string "User is already a member of this channel" @Failure 422 {string} string "Cannot add user with access level higher than or equal to your own" @Failure 500 {string} string "Internal server error" @Router /channels/{id}/members [post] @Security JWTBearerToken

func (*ChannelController) ConfirmManagerChange added in v0.4.1

func (ctr *ChannelController) ConfirmManagerChange(c echo.Context) error

ConfirmManagerChange handles manager change confirmation via email token @Summary Confirm a manager change request @Description Confirm a manager change request using the token from the confirmation email @Tags channels @Accept json @Produce json @Param id path int true "Channel ID" @Param token query string true "Confirmation token from email" @Success 200 {object} ManagerChangeConfirmationResponse @Failure 400 {object} errors.ErrorResponse "Invalid or expired token" @Failure 404 {object} errors.ErrorResponse "Channel or token not found" @Router /channels/{id}/manager-confirm [get]

func (*ChannelController) GetChannel

func (ctr *ChannelController) GetChannel()

func (*ChannelController) GetChannelSettings added in v0.3.0

func (ctr *ChannelController) GetChannelSettings(c echo.Context) error

GetChannelSettings handles retrieving channel settings @Summary Get channel settings @Description Retrieve current channel settings including all configurable options. Requires minimum access level 100 on the channel. @Tags channels @Accept json @Produce json @Param id path int true "Channel ID" @Success 200 {object} channel.GetChannelSettingsResponse @Failure 400 {object} errors.ErrorResponse "Invalid channel ID" @Failure 401 {object} errors.ErrorResponse "Authorization information is missing or invalid" @Failure 403 {object} errors.ErrorResponse "Insufficient permissions to view channel" @Failure 404 {object} errors.ErrorResponse "Channel not found" @Failure 500 {object} errors.ErrorResponse "Internal server error" @Router /channels/{id} [get] @Security JWTBearerToken

func (*ChannelController) GetManagerChangeStatus added in v0.4.1

func (ctr *ChannelController) GetManagerChangeStatus(c echo.Context) error

GetManagerChangeStatus handles checking the status of pending manager change requests @Summary Get manager change request status @Description Check the status of pending manager change requests for a channel @Tags channels @Accept json @Produce json @Param id path int true "Channel ID" @Success 200 {object} ManagerChangeStatusResponse @Failure 400 {string} string "Invalid channel ID" @Failure 401 {string} string "Authorization information is missing or invalid" @Failure 403 {string} string "Insufficient permissions to view status" @Failure 404 {string} string "No pending requests found" @Failure 500 {string} string "Internal server error" @Router /channels/{id}/manager-change-status [get] @Security JWTBearerToken

func (*ChannelController) PatchChannelSettings added in v0.6.0

func (ctr *ChannelController) PatchChannelSettings(c echo.Context) error

PatchChannelSettings handles partial channel settings update requests @Summary Partially update channel settings @Description Update only the provided channel settings. Fields not included in the request remain unchanged. Requires access level 500 to modify level 500 settings (autojoin, massdeoppro, noop, strictop) and level 450 for remaining settings. @Tags channels @Accept json @Produce json @Param id path int true "Channel ID" @Param settings body channel.PartialSettingsRequest true "Partial channel settings to update" @Success 200 {object} channel.UpdateChannelSettingsResponse @Failure 400 {object} errors.ErrorResponse "Invalid request data" @Failure 401 {object} errors.ErrorResponse "Authorization information is missing or invalid" @Failure 403 {object} errors.ErrorResponse "Insufficient permissions - includes denied_settings in details when specific settings are denied" @Failure 404 {object} errors.ErrorResponse "Channel not found" @Failure 500 {object} errors.ErrorResponse "Internal server error" @Router /channels/{id} [patch] @Security JWTBearerToken

func (*ChannelController) RegisterChannel added in v0.4.0

func (ctr *ChannelController) RegisterChannel(c echo.Context) error

RegisterChannel handles channel registration requests @Summary Submit a channel registration application @Description Submit a new IRC channel registration application with validation and business rule enforcement @Tags channels @Accept json @Produce json @Param request body ChannelRegistrationRequest true "Channel registration request" @Success 201 {object} ChannelRegistrationResponse @Failure 400 {object} errors.ErrorResponse "Invalid request data" @Failure 401 {object} errors.ErrorResponse "Authorization information is missing or invalid" @Failure 403 {object} errors.ErrorResponse "User is restricted from registering channels" @Failure 409 {object} errors.ErrorResponse "Channel name already exists or user has pending registration" @Failure 422 {object} errors.ErrorResponse "Validation failed" @Failure 429 {object} errors.ErrorResponse "Cooldown period active" @Failure 500 {object} errors.ErrorResponse "Internal server error" @Router /channels [post] @Security JWTBearerToken

func (*ChannelController) RemoveChannelMember added in v0.3.0

func (ctr *ChannelController) RemoveChannelMember(c echo.Context) error

RemoveChannelMember handles removing a member from a channel @Summary Remove a member from a channel @Description Remove a member from a channel with proper validation and access control @Tags channels @Accept json @Produce json @Param id path int true "Channel ID" @Param request body RemoveMemberRequest true "Member removal request" @Success 200 {object} RemoveMemberResponse @Failure 400 {string} string "Invalid request data" @Failure 401 {string} string "Authorization information is missing or invalid" @Failure 403 {string} string "Insufficient permissions" @Failure 404 {string} string "Channel or user not found" @Failure 409 {string} string "Cannot remove the last channel owner" @Failure 422 {string} string "Cannot remove user with access level higher than or equal to your own" @Failure 500 {string} string "Internal server error" @Router /channels/{id}/members [delete] @Security JWTBearerToken

func (*ChannelController) RequestManagerChange added in v0.4.1

func (ctr *ChannelController) RequestManagerChange(c echo.Context) error

RequestManagerChange handles manager change requests for channels @Summary Submit a manager change request @Description Submit a request to change channel management (temporary or permanent) @Tags channels @Accept json @Produce json @Param id path int true "Channel ID" @Param request body ManagerChangeRequest true "Manager change request data" @Success 201 {object} ManagerChangeResponse @Failure 400 {string} string "Invalid request data or validation failure" @Failure 401 {string} string "Authorization information is missing or invalid" @Failure 403 {string} string "Insufficient permissions or business rule violation" @Failure 409 {string} string "Conflicting pending request exists" @Failure 429 {string} string "User in cooldown period" @Failure 500 {string} string "Internal server error" @Router /channels/{id}/manager-change [post] @Security JWTBearerToken

func (*ChannelController) SearchChannels added in v0.3.0

func (ctr *ChannelController) SearchChannels(c echo.Context) error

SearchChannels handles channel search requests with wildcard support and pagination @Summary Search channels by name @Description Search for channels using wildcard patterns with pagination support @Tags channels @Accept json @Produce json @Param q query string true "Search query (supports wildcards)" @Param limit query int false "Maximum number of results (default: 20, max: 100)" @Param offset query int false "Number of results to skip (default: 0)" @Success 200 {object} SearchChannelsResponse @Failure 400 {string} string "Invalid query parameters" @Failure 401 {string} string "Authorization information is missing or invalid" @Failure 500 {string} string "Internal server error" @Router /channels/search [get] @Security JWTBearerToken

func (*ChannelController) UpdateChannelSettings added in v0.3.0

func (ctr *ChannelController) UpdateChannelSettings(c echo.Context) error

UpdateChannelSettings handles channel settings update requests (full replacement) @Summary Update all channel settings @Description Replace all channel settings with new values. Requires access level 500 to modify level 500 settings (autojoin, massdeoppro, noop, strictop) and level 450 for remaining settings. @Tags channels @Accept json @Produce json @Param id path int true "Channel ID" @Param settings body channel.FullSettingsRequest true "Complete channel settings" @Success 200 {object} channel.UpdateChannelSettingsResponse @Failure 400 {object} errors.ErrorResponse "Invalid request data" @Failure 401 {object} errors.ErrorResponse "Authorization information is missing or invalid" @Failure 403 {object} errors.ErrorResponse "Insufficient permissions - includes denied_settings in details when specific settings are denied" @Failure 404 {object} errors.ErrorResponse "Channel not found" @Failure 500 {object} errors.ErrorResponse "Internal server error" @Router /channels/{id} [put] @Security JWTBearerToken

type ChannelMembership added in v0.3.0

type ChannelMembership struct {
	ChannelID   int32  `json:"channel_id"`
	ChannelName string `json:"channel_name"`
	AccessLevel int32  `json:"access_level"`
	MemberCount int64  `json:"member_count"`
	JoinedAt    int32  `json:"joined_at"`
}

ChannelMembership represents channel membership information with enhanced details

type ChannelRegistrationData added in v0.4.0

type ChannelRegistrationData struct {
	ChannelName   string    `json:"channel_name"`
	Status        string    `json:"status"`         // e.g., "pending", "under_review"
	SubmittedAt   time.Time `json:"submitted_at"`   // When the application was submitted
	ApplicationID int64     `json:"application_id"` // ID of the pending registration application
}

ChannelRegistrationData represents the data portion of a successful channel registration application response

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 incoming JSON payload for channel registration

type ChannelRegistrationResponse added in v0.4.0

type ChannelRegistrationResponse struct {
	Data   ChannelRegistrationData `json:"data"`
	Status string                  `json:"status"` // Always "success"
}

ChannelRegistrationResponse represents the success response for channel registration

type ChannelSearchResult added in v0.3.0

type ChannelSearchResult struct {
	ID          int32  `json:"id"`
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
	URL         string `json:"url,omitempty"`
	MemberCount int32  `json:"member_count"`
	CreatedAt   int32  `json:"created_at"`
}

ChannelSearchResult represents a single search result

type DBInterface added in v0.0.9

type DBInterface interface {
	Ping(ctx context.Context) error
}

DBInterface defines the interface for database operations

type DatabaseTestHelper added in v0.3.0

type DatabaseTestHelper struct {
	DB       *sql.DB
	Queries  *models.Queries
	TxCount  int
	Rollback func()
}

DatabaseTestHelper provides utilities for database testing

func NewDatabaseTestHelper added in v0.3.0

func NewDatabaseTestHelper(t *testing.T) *DatabaseTestHelper

NewDatabaseTestHelper creates a new database test helper

func (*DatabaseTestHelper) WithTransaction added in v0.3.0

func (h *DatabaseTestHelper) WithTransaction(t *testing.T, _ func(*models.Queries) error)

WithTransaction executes a function within a database transaction

type DisableTOTPRequest added in v0.2.0

type DisableTOTPRequest struct {
	CurrentPassword string `json:"current_password" validate:"required,max=72"        extensions:"x-order=0"`
	OTPCode         string `json:"otp_code"         validate:"required,len=6,numeric" extensions:"x-order=1"`
}

DisableTOTPRequest defines the request payload for 2FA disabling

type E2ETestSession added in v0.3.0

type E2ETestSession struct {
	Server   *TestServer
	Fixtures *TestFixtures
	Context  context.Context
}

E2ETestSession manages end-to-end test sessions

func NewE2ETestSession added in v0.3.0

func NewE2ETestSession(t *testing.T) *E2ETestSession

NewE2ETestSession creates a new E2E test session

func (*E2ETestSession) SimulateUserWorkflow added in v0.3.0

func (session *E2ETestSession) SimulateUserWorkflow() error

SimulateUserWorkflow simulates a complete user workflow for E2E testing

type EnrollTOTPRequest added in v0.2.0

type EnrollTOTPRequest struct {
	CurrentPassword string `json:"current_password" validate:"required,max=72" extensions:"x-order=0"`
}

EnrollTOTPRequest defines the request payload for 2FA enrollment

type EnrollTOTPResponse added in v0.2.0

type EnrollTOTPResponse struct {
	QRCodeBase64 string `json:"qr_code_base64" extensions:"x-order=0"`
	Secret       string `json:"secret"         extensions:"x-order=1"`
}

EnrollTOTPResponse defines the response for 2FA enrollment

type HealthCheckController

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

func NewHealthCheckController

func NewHealthCheckController(dbPool *pgxpool.Pool, rdb *redis.Client) *HealthCheckController

func (*HealthCheckController) HealthCheck

func (ctr *HealthCheckController) HealthCheck(c echo.Context) error

type HealthCheckResponse

type HealthCheckResponse struct {
	Status   string `json:"status"`
	Postgres string `json:"postgres,omitempty"`
	Redis    string `json:"redis,omitempty"`
}

type LoadTestConfig added in v0.3.0

type LoadTestConfig struct {
	Endpoint    string
	Requests    int
	Concurrency int
	Duration    time.Duration
}

LoadTestConfig configures load test parameters

type LoadTestResult added in v0.3.0

type LoadTestResult struct {
	TotalRequests  int
	SuccessfulReqs int
	FailedRequests int
	AverageLatency time.Duration
	MinLatency     time.Duration
	MaxLatency     time.Duration
	RequestsPerSec float64
	ErrorRate      float64
}

LoadTestResult contains the results of a load test

func PerformLoadTest added in v0.3.0

func PerformLoadTest(config PerformanceTestConfig, setup func() (*TestServer, *http.Request)) *LoadTestResult

PerformLoadTest executes a load test with the given configuration

type LoginResponse

type LoginResponse struct {
	AccessToken  string `` /* 219-byte string literal not displayed */
	RefreshToken string `` /* 219-byte string literal not displayed */
}

LoginResponse is the response sent to a client upon successful FULL authentication

type ManagerChangeConfirmationData added in v0.4.1

type ManagerChangeConfirmationData struct {
	ChannelID   int32  `json:"channel_id"`
	ChannelName string `json:"channel_name"`
	RequestID   int32  `json:"request_id"`
	ChangeType  string `json:"change_type"`
	Status      string `json:"status"`
}

ManagerChangeConfirmationData contains the confirmation response data

type ManagerChangeConfirmationResponse added in v0.4.1

type ManagerChangeConfirmationResponse struct {
	Status  string                        `json:"status"`
	Message string                        `json:"message"`
	Data    ManagerChangeConfirmationData `json:"data"`
}

ManagerChangeConfirmationResponse represents the response for confirming a manager change

type ManagerChangeData added in v0.4.1

type ManagerChangeData struct {
	ChannelID     int32     `json:"channel_id"               extensions:"x-order=0"`
	ChangeType    string    `json:"change_type"              extensions:"x-order=1"`
	NewManager    string    `json:"new_manager"              extensions:"x-order=2"`
	DurationWeeks *int      `json:"duration_weeks,omitempty" extensions:"x-order=3"`
	Reason        string    `json:"reason"                   extensions:"x-order=4"`
	SubmittedAt   time.Time `json:"submitted_at"             extensions:"x-order=5"`
	ExpiresAt     time.Time `json:"expires_at"               extensions:"x-order=6"`
	Status        string    `json:"status"                   extensions:"x-order=7"`
}

ManagerChangeData contains the manager change response data

type ManagerChangeRequest added in v0.4.1

type ManagerChangeRequest struct {
	NewManagerUsername string `json:"new_manager_username"     validate:"required,min=2,max=12,ircusername"`
	ChangeType         string `json:"change_type"              validate:"required,oneof=temporary permanent"`
	DurationWeeks      *int   `json:"duration_weeks,omitempty" validate:"omitempty,min=3,max=7"`
	Reason             string `json:"reason"                   validate:"required,min=1,max=500,nocontrolchars,meaningful"`
}

ManagerChangeRequest represents the request to change channel management

type ManagerChangeResponse added in v0.4.1

type ManagerChangeResponse struct {
	Data   ManagerChangeData `json:"data"`
	Status string            `json:"status"`
}

ManagerChangeResponse represents the response after submitting manager change request

type ManagerChangeStatusResponse added in v0.4.1

type ManagerChangeStatusResponse struct {
	RequestID     *int32     `json:"request_id,omitempty"`
	ChannelID     *int32     `json:"channel_id,omitempty"`
	ChangeType    *string    `json:"change_type,omitempty"`
	NewManager    *string    `json:"new_manager,omitempty"`
	DurationWeeks *int       `json:"duration_weeks,omitempty"`
	Reason        *string    `json:"reason,omitempty"`
	Status        *string    `json:"status,omitempty"`
	SubmittedAt   *time.Time `json:"submitted_at,omitempty"`
	ExpiresAt     *time.Time `json:"expires_at,omitempty"`
}

ManagerChangeStatusResponse represents the response for checking status of manager change requests

type PaginationInfo added in v0.3.0

type PaginationInfo struct {
	Total   int  `json:"total"`
	Limit   int  `json:"limit"`
	Offset  int  `json:"offset"`
	HasMore bool `json:"has_more"`
}

PaginationInfo represents pagination metadata

type PerformanceMetrics added in v0.3.0

type PerformanceMetrics struct {
	TotalRequests   int64
	SuccessfulReqs  int64
	FailedRequests  int64
	AverageLatency  time.Duration
	MinLatency      time.Duration
	MaxLatency      time.Duration
	ThroughputRPS   float64
	P95Latency      time.Duration
	P99Latency      time.Duration
	ErrorRate       float64
	MemoryUsage     uint64
	CPUUsage        float64
	ConcurrentUsers int
	TestDuration    time.Duration
	// contains filtered or unexported fields
}

PerformanceMetrics tracks performance test results

type PerformanceTestConfig added in v0.3.0

type PerformanceTestConfig struct {
	Concurrency int
	Duration    time.Duration
	Requests    int
}

PerformanceTestConfig configures performance testing parameters

type PerformanceTestHelper added in v0.3.0

type PerformanceTestHelper struct {
	*APITestHelper
	Metrics *PerformanceMetrics
}

PerformanceTestHelper provides utilities for performance testing

func NewPerformanceTestHelper added in v0.3.0

func NewPerformanceTestHelper(t *testing.T) *PerformanceTestHelper

NewPerformanceTestHelper creates a new performance test helper

func (*PerformanceTestHelper) RunLoadTest added in v0.3.0

func (h *PerformanceTestHelper) RunLoadTest(t *testing.T, config LoadTestConfig) *PerformanceMetrics

RunLoadTest executes a load test with specified parameters

type PoolInterface added in v0.1.0

type PoolInterface interface {
	Begin(ctx context.Context) (pgx.Tx, error)
}

PoolInterface defines the interface for database pool operations

type RedisInterface added in v0.0.9

type RedisInterface interface {
	Ping(ctx context.Context) *redis.StatusCmd
}

RedisInterface defines the interface for Redis operations

type RegenerateBackupCodesRequest added in v0.4.1

type RegenerateBackupCodesRequest struct {
	TOTPCode string `json:"totp_code" validate:"required,len=6,numeric" extensions:"x-order=0"`
}

RegenerateBackupCodesRequest defines the request payload for backup code regeneration

type RegenerateBackupCodesResponse added in v0.4.1

type RegenerateBackupCodesResponse struct {
	BackupCodes    []string `json:"backup_codes"    extensions:"x-order=0"`
	GeneratedAt    string   `json:"generated_at"    extensions:"x-order=1"`
	CodesRemaining int      `json:"codes_remaining" extensions:"x-order=2"`
	Message        string   `json:"message"         extensions:"x-order=3"`
}

RegenerateBackupCodesResponse defines the response for backup code regeneration

type RemoveMemberRequest added in v0.3.0

type RemoveMemberRequest struct {
	UserID int64 `json:"user_id" validate:"required"`
}

RemoveMemberRequest represents the request body for removing a member from a channel

type RemoveMemberResponse added in v0.3.0

type RemoveMemberResponse struct {
	ChannelID int32  `json:"channel_id"`
	UserID    int64  `json:"user_id"`
	RemovedAt int32  `json:"removed_at"`
	Message   string `json:"message"`
}

RemoveMemberResponse represents the response for removing a member from a channel

type Role added in v0.0.6

type Role struct {
	ID          int32  `json:"id"          extensions:"x-order=0"`
	Name        string `json:"name"        extensions:"x-order=1"`
	Description string `json:"description" extensions:"x-order=2"`
}

type SearchChannelsRequest added in v0.3.0

type SearchChannelsRequest struct {
	Query  string `query:"q"      validate:"required,min=1,max=100"`
	Limit  int    `query:"limit"  validate:"omitempty,min=1,max=100"`
	Offset int    `query:"offset" validate:"omitempty,min=0"`
}

SearchChannelsRequest represents the search parameters

type SearchChannelsResponse added in v0.3.0

type SearchChannelsResponse struct {
	Channels   []ChannelSearchResult `json:"channels"`
	Pagination PaginationInfo        `json:"pagination"`
}

SearchChannelsResponse represents the search results

type SecurityExpectation added in v0.3.0

type SecurityExpectation struct {
	ShouldBlock   bool
	ExpectedCode  int
	ExpectedError string
}

SecurityExpectation defines what should happen during a security test

type SecurityTestCase added in v0.3.0

type SecurityTestCase struct {
	Name           string
	Method         string
	URL            string
	Payload        interface{}
	Headers        map[string]string
	ExpectedStatus int
	ShouldReject   bool
	Description    string
}

SecurityTestCase represents a security test scenario

func CreateSecurityTestCases added in v0.3.0

func CreateSecurityTestCases() []SecurityTestCase

CreateSecurityTestCases generates comprehensive security test cases

type SecurityTestHelper added in v0.3.0

type SecurityTestHelper struct {
	*APITestHelper
	AttackVectors []AttackVector
}

SecurityTestHelper provides utilities for security testing

func NewSecurityTestHelper added in v0.3.0

func NewSecurityTestHelper(t *testing.T) *SecurityTestHelper

NewSecurityTestHelper creates a new security test helper

func (*SecurityTestHelper) TestAllAttackVectors added in v0.3.0

func (h *SecurityTestHelper) TestAllAttackVectors(t *testing.T)

TestAllAttackVectors runs all security attack vectors

type TestConfigManager added in v0.3.0

type TestConfigManager struct {
	TestDB    *sql.DB
	TestRedis *redis.Client
	TestSMTP  *TestSMTPServer
	TempDir   string
	Cleanup   []func()
}

TestConfigManager manages test configurations and environments

func NewTestConfigManager added in v0.3.0

func NewTestConfigManager(t *testing.T) *TestConfigManager

NewTestConfigManager creates a new test configuration manager

type TestDataGenerator added in v0.3.0

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

TestDataGenerator provides utilities for generating test data

func NewTestDataGenerator added in v0.3.0

func NewTestDataGenerator(seed int64) *TestDataGenerator

NewTestDataGenerator creates a new test data generator

func (*TestDataGenerator) GenerateChannel added in v0.3.0

func (g *TestDataGenerator) GenerateChannel() models.Channel

GenerateChannel creates a realistic test channel

func (*TestDataGenerator) GenerateUser added in v0.3.0

func (g *TestDataGenerator) GenerateUser() models.User

GenerateUser creates a realistic test user

type TestEmail added in v0.3.0

type TestEmail struct {
	To      []string
	From    string
	Subject string
	Body    string
	Headers map[string]string
	SentAt  time.Time
}

TestEmail represents an email captured during testing

type TestFixtures added in v0.3.0

type TestFixtures struct {
	Users    []models.User
	Channels []models.Channel
	Tokens   []TokenPair
}

TestFixtures contains all test data fixtures

func CreateTestFixtures added in v0.3.0

func CreateTestFixtures() *TestFixtures

CreateTestFixtures generates consistent test data

type TestSMTPServer added in v0.3.0

type TestSMTPServer struct {
	Host     string
	Port     int
	Messages []TestEmail
	// contains filtered or unexported fields
}

TestSMTPServer represents a test SMTP server

func NewTestSMTPServer added in v0.3.0

func NewTestSMTPServer() *TestSMTPServer

NewTestSMTPServer creates a new test SMTP server

func (*TestSMTPServer) ClearMessages added in v0.3.0

func (s *TestSMTPServer) ClearMessages()

ClearMessages clears all captured messages

func (*TestSMTPServer) GetMessages added in v0.3.0

func (s *TestSMTPServer) GetMessages() []TestEmail

GetMessages returns all captured messages

type TestServer added in v0.3.0

type TestServer struct {
	Echo      *echo.Echo
	Recorder  *httptest.ResponseRecorder
	MockDB    *mocks.Querier
	MockRedis *redis.Client
	JWTConfig echojwt.Config
}

TestServer wraps Echo for consistent test setup

func NewTestServer added in v0.3.0

func NewTestServer(t *testing.T) *TestServer

NewTestServer creates a configured test server

func (*TestServer) CreateRequest added in v0.3.0

func (ts *TestServer) CreateRequest(method, url string, body interface{}, userID ...int32) *http.Request

CreateRequest creates an HTTP request with optional authentication

func (*TestServer) ExecuteRequest added in v0.3.0

func (ts *TestServer) ExecuteRequest(req *http.Request) *httptest.ResponseRecorder

ExecuteRequest executes an HTTP request and returns the response recorder

func (*TestServer) MockChannelQueries added in v0.3.0

func (ts *TestServer) MockChannelQueries(fixtures *TestFixtures)

MockChannelQueries sets up common channel-related database mocks

func (*TestServer) MockUserQueries added in v0.3.0

func (ts *TestServer) MockUserQueries(fixtures *TestFixtures)

MockUserQueries sets up common user-related database mocks

type TokenPair added in v0.3.0

type TokenPair struct {
	AccessToken  string
	RefreshToken string
	UserID       int32
	Username     string
}

TokenPair represents access and refresh tokens

type UserController

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

func NewUserController

func NewUserController(s models.Querier) *UserController

func (*UserController) ActivateTOTP added in v0.2.0

func (ctr *UserController) ActivateTOTP(c echo.Context) error

ActivateTOTP completes 2FA enrollment by validating the provided OTP code @Summary Complete 2FA enrollment @Description Validates the OTP code and activates 2FA for the user account @Tags user @Accept json @Produce json @Param data body ActivateTOTPRequest true "OTP code for 2FA activation" @Success 200 "2FA activated successfully" @Failure 400 "Bad request - validation failed" @Failure 401 "Unauthorized - missing or invalid token" @Failure 403 "Forbidden - invalid OTP code" @Failure 409 "Conflict - 2FA already enabled or not enrolled" @Failure 500 "Internal server error" @Router /user/2fa/activate [post] @Security JWTBearerToken

func (*UserController) ChangePassword added in v0.2.0

func (ctr *UserController) ChangePassword(c echo.Context) error

ChangePassword allows an authenticated user to change their password @Summary Change user password @Description Changes the password for the currently authenticated user @Tags user @Accept json @Produce json @Param data body ChangePasswordRequest true "Password change request" @Success 200 {string} string "Password changed successfully" @Failure 400 {string} string "Bad request - validation error" @Failure 401 {string} string "Unauthorized - invalid current password" @Failure 404 {string} string "User not found" @Failure 500 {string} string "Internal server error" @Router /user/password [put] @Security JWTBearerToken

func (*UserController) DisableTOTP added in v0.2.0

func (ctr *UserController) DisableTOTP(c echo.Context) error

DisableTOTP disables 2FA for the authenticated user @Summary Disable 2FA @Description Disables 2FA for the user account. Requires both current password and valid OTP code for security. @Tags user @Accept json @Produce json @Param data body DisableTOTPRequest true "Password and OTP code for 2FA disabling" @Success 200 "2FA disabled successfully" @Failure 400 "Bad request - validation failed" @Failure 401 "Unauthorized - missing or invalid token" @Failure 403 "Forbidden - incorrect password or invalid OTP" @Failure 409 "Conflict - 2FA is not enabled" @Failure 500 "Internal server error" @Router /user/2fa/disable [post] @Security JWTBearerToken

func (*UserController) EnrollTOTP added in v0.2.0

func (ctr *UserController) EnrollTOTP(c echo.Context) error

EnrollTOTP allows an authenticated user to start 2FA enrollment by generating a QR code @Summary Start 2FA enrollment @Description Generates a QR code and secret for TOTP 2FA enrollment. Requires current password for security. @Tags user @Accept json @Produce json @Param data body EnrollTOTPRequest true "Password confirmation for 2FA enrollment" @Success 200 {object} EnrollTOTPResponse @Failure 400 "Bad request - validation failed" @Failure 401 "Unauthorized - missing or invalid token" @Failure 403 "Forbidden - incorrect password" @Failure 409 "Conflict - 2FA already enabled" @Failure 500 "Internal server error" @Router /user/2fa/enroll [post] @Security JWTBearerToken

func (*UserController) GetCurrentUser added in v0.1.0

func (ctr *UserController) GetCurrentUser(c echo.Context) error

GetCurrentUser returns detailed information about the current authenticated user @Summary Get current user information @Description Get current user information with detailed channel membership data and backup code status @Description Performance: Uses optimized single-query approach to avoid N+1 problems @Description Backup code status is only checked if 2FA (TOTP) is enabled @Tags user @Accept json @Produce json @Success 200 {object} UserResponse @Failure 401 "Authorization information is missing or invalid." @Failure 404 "User not found." @Failure 500 "Internal server error." @Router /user [get] @Security JWTBearerToken

func (*UserController) GetUser

func (ctr *UserController) GetUser(c echo.Context) error

GetUser returns a user by id @Summary Get user data by id @Description Returns a user by id with detailed channel membership information @Tags users @Produce json @Param id path int true "User ID" @Success 200 {object} UserResponse @Router /users/{id} [get] @Security JWTBearerToken

func (*UserController) GetUserChannels added in v0.0.8

func (ctr *UserController) GetUserChannels(c echo.Context) error

GetUserChannels returns detailed channel membership information for a user @Summary Get user's channel memberships @Description Returns detailed channel membership information for a user including member counts @Tags users @Produce json @Param id path int true "User ID" @Success 200 {array} ChannelMembership @Failure 400 "Invalid user ID" @Failure 500 "Internal server error" @Router /users/{id}/channels [get] @Security JWTBearerToken

func (*UserController) GetUserRoles added in v0.0.6

func (ctr *UserController) GetUserRoles(c echo.Context) error

GetUserRoles returns the roles for a given user @Summary Get the roles for a given user @Description Get the roles for a given user @Tags users @Produce json @Param id path int true "User ID" @Success 200 {object} UserRolesResponse @Failure 400 {string} string "Invalid user ID" @Failure 404 {string} string "User not found" @Failure 500 {string} string "Internal server error" @Router /users/{id}/roles [get] @Security JWTBearerToken

func (*UserController) MarkBackupCodesAsRead added in v0.4.1

func (ctr *UserController) MarkBackupCodesAsRead(c echo.Context) error

MarkBackupCodesAsRead marks the user's backup codes as read @Summary Mark backup codes as read @Description Marks the user's backup codes as read without retrieving them. This is an idempotent operation. @Tags user @Accept json @Produce json @Success 200 {object} map[string]string @Failure 401 "Unauthorized - missing or invalid token" @Failure 404 "Not found - no backup codes generated" @Failure 500 "Internal server error" @Router /user/backup-codes/mark-read [put] @Security JWTBearerToken

func (*UserController) RegenerateBackupCodes added in v0.4.1

func (ctr *UserController) RegenerateBackupCodes(c echo.Context) error

RegenerateBackupCodes generates new backup codes for the authenticated user @Summary Regenerate backup codes @Description Generates new backup codes, completely replacing any existing ones. Requires valid TOTP code for security verification. @Tags user @Accept json @Produce json @Param data body RegenerateBackupCodesRequest true "TOTP code for verification" @Success 200 {object} RegenerateBackupCodesResponse @Failure 400 "Bad request - validation failed" @Failure 401 "Unauthorized - missing or invalid token" @Failure 403 "Forbidden - invalid TOTP code or 2FA not enabled" @Failure 500 "Internal server error" @Router /user/backup-codes [post] @Security JWTBearerToken

type UserRegisterActivateRequest added in v0.1.0

type UserRegisterActivateRequest struct {
	Token string `json:"token" validate:"required" extensions:"x-order=0"`
}

UserActivateRequest is the request body for the activate endpoint

type UserRegisterActivateResponse added in v0.1.0

type UserRegisterActivateResponse struct {
	Username string `json:"username" extensions:"x-order=0"`
	Email    string `json:"email"    extensions:"x-order=1"`
}

UserActivateAccountResponse is the response sent to a client upon successful account activation

type UserRegisterController added in v0.1.0

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

UserRegisterController is the controller for the authentication routes

func NewUserRegisterController added in v0.1.0

func NewUserRegisterController(s models.ServiceInterface, pool PoolInterface) *UserRegisterController

NewUserRegisterController returns a new UserRegisterController

func (*UserRegisterController) UserActivateAccount added in v0.1.0

func (ctr *UserRegisterController) UserActivateAccount(c echo.Context) error

UserActivateAccount godoc @Summary Activate user account @Description Activates a user account using the provided token. @Tags auth @Accept json @Produce json @Param data body UserRegisterActivateRequest true "Activate account request" @Success 200 {object} UserRegisterActivateResponse @Failure 400 {object} errors.ErrorResponse "Bad request" @Failure 401 {object} errors.ErrorResponse "Unauthorized" @Failure 404 {object} errors.ErrorResponse "Not found" @Failure 500 {object} errors.ErrorResponse "Internal server error" @Router /activate [post]

func (*UserRegisterController) UserRegister added in v0.1.0

func (ctr *UserRegisterController) UserRegister(c echo.Context) error

UserRegister example @Summary Register @Description Creates a new user account. @Tags auth @Accept json @Produce json @Param data body UserRegisterRequest true "Register request" @Success 201 "User created" @Failure 400 {object} errors.ErrorResponse "Bad request" @Failure 500 {object} errors.ErrorResponse "Internal server error" @Router /register [post]

type UserRegisterRequest added in v0.1.0

type UserRegisterRequest struct {
	Username        string `json:"username"         validate:"required,min=2,max=12"     extensions:"x-order=0"`
	Password        string `json:"password"         validate:"required,min=10,max=72"    extensions:"x-order=1"`
	ConfirmPassword string `json:"confirm_password" validate:"required,eqfield=Password" extensions:"x-order=2"`
	Email           string `json:"email"            validate:"required,email"            extensions:"x-order=3"`
	AUP             bool   `json:"aup"              validate:"required,eq=true"          extensions:"x-order=4"`
	COPPA           bool   `json:"coppa"            validate:"required,eq=true"          extensions:"x-order=5"`
}

RegisterRequest is the request body for the register route

type UserResponse

type UserResponse struct {
	ID                   int32               `json:"id"                               extensions:"x-order=0"`
	Username             string              `json:"username"                         extensions:"x-order=1"`
	Email                string              `json:"email,omitempty"                  extensions:"x-order=2"`
	MaxLogins            int32               `json:"max_logins"                       extensions:"x-order=3"`
	LanguageCode         string              `json:"language_code,omitempty"          extensions:"x-order=4"`
	LanguageName         string              `json:"language_name,omitempty"          extensions:"x-order=5"`
	LastSeen             int32               `json:"last_seen,omitempty"              extensions:"x-order=6"`
	TotpEnabled          bool                `json:"totp_enabled"                     extensions:"x-order=7"`  // Whether 2FA (TOTP) is enabled
	BackupCodesGenerated bool                `json:"backup_codes_generated"           extensions:"x-order=8"`  // Whether backup codes have been generated (only shown if 2FA enabled)
	BackupCodesRead      bool                `json:"backup_codes_read"                extensions:"x-order=9"`  // Whether backup codes have been viewed by user (only shown if 2FA enabled)
	BackupCodesRemaining int                 `json:"backup_codes_remaining,omitempty" extensions:"x-order=10"` // Number of remaining backup codes (only shown when warning is true)
	BackupCodesWarning   bool                `json:"backup_codes_warning,omitempty"   extensions:"x-order=11"` // Warning flag when ≤3 backup codes remain (only shown when true)
	Channels             []ChannelMembership `json:"channels,omitempty"               extensions:"x-order=12"`
}

UserResponse represents the user response with detailed channel membership information

type UserRolesResponse added in v0.0.6

type UserRolesResponse struct {
	User struct {
		ID       int32  `json:"id" extensions:"x-order=0"`
		Username string `json:"username" extensions:"x-order=1"`
		Roles    []Role `json:"roles" extensions:"x-order=1"`
	} `json:"user" extensions:"x-order=0"`
}

type UsersResponse added in v0.5.0

type UsersResponse struct {
	ID       int32               `json:"id"                  extensions:"x-order=0"`
	Username string              `json:"username"            extensions:"x-order=1"`
	LastSeen int32               `json:"last_seen,omitempty" extensions:"x-order=3"`
	Channels []ChannelMembership `json:"channels,omitempty"  extensions:"x-order=4"`
}

UsersResponse represents the user response with detailed channel membership information

Directories

Path Synopsis
Package admin defines the admin controllers.
Package admin defines the admin controllers.

Jump to

Keyboard shortcuts

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