handlers

package
v0.31.0 Latest Latest
Warning

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

Go to latest
Published: Sep 9, 2025 License: Apache-2.0 Imports: 97 Imported by: 0

Documentation

Overview

Package handlers contains custom handler functions

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrBadRequest is returned when the request cannot be processed
	ErrBadRequest = errors.New("invalid request")
	// ErrProcessingRequest is returned when the request cannot be processed
	ErrProcessingRequest = errors.New("error processing request, please try again")
	// ErrMissingRequiredFields is returned when the login request has an empty username or password
	ErrMissingRequiredFields = errors.New("invalid request, missing username and/or password")
	// ErrInvalidInput is returned when the input is invalid
	ErrInvalidInput = errors.New("invalid input")
	// ErrNotFound is returned when the requested object is not found
	ErrNotFound = errors.New("object not found in the database")
	// ErrMissingField is returned when a field is missing duh
	ErrMissingField = errors.New("missing required field")
	// ErrInvalidCredentials is returned when the password is invalid or missing
	ErrInvalidCredentials = errors.New("credentials are missing or invalid")
	// ErrUnverifiedUser is returned when email_verified on the user is false
	ErrUnverifiedUser = errors.New("user is not verified")
	// ErrUnableToVerifyEmail is returned when user's email is not able to be verified
	ErrUnableToVerifyEmail = errors.New("could not verify email")
	// ErrMaxAttempts is returned when user has requested the max retry attempts to verify their email
	ErrMaxAttempts = errors.New("max attempts verifying email address")
	// ErrNoEmailFound is returned when using an oauth provider and the email address cannot be determined
	ErrNoEmailFound = errors.New("no email found from oauth provider")
	// ErrInvalidProvider is returned when registering a user with an unsupported oauth provider
	ErrInvalidProvider = errors.New("oauth2 provider not supported")
	// ErrMissingOrganizationContext is returned when organization context is missing during OAuth flow
	ErrMissingOrganizationContext = errors.New("missing organization context")
	// ErrMissingUserContext is returned when user context is missing during OAuth flow
	ErrMissingUserContext = errors.New("missing user context")
	// ErrNoAuthUser is returned when the user couldn't be identified by the request
	ErrNoAuthUser = errors.New("could not identify authenticated user in request")
	// ErrPassWordResetTokenInvalid is returned when the provided token and secret do not match the stored
	ErrPassWordResetTokenInvalid = errors.New("password reset token invalid")
	// ErrNonUniquePassword is returned when the password was already used
	ErrNonUniquePassword = errors.New("password was already used, please try again")
	// ErrPasswordTooWeak is returned when the password is too weak
	ErrPasswordTooWeak = errors.New("password is too weak: use a combination of upper and lower case letters, numbers, and special characters")
	// ErrMaxDeviceLimit is returned when the user has reached the max device limit
	ErrMaxDeviceLimit = errors.New("max device limit reached")
	// ErrDeviceAlreadyRegistered is returned when the device is already registered
	ErrDeviceAlreadyRegistered = errors.New("device already registered")
	// ErrSubscriberNotFound is returned when the subscriber is not found
	ErrSubscriberNotFound = errors.New("subscriber not found")
	// ErrExpiredToken is returned when the token has expired
	ErrExpiredToken = errors.New("token has expired")
	// ErrUnauthorized is returned when the user is not authorized to make the request
	ErrUnauthorized = errors.New("not authorized")
	// ErrConflict is returned when the request cannot be processed due to a conflict
	ErrConflict = errors.New("conflict")
	// ErrAlreadySwitchedIntoOrg is returned when a user attempts to switch into an org they are currently authenticated in
	ErrAlreadySwitchedIntoOrg = errors.New("user already switched into organization")
	// ErrNoBillingEmail is returned when the user has no billing email
	ErrNoBillingEmail = errors.New("no billing email found")
	// ErrPersonalOrgsNoBilling is returned when the org ID looked up is a personal org
	ErrPersonalOrgsNoBilling = errors.New("personal orgs do not have billing")
	// ErrInvalidRecoveryCode is returned when the recovery code is invalid
	ErrInvalidRecoveryCode = errors.New("invalid code provided")
	// ErrUnsupportedEventType is returned when the event type is not supported
	ErrUnsupportedEventType = errors.New("unsupported event type")
	// ErrUnableToRegisterJobRunner is returned when the job runner node cannot be registered
	ErrUnableToRegisterJobRunner = errors.New("could not register your job runner at this time")
	// ErrJobRunnerRegistrationTokenExpired is returned when a token has expired
	ErrJobRunnerRegistrationTokenExpired = errors.New("job runner registration token expired")
	// ErrJobRunnerAlreadyRegistered is returned when we hit the ip address unique constraint
	ErrJobRunnerAlreadyRegistered = errors.New("this job runner node exists and cannot be registered twice")
	// ErrMissingOIDCConfig is returned when the OIDC configuration is missing
	ErrMissingOIDCConfig = errors.New("missing OIDC configuration, please contact support")
	// ErrStateMismatch is returned when the state parameter does not match the expected value
	ErrStateMismatch = errors.New("state parameter does not match, possible CSRF attack or session expired")
	// ErrMissingSSOConfig is returned when the SSO configuration is missing
	ErrNonceMissing = errors.New("missing nonce cookie, possible CSRF attack or session expired")
	// ErrMissingReferer is returned when the referer is missing from the request
	ErrMissingReferer = errors.New("referer is required")
	// ErrInvalidRefererURL is returned when the referer URL is invalid
	ErrInvalidRefererURL = errors.New("invalid referer URL")
	// ErrMissingSlugInPath is returned when the slug is missing from the path
	ErrMissingSlugInPath = errors.New("slug is required in the path for default trust center domain")
	// ErrTrustCenterNotFound is returned when the trust center is not found
	ErrTrustCenterNotFound = errors.New("trust center not found")
	// ErrAuthenticationRequired indicates that the user must be authenticated to perform this action
	ErrAuthenticationRequired = errors.New("authentication required")
	// ErrNoActiveImpersonationSession indicates that there is no active impersonation session
	ErrNoActiveImpersonationSession = errors.New("no active impersonation session")
	// ErrInvalidSessionID indicates that the provided session ID is invalid
	ErrInvalidSessionID = errors.New("invalid session ID")
	// ErrInsufficientPermissionsSupport indicates that the user does not have permissions to perform support impersonation
	ErrInsufficientPermissionsSupport = errors.New("insufficient permissions for support impersonation")
	// ErrInsufficientPermissionsAdmin indicates that the user does not have permissions to perform admin impersonation
	ErrInsufficientPermissionsAdmin = errors.New("insufficient permissions for admin impersonation")
	// ErrJobImpersonationAdminOnly indicates that job impersonation is only allowed for system admins
	ErrJobImpersonationAdminOnly = errors.New("job impersonation only allowed for system admins")
	// ErrInvalidImpersonationType indicates that the provided impersonation type is invalid
	ErrInvalidImpersonationType = errors.New("invalid impersonation type")
	// ErrTargetUserNotFound indicates that the target user for impersonation was not found
	ErrTargetUserNotFound = errors.New("target user not found")
	// ErrTokenManagerNotConfigured indicates that the token manager is not configured
	ErrTokenManagerNotConfigured = errors.New("token manager not configured")
	// ErrFailedToExtractSessionID indicates that the session ID could not be extracted from the token
	ErrFailedToExtractSessionID = errors.New("failed to extract session ID from token")
)
View Source
var (
	// DeviceRegisteredErrCode is returned when the device is already registered
	DeviceRegisteredErrCode rout.ErrorCode = "DEVICE_REGISTERED"
	// UserExistsErrCode is returned when the user already exists
	UserExistsErrCode rout.ErrorCode = "USER_EXISTS"
	// InvalidInputErrCode is returned when the input is invalid
	InvalidInputErrCode rout.ErrorCode = "INVALID_INPUT"
)
View Source
var (
	// ErrInvalidState is returned when OAuth state validation fails
	ErrInvalidState = fmt.Errorf("invalid OAuth state parameter")
	// ErrMissingCode is returned when OAuth authorization code is missing
	ErrMissingCode = fmt.Errorf("missing OAuth authorization code")
	// ErrExchangeAuthCode is returned when OAuth code exchange fails
	ErrExchangeAuthCode = fmt.Errorf("failed to exchange authorization code")
	// ErrValidateToken is returned when OAuth token validation fails
	ErrValidateToken = fmt.Errorf("failed to validate OAuth token")
	// ErrInvalidStateFormat is returned when OAuth state format is invalid
	ErrInvalidStateFormat = fmt.Errorf("invalid state format")
	// ErrProviderRequired is returned when provider parameter is missing
	ErrProviderRequired = fmt.Errorf("provider parameter is required")
	// ErrIntegrationIDRequired is returned when integration ID is missing
	ErrIntegrationIDRequired = fmt.Errorf("integration ID is required")
	// ErrIntegrationNotFound is returned when integration is not found
	ErrIntegrationNotFound = fmt.Errorf("integration not found")
	// ErrDeleteSecrets is returned when deleting integration secrets fails
	ErrDeleteSecrets = fmt.Errorf("failed to delete integration secrets")
)
View Source
var (
	// AuthenticatedSecurity for endpoints requiring authentication
	AuthenticatedSecurity = BearerSecurity()
	// PublicSecurity for public endpoints with no authentication
	PublicSecurity = &openapi3.SecurityRequirements{}
	// AllAuthSecurity for endpoints accepting any authentication method
	AllAuthSecurity = AllSecurityRequirements()
)

