Documentation
¶
Overview ¶
Package handlers contains custom handler functions
Index ¶
- Variables
- func IsConstraintError(err error) bool
- func IsForeignKeyConstraintError(err error) bool
- func IsUniqueConstraintError(err error) bool
- type CheckFunc
- type Checks
- type ForgotPasswordReply
- type ForgotPasswordRequest
- type Handler
- func (h *Handler) AddReadinessCheck(name string, f CheckFunc)
- func (h *Handler) BeginWebauthnLogin(ctx echo.Context) error
- func (h *Handler) BeginWebauthnRegistration(ctx echo.Context) error
- func (h *Handler) CheckAndCreateUser(ctx context.Context, name, email string, provider enums.AuthProvider) (*ent.User, error)
- func (h *Handler) FinishWebauthnLogin(ctx echo.Context) error
- func (h *Handler) FinishWebauthnRegistration(ctx echo.Context) error
- func (h *Handler) ForgotPassword(ctx echo.Context) error
- func (h *Handler) GetGitHubLoginHandlers() (http.Handler, http.Handler)
- func (h *Handler) GetGoogleLoginHandlers() (http.Handler, http.Handler)
- func (h *Handler) IsAuthenticated(req *http.Request) bool
- func (h *Handler) LoginHandler(ctx echo.Context) error
- func (h *Handler) Logout(ctx echo.Context) error
- func (h *Handler) OauthRegister(ctx echo.Context) error
- func (h *Handler) OpenIDConfiguration(ctx echo.Context) error
- func (h *Handler) OrganizationInviteAccept(ctx echo.Context) error
- func (h *Handler) RefreshHandler(ctx echo.Context) error
- func (h *Handler) RegisterHandler(ctx echo.Context) error
- func (h *Handler) RequireLogin(next http.Handler) http.Handler
- func (h *Handler) ResendEmail(ctx echo.Context) error
- func (h *Handler) ResetPassword(ctx echo.Context) error
- func (h *Handler) SendOrgInvitationEmail(i *emails.Invite) error
- func (h *Handler) SendPasswordResetRequestEmail(user *User) error
- func (h *Handler) SendPasswordResetSuccessEmail(user *User) error
- func (h *Handler) SendSubscriberEmail(user *User, orgName string) error
- func (h *Handler) SendVerificationEmail(user *User) error
- func (h *Handler) SubscribeHandler(ctx echo.Context) error
- func (h *Handler) SwitchHandler(ctx echo.Context) error
- func (h *Handler) UnsubscribeHandler(ctx echo.Context) error
- func (h *Handler) UserInfo(ctx echo.Context) error
- func (h *Handler) VerifyEmail(ctx echo.Context) error
- func (h *Handler) VerifySubscriptionHandler(ctx echo.Context) error
- type Invite
- type InviteReply
- type InviteRequest
- type InviteToken
- type LoginReply
- type LoginRequest
- type OauthProviderConfig
- type OauthTokenRequest
- type RefreshReply
- type RefreshRequest
- type RegisterReply
- type RegisterRequest
- type ResendReply
- type ResendRequest
- type ResetPasswordReply
- type ResetPasswordRequest
- type StatusReply
- type SubscribeReply
- type SubscribeRequest
- type SwitchOrganizationReply
- type SwitchOrganizationRequest
- type URLToken
- type UnsubscribeReply
- type UnsubscribeRequest
- type User
- func (u *User) CreatePasswordResetToken() error
- func (u *User) CreateVerificationToken() error
- func (u *User) GetPasswordResetExpires() (time.Time, error)
- func (u *User) GetPasswordResetToken() string
- func (u *User) GetVerificationExpires() (time.Time, error)
- func (u *User) GetVerificationToken() string
- type VerifyReply
- type VerifyRequest
- type VerifySubscribeReply
- type VerifySubscribeRequest
- type WebauthnBeginLoginResponse
- type WebauthnBeginRegistrationResponse
- type WebauthnLoginResponse
- type WebauthnRegistrationRequest
- type WebauthnRegistrationResponse
Constants ¶
This section is empty.
Variables ¶
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") // 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("central-server 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 = errors.New("not authorized") )
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" )
Functions ¶
func IsConstraintError ¶
IsConstraintError returns true if the error resulted from a database constraint violation.
func IsForeignKeyConstraintError ¶
IsForeignKeyConstraintError reports if the error resulted from a database foreign-key constraint violation. e.g. parent row does not exist.
func IsUniqueConstraintError ¶
IsUniqueConstraintError reports if the error resulted from a DB uniqueness constraint violation. e.g. duplicate value in unique index.
Types ¶
type ForgotPasswordReply ¶
ForgotPasswordReply contains fields for a forgot password response
type ForgotPasswordRequest ¶
type ForgotPasswordRequest struct {
Email string `json:"email"`
}
ForgotPasswordRequest contains fields for a forgot password request
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 generated ent schema DBClient *ent.Client // RedisClient to interact with redis RedisClient *redis.Client // TM contains the token manager in order to validate auth requests TM *tokens.TokenManager // Logger provides the zap logger to do logging things from the handlers Logger *zap.SugaredLogger // 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 // EmailManager to handle sending emails EmailManager *emails.EmailManager // TaskMan manages tasks in a separate goroutine to allow for non blocking operations TaskMan *marionette.TaskManager // AnalyticsClient is the client used to send analytics events AnalyticsClient *analytics.EventManager // 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 }
Handler contains configuration options for handlers
func (*Handler) AddReadinessCheck ¶
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) BeginWebauthnLogin ¶
BeginWebauthnLogin is the request to begin a webauthn login
func (*Handler) BeginWebauthnRegistration ¶
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) (*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) FinishWebauthnLogin ¶
FinishWebauthnLogin is the request to finish a webauthn login
func (*Handler) FinishWebauthnRegistration ¶
FinishWebauthnRegistration is the request to finish a webauthn registration - this is where we get the credential created by the user back
func (*Handler) ForgotPassword ¶
ForgotPassword will send an forgot password email if the provided email exists
func (*Handler) GetGitHubLoginHandlers ¶
GetGitHubLoginHandlers returns the github login and callback handlers
func (*Handler) GetGoogleLoginHandlers ¶
GetGoogleLoginHandlers returns the google login and callback handlers
func (*Handler) IsAuthenticated ¶
IsAuthenticated checks the sessions to a valid session cookie
func (*Handler) LoginHandler ¶
LoginHandler validates the user credentials and returns a valid cookie this handler only supports username password login
func (*Handler) OauthRegister ¶
OauthRegister returns the TokenResponse for a verified authenticated external oauth user
func (*Handler) OpenIDConfiguration ¶
OpenIDConfiguration returns a JSON document with the OpenID configuration as defined by the OpenID Connect standard: https://connect2id.com/learn/openid-connect. This document helps clients understand how to authenticate with Khulnasoft.
func (*Handler) OrganizationInviteAccept ¶
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) RefreshHandler ¶
RefreshHandler allows users to refresh their access token using their refresh token.
func (*Handler) RegisterHandler ¶
RegisterHandler handles the registration of a new central-server 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 ¶
RequireLogin redirects unauthenticated users to the login route
func (*Handler) ResendEmail ¶
ResendEmail will resend an email verification email if the provided email exists
func (*Handler) ResetPassword ¶
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) SendOrgInvitationEmail ¶
SendOrgInvitationEmail sends an email inviting a user to join Khulnasoft and an existing organization
func (*Handler) SendPasswordResetRequestEmail ¶
SendPasswordResetRequestEmail Send an email to a user to request them to reset their password
func (*Handler) SendPasswordResetSuccessEmail ¶
SendPasswordResetSuccessEmail Send an email to a user to inform them that their password has been reset
func (*Handler) SendSubscriberEmail ¶
SendSubscriberEmail sends an email to confirm a user's subscription
func (*Handler) SendVerificationEmail ¶
SendVerificationEmail sends an email to a user to verify their email address
func (*Handler) SubscribeHandler ¶
SubscribeHandler is responsible for handling requests to the `/subscribe` endpoint It creates a new subscriber and sends a verification email to the subscriber this current only supports email subscriptions
func (*Handler) SwitchHandler ¶
SwitchHandler is responsible for handling requests to the `/switch` endpoint, and changing the user's logged in organization context
func (*Handler) UnsubscribeHandler ¶
UnsubscribeHandler is responsible for handling requests to the `/unsubscribe` endpoint and removes subscribers from the mailing list
func (*Handler) VerifyEmail ¶
VerifyEmail is the handler for the email 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 ¶
GetInviteExpires returns the expiration time of invite token
func (*Invite) GetInviteToken ¶
GetInviteToken returns the invitation token if its valid
type InviteReply ¶
type InviteReply struct { rout.Reply ID string `json:"user_id"` Email string `json:"email"` Message string `json:"message"` JoinedOrgID string `json:"joined_org_id"` Role string `json:"role"` }
InviteReply holds the fields that are sent on a response to an accepted invitation Note: there is no InviteRequest as this is handled via our graph interfaces
type InviteRequest ¶
type InviteRequest struct {
Token string `query:"token"`
}
InviteRequest holds the fields that should be included on a request to the `/invite` endpoint
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 LoginReply ¶
type LoginReply struct { rout.Reply AccessToken string `json:"access_token"` RefreshToken string `json:"refresh_token,omitempty"` Session string `json:"session,omitempty"` TokenType string `json:"token_type"` ExpiresIn int64 `json:"expires_in"` Message string `json:"message"` }
LoginReply holds response to successful authentication
type LoginRequest ¶
type LoginRequest struct { Username string `json:"username"` Password string `json:"password"` OTPCode string `json:"otp_code,omitempty"` }
LoginRequest to authenticate with the Khulnasoft Sever
type OauthProviderConfig ¶
type OauthProviderConfig struct { // RedirectURL is the URL that the OAuth2 client will redirect to after authentication with central-server RedirectURL string `json:"redirectUrl" koanf:"redirectUrl" default:"http://localhost:3001/api/auth/callback/central-server"` // 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 OauthTokenRequest ¶
type OauthTokenRequest struct { Name string `json:"name"` Email string `json:"email"` AuthProvider string `json:"authProvider"` ExternalUserID string `json:"externalUserId"` ExternalUserName string `json:"externalUserName"` ClientToken string `json:"clientToken"` }
OauthTokenRequest to authenticate an oauth user with the KhulnaSoft Server
type RefreshReply ¶
RefreshReply holds the fields that are sent on a response to the `/refresh` endpoint
type RefreshRequest ¶
type RefreshRequest struct {
RefreshToken string `json:"refresh_token"`
}
RefreshRequest holds the fields that should be included on a request to the `/refresh` endpoint
type RegisterReply ¶
type RegisterReply struct { rout.Reply ID string `json:"user_id"` Email string `json:"email"` Message string `json:"message"` Token string `json:"token"` }
RegisterReply holds the fields that are sent on a response to the `/register` endpoint
type RegisterRequest ¶
type RegisterRequest struct { FirstName string `json:"first_name"` LastName string `json:"last_name"` Email string `json:"email"` Password string `json:"password"` }
RegisterRequest holds the fields that should be included on a request to the `/register` endpoint
func (*RegisterRequest) Validate ¶
func (r *RegisterRequest) Validate() error
Validate the register request ensuring that the required fields are available and that the password is valid - an error is returned if the request is not correct. This method also performs some basic data cleanup, trimming whitespace
type ResendReply ¶
ResendReply holds the fields that are sent on a response to the `/resend` endpoint
type ResendRequest ¶
type ResendRequest struct {
Email string `json:"email"`
}
ResendRequest contains fields for a resend email verification request
type ResetPasswordReply ¶
ResetPasswordReply is the response returned from a non-successful password reset request on success, no content is returned (204)
type ResetPasswordRequest ¶
ResetPasswordRequest contains user input required to reset a user's password
type StatusReply ¶
StatusReply returns server status
type SubscribeReply ¶
SubscribeReply holds the fields that are sent on a response to the `/subscribe` endpoint
type SubscribeRequest ¶
type SubscribeRequest struct { Email string `query:"email"` OrganizationID string `query:"organization_id" json:",omitempty"` }
SubscribeRequest holds the fields that should be included on a request to the `/subscribe` endpoint
type SwitchOrganizationReply ¶
type SwitchOrganizationReply struct { rout.Reply AccessToken string `json:"access_token"` RefreshToken string `json:"refresh_token"` Session string `json:"session"` }
SwitchOrganizationReply holds the new authentication and session information for the user for the new organization
type SwitchOrganizationRequest ¶
type SwitchOrganizationRequest struct {
TargetOrganizationID string `json:"target_organization_id"`
}
SwitchOrganizationRequest contains the target organization ID being switched to
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 UnsubscribeReply ¶
UnsubscribeReply holds the fields that are sent on a response to the `/unsubscribe` endpoint
type UnsubscribeRequest ¶
type UnsubscribeRequest struct { Email string `query:"email"` OrganizationID string `query:"organization_id" json:",omitempty"` }
UnsubscribeRequest holds the fields that should be included on a request to the `/unsubscribe` endpoint
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 central-server user for the REST handlers for login, registration, verification, etc
func (*User) CreatePasswordResetToken ¶
CreatePasswordResetToken creates a new reset token for the user
func (*User) CreateVerificationToken ¶
CreateVerificationToken creates a new email verification token for the user
func (*User) GetPasswordResetExpires ¶
GetPasswordResetExpires returns the expiration time of password verification token
func (*User) GetPasswordResetToken ¶
GetPasswordResetToken returns the password reset token if its valid
func (*User) GetVerificationExpires ¶
GetVerificationExpires returns the expiration time of email verification token
func (*User) GetVerificationToken ¶
GetVerificationToken returns the verification token if its valid
type VerifyReply ¶
type VerifyReply struct { rout.Reply ID string `json:"user_id"` Email string `json:"email"` Token string `json:"token"` AccessToken string `json:"access_token"` RefreshToken string `json:"refresh_token,omitempty"` TokenType string `json:"token_type"` ExpiresIn int64 `json:"expires_in"` Message string `json:"message,omitempty"` }
VerifyReply holds the fields that are sent on a response to the `/verify` endpoint
type VerifyRequest ¶
type VerifyRequest struct {
Token string `query:"token"`
}
VerifyRequest holds the fields that should be included on a request to the `/verify` endpoint
type VerifySubscribeReply ¶
VerifySubscribeReply holds the fields that are sent on a response to the `/subscribe/verify` endpoint
type VerifySubscribeRequest ¶
type VerifySubscribeRequest struct {
Token string `query:"token"`
}
VerifySubscribeRequest holds the fields that should be included on a request to the `/subscribe/verify` endpoint
type WebauthnBeginLoginResponse ¶
type WebauthnBeginLoginResponse struct { Reply rout.Reply *protocol.CredentialAssertion Session string `json:"session,omitempty"` }
WebauthnBeginLoginResponse is the response to begin a webauthn login this includes the credential assertion options and the session token
type WebauthnBeginRegistrationResponse ¶
type WebauthnBeginRegistrationResponse struct { Reply rout.Reply *protocol.CredentialCreation Session string `json:"session,omitempty"` }
WebauthnRegistrationResponse is the response to begin a webauthn login this includes the credential creation options and the session token
type WebauthnLoginResponse ¶
type WebauthnLoginResponse struct { rout.Reply Message string `json:"message,omitempty"` AccessToken string `json:"access_token"` RefreshToken string `json:"refresh_token,omitempty"` Session string `json:"session,omitempty"` TokenType string `json:"token_type"` }
WebauthnRegistrationResponse is the response after a successful webauthn login
type WebauthnRegistrationRequest ¶
WebauthnRegistrationRequest is the request to begin a webauthn login
type WebauthnRegistrationResponse ¶
type WebauthnRegistrationResponse struct { rout.Reply Message string `json:"message,omitempty"` AccessToken string `json:"access_token"` RefreshToken string `json:"refresh_token,omitempty"` Session string `json:"session,omitempty"` TokenType string `json:"token_type"` }
WebauthnRegistrationResponse is the response after a successful webauthn registration
Source Files
¶
- doc.go
- email.go
- ent.go
- errors.go
- forgotpassword.go
- handlers.go
- invite.go
- login.go
- logout.go
- oauth_login.go
- oauth_register.go
- readiness.go
- refresh.go
- register.go
- resendemail.go
- resetpassword.go
- static.go
- subscribe.go
- switch.go
- unsubscribe.go
- userinfo.go
- users.go
- verifyemail.go
- verifysubscribe.go
- webauthn.go