handlers

package
v0.4.2 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2024 License: Apache-2.0 Imports: 53 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")

	// 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")
)
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 DefaultAllRelations = []string{
	"can_view",
	"can_edit",
	"can_delete",
	"audit_log_viewer",
	"can_invite_admins",
	"can_invite_members",
}

DefaultAllRelations is the default list of relations to check these come from the fga/model/model.fga file relations TODO (sfunk): look into a way to get this from the fga model

Functions

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.

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 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
	// 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.Config
	// 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
	OauthProvider OauthProviderConfig
	// AuthMiddleware contains the middleware to be used for authenticated endpoints
	AuthMiddleware []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.Manager
	// Email contains email sending configuration for the server
	Emailer emailtemplates.Config
	// Entitlements contains the entitlements client
	Entitlements *entitlements.StripeClient
}

Handler contains configuration options for handlers

func (*Handler) AccountAccessHandler

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

AccountAccessHandler checks if a subject has access to an object

func (*Handler) AccountRolesHandler

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

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

func (*Handler) AccountRolesOrganizationHandler

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

AccountRolesOrganizationHandler lists roles a subject has in relation to an organization

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) error

BadRequest returns a 400 Bad Request response with the error message.

func (*Handler) BadRequestWithCode

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

BadRequest returns a 400 Bad Request response with the error message.

func (*Handler) BeginWebauthnLogin

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

BeginWebauthnLogin is the request to begin a webauthn login

func (*Handler) BeginWebauthnRegistration

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

BeginWebauthnRegistration is the request to begin a webauthn login

func (*Handler) BindAccountAccess

func (h *Handler) BindAccountAccess() *openapi3.Operation

BindAccountAccess returns the OpenAPI3 operation for accepting an account access request

func (*Handler) BindAccountRoles

func (h *Handler) BindAccountRoles() *openapi3.Operation

BindAccountRoles returns the OpenAPI3 operation for accepting an account roles request

func (*Handler) BindAccountRolesOrganization

func (h *Handler) BindAccountRolesOrganization() *openapi3.Operation

BindAccountRolesOrganization returns the OpenAPI3 operation for accepting an account roles organization request

func (*Handler) BindAccountRolesOrganizationWithParam

func (h *Handler) BindAccountRolesOrganizationWithParam() *openapi3.Operation

BindAccountRolesOrganization returns the OpenAPI3 operation for accepting an account roles organization request

func (*Handler) BindForgotPassword

func (h *Handler) BindForgotPassword() *openapi3.Operation

BindForgotPassword is used to bind the forgot password endpoint to the OpenAPI schema

func (*Handler) BindLoginHandler

func (h *Handler) BindLoginHandler() *openapi3.Operation

BindLoginHandler binds the login request to the OpenAPI schema

func (*Handler) BindOrganizationInviteAccept

func (h *Handler) BindOrganizationInviteAccept() *openapi3.Operation

BindOrganizationInviteAccept returns the OpenAPI3 operation for accepting an organization invite

func (*Handler) BindRefreshHandler

func (h *Handler) BindRefreshHandler() *openapi3.Operation

BindRefreshHandler is used to bind the refresh endpoint to the OpenAPI schema

func (*Handler) BindRegisterHandler

func (h *Handler) BindRegisterHandler() *openapi3.Operation

BindRegisterHandler is used to bind the register endpoint to the OpenAPI schema

func (*Handler) BindResendEmailHandler

func (h *Handler) BindResendEmailHandler() *openapi3.Operation

BindResendEmailHandler binds the resend email verification endpoint to the OpenAPI schema

func (*Handler) BindResetPasswordHandler

func (h *Handler) BindResetPasswordHandler() *openapi3.Operation

BindResetPasswordHandler binds the reset password handler to the OpenAPI schema

func (*Handler) BindSwitchHandler

func (h *Handler) BindSwitchHandler() *openapi3.Operation

BindSwitchHandler binds the reset password handler to the OpenAPI schema

func (*Handler) BindUploadBander added in v0.3.0

func (h *Handler) BindUploadBander() *openapi3.Operation

BindUploadBander binds the upload handler to the OpenAPI schema

func (*Handler) BindVerifyEmailHandler

func (h *Handler) BindVerifyEmailHandler() *openapi3.Operation

BindVerifyEmailHandler binds the verify email verification endpoint to the OpenAPI schema

func (*Handler) BindVerifySubscriberHandler

func (h *Handler) BindVerifySubscriberHandler() *openapi3.Operation

BindVerifySubscriberHandler creates the openapi operation for the subscription verification endpoint

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) CheckoutSessionHandler added in v0.4.1

func (h *Handler) CheckoutSessionHandler(ctx echo.Context) error

CheckoutSessionHandler is responsible for handling requests to /checkout/session and creating a stripe checkout session based on the user's organization context

func (*Handler) CheckoutSuccessHandler added in v0.4.1

func (h *Handler) CheckoutSuccessHandler(ctx echo.Context) error

CheckoutSuccessHandler is responsible for handling requests to the `/checkout/success` endpoint

func (*Handler) Conflict

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

Conflict returns a 409 Conflict response with the error message.

func (*Handler) Created

func (h *Handler) Created(ctx echo.Context, rep interface{}) error

Created returns a 201 Created response with the response object.

func (*Handler) FileUploadHandler added in v0.3.0

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

FileUploadHandler is responsible for uploading files

func (*Handler) FinishWebauthnLogin

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

FinishWebauthnLogin is the request to finish a webauthn login

func (*Handler) FinishWebauthnRegistration

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

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

func (*Handler) ForgotPassword

func (h *Handler) ForgotPassword(ctx echo.Context) 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) InternalServerError

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

InternalServerError returns a 500 Internal Server Error response with the error message.

func (*Handler) InvalidInput

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

InvalidInput returns a 400 Bad Request response with the error message.

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) 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) error

NotFound returns a 404 Not Found response with the error message.

func (*Handler) OauthRegister

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

OauthRegister returns the TokenResponse for a verified authenticated external oauth user

func (*Handler) OrganizationInviteAccept

func (h *Handler) OrganizationInviteAccept(ctx echo.Context) 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) error

Redirect returns a 302 Found response with the location header.

func (*Handler) RefreshHandler

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

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

func (*Handler) RegisterHandler

func (h *Handler) RegisterHandler(ctx echo.Context) 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 [MermaidChart: 5a357443-f959-4f16-a07f-ec504f67f0eb]

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) error

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

func (*Handler) ResetPassword

func (h *Handler) ResetPassword(ctx echo.Context) 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) Success

func (h *Handler) Success(ctx echo.Context, rep interface{}) error

Success returns a 200 OK response with the response object.

func (*Handler) SuccessBlob added in v0.3.0

func (h *Handler) SuccessBlob(ctx echo.Context, rep interface{}) error

func (*Handler) SwitchHandler

func (h *Handler) SwitchHandler(ctx echo.Context) 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) error

TooManyRequests returns a 429 Too Many Requests response with the error message.

func (*Handler) Unauthorized

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

Unauthorized returns a 401 Unauthorized response with the error message.

func (*Handler) UserInfo

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

UserInfo returns the user information for the authenticated user

func (*Handler) VerifyEmail

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

VerifyEmail is the handler for the email verification endpoint

func (*Handler) VerifySubscriptionHandler

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

VerifySubscriptionHandler is the handler for the subscription verification endpoint

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 invite token

func (*Invite) GetInviteToken

func (i *Invite) GetInviteToken() string

GetInviteToken returns the invitation token if its 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 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