Security Requirements for common authentication patterns

View Source
var (
	// StandardAuthErrors for typical authenticated endpoints
	StandardAuthErrors = []int{http.StatusBadRequest, http.StatusUnauthorized, http.StatusInternalServerError}
	// PublicEndpointErrors for public endpoints
	PublicEndpointErrors = []int{http.StatusBadRequest, http.StatusInternalServerError}
	// AdminOnlyErrors for admin-only endpoints
	AdminOnlyErrors = []int{http.StatusBadRequest, http.StatusUnauthorized, http.StatusForbidden, http.StatusInternalServerError}
)

Error Response Patterns for common error combinations

Functions

func APIKeySecurity added in v0.6.12

func APIKeySecurity() *openapi3.SecurityRequirements

apiKeySecurity is used to add a apiKey security definition to the OpenAPI schema

func AddRequest added in v0.25.0

func AddRequest[T any](h *Handler, example T, op *openapi3.Operation)

AddRequest adds a request body to the OpenAPI schema using the type name of T

func AddResponseFor added in v0.25.0

func AddResponseFor[T any](h *Handler, description string, example T, op *openapi3.Operation, status int)

AddResponseFor adds a response definition to the OpenAPI schema using the type name of T

func AddStandardResponses added in v0.25.0

func AddStandardResponses(operation *openapi3.Operation)

AddStandardResponses adds common error responses to an OpenAPI operation Note: This function is now a no-op since error responses are registered dynamically by the error handler methods themselves when they are called.

func AdminEndpointDesc added in v0.25.0

func AdminEndpointDesc(action, resource string) string

func AllSecurityRequirements added in v0.6.12

func AllSecurityRequirements() *openapi3.SecurityRequirements

allSecurityRequirements is used to add all security definitions to the OpenAPI schema under the "or" context, meaning you can satisfy 1 or any / all of these requirements but only 1 is required if you wanted to list the security requirements with an "and" operator (meaning more than 1 needs to be met) you would list them all under a single `SecurityRequirement` rather than individual ones

func AuthEndpointDesc added in v0.25.0

func AuthEndpointDesc(action, resource string) string

AuthEndpointDesc creates a description for authenticated endpoints

func BasicSecurity added in v0.6.12

func BasicSecurity() *openapi3.SecurityRequirements

basicSecurity is used to add a basic security definition to the OpenAPI schema

func BearerSecurity added in v0.6.12

func BearerSecurity() *openapi3.SecurityRequirements

bearerSecurity is used to add a bearer security definition to the OpenAPI schema

func BindAndValidate added in v0.25.0

func BindAndValidate[T any](ctx echo.Context) (*T, error)

BindAndValidate binds the context payload into T and runs Validate if present.

func BindAndValidateQueryParams added in v0.25.0

func BindAndValidateQueryParams[T any](ctx echo.Context, op *openapi3.Operation, example T, registry SchemaRegistry) (*T, error)

BindAndValidateQueryParams binds and validates query parameters for GET requests and registers them in the OpenAPI schema For backwards compatibility - use BindAndValidateQueryParamsWithResponse for new code

func BindAndValidateQueryParamsWithResponse added in v0.26.9

func BindAndValidateQueryParamsWithResponse[T any, R any](ctx echo.Context, op *openapi3.Operation, requestExample T, responseExample R, registry SchemaRegistry) (*T, error)

BindAndValidateQueryParamsWithResponse binds and validates query parameters and registers both request and response schemas

func BindAndValidateWithAutoRegistry added in v0.25.0

func BindAndValidateWithAutoRegistry[T any, R any](ctx echo.Context, _ *Handler, op *openapi3.Operation, requestExample T, responseExample R, registry interface {
	GetOrRegister(any) (*openapi3.SchemaRef, error)
}) (*T, error)

BindAndValidateWithAutoRegistry registers the request and response with the OpenAPI specification using dynamic schema registration and then binds and validates the payload. This automatically detects response examples using the ExampleProvider interface.

func BindAndValidateWithRequest added in v0.25.0

func BindAndValidateWithRequest[T any](ctx echo.Context, h *Handler, op *openapi3.Operation, example T) (*T, error)

BindAndValidateWithRequest registers the request with the OpenAPI specification and then binds and validates the payload. op may be nil when the handler does not require OpenAPI registration.

func CheckRegistrationModeWithResponse added in v0.26.9

func CheckRegistrationModeWithResponse(ctx echo.Context) error

CheckRegistrationModeWithResponse checks if we're in registration mode and returns early with nil This should be called at the beginning of handlers to skip execution during OpenAPI generation

func IsConstraintError

func IsConstraintError(err error) bool

IsConstraintError returns true if the error resulted from a database constraint violation.

func IsForeignKeyConstraintError

func IsForeignKeyConstraintError(err error) bool

IsForeignKeyConstraintError reports if the error resulted from a database foreign-key constraint violation. e.g. parent row does not exist.

func IsUniqueConstraintError

func IsUniqueConstraintError(err error) bool

IsUniqueConstraintError reports if the error resulted from a DB uniqueness constraint violation. e.g. duplicate value in unique index.

func OauthSecurity added in v0.6.12

func OauthSecurity() *openapi3.SecurityRequirements

oauthSecurity is used to add a oauth security definition to the OpenAPI schema

func ProcessAuthenticatedRequest added in v0.25.0

func ProcessAuthenticatedRequest[TReq, TResp any](ctx echo.Context, h *Handler, openapi *OpenAPIContext, requestExample TReq, responseExample TResp, processor func(context.Context, *TReq, *auth.AuthenticatedUser) (*TResp, error)) error

ProcessAuthenticatedRequest provides a generic pattern for authenticated requests with automatic user context injection

func ProcessRequest added in v0.25.0

func ProcessRequest[TReq, TResp any](ctx echo.Context, h *Handler, openapi *OpenAPIContext, requestExample TReq, responseExample TResp, processor func(context.Context, *TReq) (*TResp, error)) error

ProcessRequest provides a generic pattern for handling requests with automatic binding, validation, and response handling

func PublicEndpointDesc added in v0.25.0

func PublicEndpointDesc(action, resource string) string

Types

type CheckFunc

type CheckFunc func(ctx context.Context) error

CheckFunc is a function that can be used to check the status of a service

type Checks

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

func (*Checks) ReadyHandler

func (c *Checks) ReadyHandler(ctx echo.Context) error

type GitHubEmail added in v0.24.1

type GitHubEmail struct {
	Email    string `json:"email"`
	Primary  bool   `json:"primary"`
	Verified bool   `json:"verified"`
}

GitHubEmail represents GitHub email data from API

type GitHubUser added in v0.24.1

type GitHubUser struct {
	ID       int    `json:"id"`
	Login    string `json:"login"`
	Email    string `json:"email"`
	Name     string `json:"name"`
	Company  string `json:"company"`
	Location string `json:"location"`
	Blog     string `json:"blog"`
	Bio      string `json:"bio"`
}

GitHubUser represents GitHub user data from API

type Handler

type Handler struct {
	// IsTest is a flag to determine if the application is running in test mode and will mock external calls
	IsTest bool
	// IsDev is a flag to determine if the application is running in development mode
	IsDev bool
	// DBClient to interact with the database
	DBClient *ent.Client
	// RedisClient to interact with redis
	RedisClient *redis.Client
	// AuthManager contains the required configuration for the auth session creation
	AuthManager *authmanager.Client
	// TokenManager contains the token manager in order to validate auth requests
	TokenManager *tokens.TokenManager
	// ReadyChecks is a set of checkFuncs to determine if the application is "ready" upon startup
	ReadyChecks Checks
	// JWTKeys contains the set of valid JWT authentication key
	JWTKeys jwk.Set
	// SessionConfig to handle sessions
	SessionConfig *sessions.SessionConfig
	// OauthProvider contains the configuration settings for all supported Oauth2 providers (for social login)
	OauthProvider OauthProviderConfig
	// IntegrationOauthProvider contains the configuration settings for integration Oauth2 providers
	IntegrationOauthProvider IntegrationOauthProviderConfig
	// AuthMiddleware contains the middleware to be used for authenticated endpoints
	AuthMiddleware []echo.MiddlewareFunc
	// AdditionalMiddleware contains the additional middleware to be used for all endpoints
	// it is separate so it can be applied after any auth middleware if needed
	AdditionalMiddleware []echo.MiddlewareFunc
	// WebAuthn contains the configuration settings for the webauthn provider
	WebAuthn *webauthn.WebAuthn
	// OTPManager contains the configuration settings for the OTP provider
	OTPManager *totp.Client
	// Email contains email sending configuration for the server
	Emailer emailtemplates.Config
	// Entitlements contains the entitlements client
	Entitlements *entitlements.StripeClient
	// Summarizer contains the summarizing client
	Summarizer *summarizer.Client
	// Windmill contains the Windmill workflow automation client
	Windmill *windmill.Client
	// DefaultTrustCenterDomain is the default domain to use for the trust center if no custom domain is set
	DefaultTrustCenterDomain string
}

Handler contains configuration options for handlers

func (*Handler) ACMESolverHandler added in v0.15.2

func (h *Handler) ACMESolverHandler(ctx echo.Context, openapi *OpenAPIContext) error

ACMESolverHandler handles ACME challenge requests by looking up the challenge path and returning the expected challenge value for domain verification

func (*Handler) AccountAccessHandler

func (h *Handler) AccountAccessHandler(ctx echo.Context, openapi *OpenAPIContext) error

AccountAccessHandler checks if a subject has access to an object

func (*Handler) AccountFeaturesHandler added in v0.12.0

func (h *Handler) AccountFeaturesHandler(ctx echo.Context, openapi *OpenAPIContext) error

AccountFeaturesHandler lists all features the authenticated user has access to in relation to an organization

func (*Handler) AccountRolesHandler

func (h *Handler) AccountRolesHandler(ctx echo.Context, openapi *OpenAPIContext) error

AccountAccessHandler list roles a subject has access to in relation an object

func (*Handler) AccountRolesOrganizationHandler

func (h *Handler) AccountRolesOrganizationHandler(ctx echo.Context, openapi *OpenAPIContext) error

AccountRolesOrganizationHandler lists roles a subject has in relation to an organization

func (*Handler) AddPathParameter added in v0.6.2

func (h *Handler) AddPathParameter(paramName string, op *openapi3.Operation)

AddPathParameter is used to add a path parameter definition to the OpenAPI schema (e.g. /users/{id})

func (*Handler) AddQueryParameter added in v0.6.2

func (h *Handler) AddQueryParameter(paramName string, op *openapi3.Operation)

AddQueryParameter is used to add a query parameter definition to the OpenAPI schema (e.g ?name=value)

func (*Handler) AddReadinessCheck

func (h *Handler) AddReadinessCheck(name string, f CheckFunc)

AddReadinessCheck will accept a function to be ran during calls to /readyz These functions should accept a context and only return an error. When adding a readiness check a name is also provided, this name will be used when returning the state of all the checks

func (*Handler) AddRequestBody

func (h *Handler) AddRequestBody(name string, body interface{}, op *openapi3.Operation)

AddRequestBody is used to add a request body definition to the OpenAPI schema

func (*Handler) AddResponse

func (h *Handler) AddResponse(name string, description string, body interface{}, op *openapi3.Operation, status int)

AddResponse is used to add a response definition to the OpenAPI schema

func (*Handler) BadRequest

func (h *Handler) BadRequest(ctx echo.Context, err error, openapi ...*OpenAPIContext) error

BadRequest returns a 400 Bad Request response with the error message. Automatically registers the response schema if an OpenAPI context is provided.

func (*Handler) BadRequestWithCode

func (h *Handler) BadRequestWithCode(ctx echo.Context, err error, code rout.ErrorCode, openapi ...*OpenAPIContext) error

BadRequestWithCode returns a 400 Bad Request response with the error message and code. Automatically registers the response schema if an OpenAPI context is provided.

func (*Handler) BeginWebauthnLogin

func (h *Handler) BeginWebauthnLogin(ctx echo.Context, openapi *OpenAPIContext) error

BeginWebauthnLogin is the request to begin a webauthn login

func (*Handler) BeginWebauthnRegistration

func (h *Handler) BeginWebauthnRegistration(ctx echo.Context, openapi *OpenAPIContext) error

BeginWebauthnRegistration is the request to begin a webauthn login

func (*Handler) CheckAndCreateUser

func (h *Handler) CheckAndCreateUser(ctx context.Context, name, email string, provider enums.AuthProvider, image string) (*ent.User, error)

CheckAndCreateUser takes a user with an OauthTooToken set in the context and checks if the user is already created if the user already exists, update last seen

func (*Handler) Conflict

func (h *Handler) Conflict(ctx echo.Context, err string, code rout.ErrorCode, openapi ...*OpenAPIContext) error

Conflict returns a 409 Conflict response with the error message. Automatically registers the response schema if an OpenAPI context is provided.

func (*Handler) CreateTrustCenterAnonymousJWT added in v0.20.5

func (h *Handler) CreateTrustCenterAnonymousJWT(ctx echo.Context, openapi *OpenAPIContext) error

func (*Handler) Created

func (h *Handler) Created(ctx echo.Context, rep any, openapi ...*OpenAPIContext) error

Created returns a 201 Created response with the response object. Automatically registers the response schema if an OpenAPI context is provided.

func (*Handler) EndImpersonation added in v0.24.1

func (h *Handler) EndImpersonation(ctx echo.Context, openapi *OpenAPIContext) error

EndImpersonation handles requests to end an impersonation session

func (*Handler) ExampleCSV added in v0.7.5

func (h *Handler) ExampleCSV(ctx echo.Context, openapi *OpenAPIContext) error

ExampleCSV will return an example csv file that can be used for bulk uploads of the object

func (*Handler) FileUploadHandler added in v0.3.0

func (h *Handler) FileUploadHandler(ctx echo.Context, openapi *OpenAPIContext) error

FileUploadHandler is responsible for uploading files

func (*Handler) FinishWebauthnLogin

func (h *Handler) FinishWebauthnLogin(ctx echo.Context, openapi *OpenAPIContext) error

FinishWebauthnLogin is the request to finish a webauthn login

func (*Handler) FinishWebauthnRegistration

func (h *Handler) FinishWebauthnRegistration(ctx echo.Context, openapi *OpenAPIContext) error

FinishWebauthnRegistration is the request to finish a webauthn registration - this is where we get the credential created by the user back

func (*Handler) Forbidden added in v0.25.0

func (h *Handler) Forbidden(ctx echo.Context, err error, openapi ...*OpenAPIContext) error

Forbidden returns a 403 Forbidden response with the error message. Automatically registers the response schema if an OpenAPI context is provided.

func (*Handler) ForgotPassword

func (h *Handler) ForgotPassword(ctx echo.Context, openapi *OpenAPIContext) error

ForgotPassword will send an forgot password email if the provided email exists

func (*Handler) GetGitHubLoginHandlers

func (h *Handler) GetGitHubLoginHandlers() (http.Handler, http.Handler)

GetGitHubLoginHandlers returns the github login and callback handlers

func (*Handler) GetGoogleLoginHandlers

func (h *Handler) GetGoogleLoginHandlers() (http.Handler, http.Handler)

GetGoogleLoginHandlers returns the google login and callback handlers

func (*Handler) HandleEvent added in v0.7.4

func (h *Handler) HandleEvent(c context.Context, e *stripe.Event) error

HandleEvent unmarshals event data and triggers a corresponding function to be executed based on case match

func (*Handler) HandleOAuthCallback added in v0.24.1

func (h *Handler) HandleOAuthCallback(ctx echo.Context, openapi *OpenAPIContext) error

HandleOAuthCallback processes the OAuth callback and stores integration tokens

func (*Handler) HasValidSSOSession added in v0.22.0

func (h *Handler) HasValidSSOSession(ctx echo.Context, userID string) bool

func (*Handler) InternalServerError

func (h *Handler) InternalServerError(ctx echo.Context, err error, openapi ...*OpenAPIContext) error

InternalServerError returns a 500 Internal Server Error response with the error message. Automatically registers the response schema if an OpenAPI context is provided.

func (*Handler) InvalidInput

func (h *Handler) InvalidInput(ctx echo.Context, err error, openapi ...*OpenAPIContext) error

InvalidInput returns a 400 Bad Request response with the error message. Automatically registers the response schema if an OpenAPI context is provided.

func (*Handler) IsAuthenticated

func (h *Handler) IsAuthenticated(req *http.Request) bool

IsAuthenticated checks the sessions to a valid session cookie

func (*Handler) LoginHandler

func (h *Handler) LoginHandler(ctx echo.Context, openapi *OpenAPIContext) error

LoginHandler validates the user credentials and returns a valid cookie this handler only supports username password login

func (*Handler) NotFound

func (h *Handler) NotFound(ctx echo.Context, err error, openapi ...*OpenAPIContext) error

NotFound returns a 404 Not Found response with the error message. Automatically registers the response schema if an OpenAPI context is provided.

func (*Handler) OauthRegister

func (h *Handler) OauthRegister(ctx echo.Context, openapi *OpenAPIContext) error

OauthRegister returns the TokenResponse for a verified authenticated external oauth user

func (*Handler) OrganizationInviteAccept

func (h *Handler) OrganizationInviteAccept(ctx echo.Context, openapi *OpenAPIContext) error

OrganizationInviteAccept is responsible for handling the invitation of a user to an organization. It receives a request with the user's invitation details, validates the request, and creates organization membership for the user On success, it returns a response with the organization information

func (*Handler) Redirect added in v0.4.1

func (h *Handler) Redirect(ctx echo.Context, location string, openapi ...*OpenAPIContext) error

Redirect returns a 302 Found response with the location header. Automatically registers the response schema if an OpenAPI context is provided.

func (*Handler) RefreshHandler

func (h *Handler) RefreshHandler(ctx echo.Context, openapi *OpenAPIContext) error

RefreshHandler allows users to refresh their access token using their refresh token

func (*Handler) RefreshIntegrationToken added in v0.24.1

func (h *Handler) RefreshIntegrationToken(ctx context.Context, orgID, provider string) (*models.IntegrationToken, error)

RefreshIntegrationToken refreshes an expired OAuth token if refresh token is available

func (*Handler) RefreshIntegrationTokenHandler added in v0.24.1

func (h *Handler) RefreshIntegrationTokenHandler(ctx echo.Context, openapi *OpenAPIContext) error

RefreshIntegrationTokenHandler is the HTTP handler for refreshing integration tokens

func (*Handler) RegisterHandler

func (h *Handler) RegisterHandler(ctx echo.Context, openapi *OpenAPIContext) error

RegisterHandler handles the registration of a new user, creating the user, personal organization and sending an email verification to the email address in the request the user will not be able to authenticate until the email is verified

func (*Handler) RegisterJobRunner added in v0.14.1

func (h *Handler) RegisterJobRunner(ctx echo.Context, openapi *OpenAPIContext) error

func (*Handler) RequireLogin

func (h *Handler) RequireLogin(next http.Handler) http.Handler

RequireLogin redirects unauthenticated users to the login route

func (*Handler) ResendEmail

func (h *Handler) ResendEmail(ctx echo.Context, openapi *OpenAPIContext) error

ResendEmail will resend an email verification email if the provided email exists

func (*Handler) ResetPassword

func (h *Handler) ResetPassword(ctx echo.Context, openapi *OpenAPIContext) error

ResetPassword allows the user (after requesting a password reset) to set a new password - the password reset token needs to be set in the request and not expired. If the request is successful, a confirmation of the reset is sent to the user and a 204 no content is returned

func (*Handler) SSOCallbackHandler added in v0.22.0

func (h *Handler) SSOCallbackHandler(ctx echo.Context, openapi *OpenAPIContext) error

SSOCallbackHandler completes the OIDC login flow after the user returns from the IdP It validates state/nonce, exchanges the code for tokens, provisions the user if needed, and issues a session

func (*Handler) SSOLoginHandler added in v0.22.0

func (h *Handler) SSOLoginHandler(ctx echo.Context, openapi *OpenAPIContext) error

SSOLoginHandler redirects the user to the organization's configured IdP for authentication It sets state and nonce cookies, builds the OIDC auth URL, and issues a redirect see docs/SSO.md for more details on the SSO flow

func (*Handler) SSOTokenAuthorizeHandler added in v0.22.0

func (h *Handler) SSOTokenAuthorizeHandler(ctx echo.Context, openapi *OpenAPIContext) error

SSOTokenAuthorizeHandler marks a token as authorized for SSO for an organization

func (*Handler) SSOTokenCallbackHandler added in v0.22.0

func (h *Handler) SSOTokenCallbackHandler(ctx echo.Context, openapi *OpenAPIContext) error

SSOTokenCallbackHandler completes the SSO authorization flow for a token. It validates the state and nonce, exchanges the code if required and updates the token's SSO authorizations for the organization.

func (*Handler) StartImpersonation added in v0.24.1

func (h *Handler) StartImpersonation(ctx echo.Context, openapi *OpenAPIContext) error

StartImpersonation handles requests to start user impersonation

func (*Handler) StartOAuthFlow added in v0.24.1

func (h *Handler) StartOAuthFlow(ctx echo.Context, openapi *OpenAPIContext) error

StartOAuthFlow initiates the OAuth flow for a third-party integration

func (*Handler) Success

func (h *Handler) Success(ctx echo.Context, rep any, openapi ...*OpenAPIContext) error

Success returns a 200 OK response with the response object. Automatically registers the response schema if an OpenAPI context is provided.

func (*Handler) SuccessBlob added in v0.3.0

func (h *Handler) SuccessBlob(ctx echo.Context, rep any, openapi ...*OpenAPIContext) error

SuccessBlob returns a 200 OK response with the response object as pretty-printed JSON. Automatically registers the response schema if an OpenAPI context is provided.

func (*Handler) SwitchHandler

func (h *Handler) SwitchHandler(ctx echo.Context, openapi *OpenAPIContext) error

SwitchHandler is responsible for handling requests to the `/switch` endpoint, and changing the user's logged in organization context

func (*Handler) TooManyRequests

func (h *Handler) TooManyRequests(ctx echo.Context, err error, openapi ...*OpenAPIContext) error

TooManyRequests returns a 429 Too Many Requests response with the error message. Automatically registers the response schema if an OpenAPI context is provided.

func (*Handler) Unauthorized

func (h *Handler) Unauthorized(ctx echo.Context, err error, openapi ...*OpenAPIContext) error

Unauthorized returns a 401 Unauthorized response with the error message. Automatically registers the response schema if an OpenAPI context is provided.

func (*Handler) UserInfo

func (h *Handler) UserInfo(ctx echo.Context, openapi *OpenAPIContext) error

UserInfo returns the user information for the authenticated user

func (*Handler) ValidateTOTP added in v0.6.11

func (h *Handler) ValidateTOTP(ctx echo.Context, openapi *OpenAPIContext) error

ValidateTOTP validates a user's TOTP code this currently only supports TOTP and not OTP codes via email and SMS

func (*Handler) VerifyEmail

func (h *Handler) VerifyEmail(ctx echo.Context, openapi *OpenAPIContext) error

VerifyEmail is the handler for the email verification endpoint

func (*Handler) VerifySubscriptionHandler

func (h *Handler) VerifySubscriptionHandler(ctx echo.Context, openapi *OpenAPIContext) error

VerifySubscriptionHandler is the handler for the subscription verification endpoint

func (*Handler) WebfingerHandler added in v0.22.0

func (h *Handler) WebfingerHandler(ctx echo.Context, openapi *OpenAPIContext) error

WebfingerHandler is a simple protocol which allows you to publicly query a well-know URI along with a resource identifier (like an email address) to determine basic attributes In our case, we're using it to determine if SSO login is enforced for an organization or user It parses the resource query param, resolves the user (or org), and returns SSO status https://datatracker.ietf.org/doc/html/rfc7033 per the RFC, response codes should not always be 201 or similar, but 404, 200, etc., regular status codes should be used

func (*Handler) WebhookReceiverHandler added in v0.6.5

func (h *Handler) WebhookReceiverHandler(ctx echo.Context, openapi *OpenAPIContext) error

WebhookReceiverHandler handles incoming stripe webhook events for the supported event types

type IntegrationHelper added in v0.24.1

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

IntegrationHelper provides helper methods for integration operations

func NewIntegrationHelper added in v0.24.1

func NewIntegrationHelper(provider, username string) *IntegrationHelper

NewIntegrationHelper creates a new integration helper

func (*IntegrationHelper) AuthHeader added in v0.24.1

func (ih *IntegrationHelper) AuthHeader(token string) (string, string)

AuthHeader returns the appropriate authorization header for the provider

func (*IntegrationHelper) CallbackURL added in v0.24.1

func (ih *IntegrationHelper) CallbackURL(baseURL string) string

CallbackURL returns the OAuth callback URL

func (*IntegrationHelper) Description added in v0.24.1

func (ih *IntegrationHelper) Description() string

Description returns the integration description

func (*IntegrationHelper) Name added in v0.24.1

func (ih *IntegrationHelper) Name() string

Name returns the integration name

func (*IntegrationHelper) RedirectURL added in v0.24.1

func (ih *IntegrationHelper) RedirectURL(baseURL string) string

RedirectURL returns the success redirect URL with parameters

func (*IntegrationHelper) SecretDescription added in v0.24.1

func (ih *IntegrationHelper) SecretDescription(fieldName string) string

SecretDescription returns the description for a secret

func (*IntegrationHelper) SecretDisplayName added in v0.24.1

func (ih *IntegrationHelper) SecretDisplayName(integrationName, fieldName string) string

SecretDisplayName returns the display name for a secret

func (*IntegrationHelper) SecretName added in v0.24.1

func (ih *IntegrationHelper) SecretName(fieldName string) string

SecretName returns the secret name for a given field

func (*IntegrationHelper) StateData added in v0.24.1

func (ih *IntegrationHelper) StateData(orgID string, randomBytes []byte) string

StateData returns the OAuth state data

func (*IntegrationHelper) StatusMessage added in v0.24.1

func (ih *IntegrationHelper) StatusMessage(status string) string

StatusMessage returns status messages for integration status

type IntegrationOauthProviderConfig added in v0.24.1

type IntegrationOauthProviderConfig struct {
	// RedirectURL is the base URL for integration OAuth callbacks
	RedirectURL string `json:"redirectUrl" koanf:"redirectUrl"`
	// SuccessRedirectURL is the URL to redirect to after successful OAuth integration
	SuccessRedirectURL string `` /* 151-byte string literal not displayed */
	// Github contains the configuration settings for GitHub integrations
	Github IntegrationProviderConfig `json:"github" koanf:"github"`
	// Slack contains the configuration settings for Slack integrations
	Slack IntegrationProviderConfig `json:"slack" koanf:"slack"`
}

IntegrationOauthProviderConfig represents the configuration for OAuth providers used for integrations

type IntegrationProvider added in v0.24.1

type IntegrationProvider struct {
	Name     string
	Config   *oauth2.Config
	Validate func(ctx context.Context, token *oauth2.Token) (*IntegrationUserInfo, error)
}

IntegrationProvider represents a supported OAuth provider for integrations

type IntegrationProviderConfig added in v0.24.1

type IntegrationProviderConfig struct {
	// ClientID is the OAuth2 client ID
	ClientID string `json:"clientId" koanf:"clientId"`
	// ClientSecret is the OAuth2 client secret
	ClientSecret string `json:"clientSecret" koanf:"clientSecret" sensitive:"true"`
	// ClientEndpoint is the base URL for the OAuth endpoints
	ClientEndpoint string `json:"clientEndpoint" koanf:"clientEndpoint" domain:"inherit" domainPrefix:"https://api"`
	// Scopes are the OAuth2 scopes to request
	Scopes []string `json:"scopes" koanf:"scopes"`
}

IntegrationProviderConfig contains OAuth configuration for a specific integration provider

type IntegrationUserInfo added in v0.24.1

type IntegrationUserInfo struct {
	ID       string
	Username string
	Email    string
}

IntegrationUserInfo contains user information from OAuth provider

type Invite

type Invite struct {
	Token     string
	UserID    ulid.ULID
	Email     string
	DestOrgID ulid.ULID
	Role      enums.Role
	InviteToken
}

Invite holds the Token, InviteToken references, and the additional user input to complete acceptance of the invitation

func (*Invite) GetInviteExpires

func (i *Invite) GetInviteExpires() (time.Time, error)

GetInviteExpires returns the expiration time of the invite token

func (*Invite) GetInviteToken

func (i *Invite) GetInviteToken() string

GetInviteToken returns the invitation token if it's valid

type InviteToken

type InviteToken struct {
	Expires sql.NullString
	Token   sql.NullString
	Secret  []byte
}

InviteToken holds data specific to a future user of the system for invite logic

type OauthProviderConfig

type OauthProviderConfig struct {
	// RedirectURL is the URL that the OAuth2 client will redirect to after authentication is complete
	RedirectURL string `json:"redirectUrl" koanf:"redirectUrl" default:"http://localhost:3001/api/auth/callback/theopenlane"`
	// Github contains the configuration settings for the Github Oauth Provider
	Github github.ProviderConfig `json:"github" koanf:"github"`
	// Google contains the configuration settings for the Google Oauth Provider
	Google google.ProviderConfig `json:"google" koanf:"google"`
	// Webauthn contains the configuration settings for the Webauthn Oauth Provider
	Webauthn webauthn.ProviderConfig `json:"webauthn" koanf:"webauthn"`
}

OauthProviderConfig represents the configuration for OAuth providers such as Github and Google

type OpenAPIContext added in v0.25.0

type OpenAPIContext struct {
	Operation *openapi3.Operation
	Registry  SchemaRegistry
}

OpenAPIContext holds the OpenAPI operation and schema registry for automatic registration

type SchemaRegistry added in v0.25.0

type SchemaRegistry interface {
	GetOrRegister(any) (*openapi3.SchemaRef, error)
}

SchemaRegistry interface for dynamic schema registration

type SlackUser added in v0.24.1

type SlackUser struct {
	OK    bool          `json:"ok"`
	User  SlackUserInfo `json:"user"`
	Error string        `json:"error,omitempty"`
}

SlackUser represents Slack user data from API

type SlackUserInfo added in v0.24.1

type SlackUserInfo struct {
	ID       string           `json:"id"`
	TeamID   string           `json:"team_id"`
	Name     string           `json:"name"`
	Deleted  bool             `json:"deleted"`
	RealName string           `json:"real_name"`
	Profile  SlackUserProfile `json:"profile"`
}

SlackUserInfo contains Slack user profile information

type SlackUserProfile added in v0.24.1

type SlackUserProfile struct {
	Email                 string `json:"email"`
	DisplayName           string `json:"display_name"`
	DisplayNameNormalized string `json:"display_name_normalized"`
	RealName              string `json:"real_name"`
	RealNameNormalized    string `json:"real_name_normalized"`
}

SlackUserProfile contains Slack user profile details

type StatusReply

type StatusReply struct {
	Status map[string]string `json:"status"`
}

StatusReply returns server status

type URLToken

type URLToken struct {
	Expires sql.NullString
	Token   sql.NullString
	Secret  []byte
}

URLToken holds data specific to a future user of the system for invite logic

type User

type User struct {
	ID                       string
	FirstName                string
	LastName                 string
	Name                     string
	Email                    string
	Password                 *string
	OTPSecret                string `json:"-"`
	EmailVerificationExpires sql.NullString
	EmailVerificationToken   sql.NullString
	EmailVerificationSecret  []byte
	PasswordResetExpires     sql.NullString
	PasswordResetToken       sql.NullString
	PasswordResetSecret      []byte
	URLToken
}

User holds data specific to the user for the REST handlers for login, registration, verification, etc

func (*User) CreatePasswordResetToken

func (u *User) CreatePasswordResetToken() error

CreatePasswordResetToken creates a new reset token for the user

func (*User) CreateVerificationToken

func (u *User) CreateVerificationToken() error

CreateVerificationToken creates a new email verification token for the user

func (*User) GetPasswordResetExpires

func (u *User) GetPasswordResetExpires() (time.Time, error)

GetPasswordResetExpires returns the expiration time of password verification token

func (*User) GetPasswordResetToken

func (u *User) GetPasswordResetToken() string

GetPasswordResetToken returns the password reset token if its valid

func (*User) GetVerificationExpires

func (u *User) GetVerificationExpires() (time.Time, error)

GetVerificationExpires returns the expiration time of email verification token

func (*User) GetVerificationToken

func (u *User) GetVerificationToken() string

GetVerificationToken returns the verification token if its valid

Jump to

Keyboard shortcuts

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