handlers

package
v0.2.3 Latest Latest
Warning

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

Go to latest
Published: Jan 2, 2024 License: Apache-2.0 Imports: 30 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")

	// ErrDuplicate is returned when the request violates the unique constraints
	ErrDuplicate = errors.New("unique constraint violated on model")

	// ErrMissingRelation is returned when a foreign key restricted is violated
	ErrMissingRelation = errors.New("foreign key relation violated on model")

	// ErrNotNull is returned when a field is required but not provided
	ErrNotNull = errors.New("not null constraint violated on model")

	// ErrConstraint is returned when a database constraint is violated
	ErrConstraint = errors.New("database constraint violated")

	// 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("datum 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")

	// ErrNoAuthUser is returned when the user couldn't be identified by the request
	ErrNoAuthUser = errors.New("could not identify authenticated user in request")
)

Functions

func ErrorResponse added in v0.2.3

func ErrorResponse(err interface{}) *echo.HTTPError

ErrorResponse constructs a new response for an error or simply returns unsuccessful

func IsConstraintError added in v0.2.2

func IsConstraintError(err error) bool

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

func IsForeignKeyConstraintError added in v0.2.2

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 added in v0.2.2

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 ForgotPasswordRequest added in v0.2.3

type ForgotPasswordRequest struct {
	Email string `json:"email"`
}

ForgotPasswordRequest contains fields for a forgot password request

type Handler

type Handler struct {
	// DBClient to interact with the generated ent schema
	DBClient *ent.Client
	// TM contains the token manager in order to validate auth requests
	TM *tokens.TokenManager
	// CookieDomain is the domain set in cookie for authenticated requests, defaults to datum.net
	CookieDomain string
	// 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
	// SendGridConfig containing the email configuration
	SendGridConfig *emails.Config

	// EmailURL contains the urls used within emails
	EmailURL *URLConfig
	// TaskMan manages tasks in a separate goroutine to allow for non blocking operations
	TaskMan *marionette.TaskManager
	// SessionManager manages sessions for users
	SM *scs.SessionManager
	// contains filtered or unexported fields
}

Handler contains configuration options for handlers

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) ForgotPassword added in v0.2.3

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

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

func (*Handler) JWKSWellKnownHandler

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

JWKSWellKnownHandler provides the JWK used to verify all Datum-issued JWTs

func (*Handler) LoginHandler

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

LoginHandler validates the user credentials and returns a valid cookie this only supports username password login today (not oauth)

func (*Handler) NewEmailManager added in v0.2.2

func (h *Handler) NewEmailManager() error

NewEmailManager is responsible for initializing and configuring the email manager used for sending emails

func (*Handler) NewTestEmailManager added in v0.2.3

func (h *Handler) NewTestEmailManager() error

NewTestEmailManager is responsible for initializing and configuring the email manager used for sending emails but does not send emails, should be used in tests

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 added in v0.2.2

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

RegisterHandler handles the registration of a new datum 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) ResendEmail added in v0.2.3

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

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

func (*Handler) SendPasswordResetRequestEmail added in v0.2.2

func (h *Handler) SendPasswordResetRequestEmail(user *User) error

SendPasswordResetRequestEmail Send an email to a user to request them to reset their password TODO: implement handler to use this and send password reset email

func (*Handler) SendPasswordResetSuccessEmail added in v0.2.2

func (h *Handler) SendPasswordResetSuccessEmail(user *User) error

SendPasswordResetSuccessEmail Send an email to a user to inform them that their password has been reset

func (*Handler) SendVerificationEmail added in v0.2.2

func (h *Handler) SendVerificationEmail(user *User) error

func (*Handler) VerifyEmail added in v0.2.3

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

type InvalidEmailConfigError added in v0.2.2

type InvalidEmailConfigError struct {
	// RequiredField that is missing
	RequiredField string
}

InvalidEmailConfigError is returned when an invalid url configuration was provided

func (*InvalidEmailConfigError) Error added in v0.2.2

func (e *InvalidEmailConfigError) Error() string

Error returns the InvalidEmailConfigError in string format

type LoginRequest added in v0.2.3

type LoginRequest struct {
	Username string `json:"username"`
	Password string `json:"password"`
}

LoginRequest to authenticate with the Datum Sever

type MissingRequiredFieldError added in v0.2.2

type MissingRequiredFieldError struct {
	// RequiredField that is missing
	RequiredField string
}

MissingRequiredFieldError is returned when a required field was not provided in a request

func (*MissingRequiredFieldError) Error added in v0.2.2

func (e *MissingRequiredFieldError) Error() string

Error returns the InvalidEmailConfigError in string format

type RefreshRequest

type RefreshRequest struct {
	RefreshToken string `json:"refresh_token"`
}

type RegisterReply added in v0.2.2

type RegisterReply struct {
	ID      string `json:"user_id"`
	Email   string `json:"email"`
	Message string `json:"message"`
	// TODO: remove this before go live, we shouldn't actually return the token here
	Token string `json:"token"`
}

RegisterReply holds the fields that are sent on a response to the `/register` endpoint

type RegisterRequest added in v0.2.2

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 added in v0.2.2

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 added in v0.2.3

type ResendReply struct {
	Message string `json:"message"`
}

ResendReply holds the fields that are sent on a response to the `/resend` endpoint

type ResendRequest added in v0.2.3

type ResendRequest struct {
	Email string `json:"email"`
}

ResendRequest contains fields for a resend email verification request

type Response

type Response struct {
	StatusCode int         `json:"status,omitempty"`
	Message    string      `json:"message,omitempty"`
	Data       interface{} `json:"data,omitempty"`
}

type URLConfig added in v0.2.2

type URLConfig struct {
	Base   string `split_words:"true" default:"https://app.datum.net"`
	Verify string `split_words:"true" default:"/v1/verify"`
	Invite string `split_words:"true" default:"/v1/invite"`
	Reset  string `split_words:"true" default:"/v1/reset"`
}

URLConfig for the datum registration

func (URLConfig) InviteURL added in v0.2.2

func (c URLConfig) InviteURL(token string) (string, error)

InviteURL Construct an invite URL from the token.

func (URLConfig) ResetURL added in v0.2.2

func (c URLConfig) ResetURL(token string) (string, error)

ResetURL constructs a reset URL from the token.

func (URLConfig) Validate added in v0.2.2

func (c URLConfig) Validate() error

func (URLConfig) VerifyURL added in v0.2.2

func (c URLConfig) VerifyURL(token string) (string, error)

VerifyURL constructs a verify URL from the token.

type User

type User struct {
	ID                       string
	FirstName                string
	LastName                 string
	Name                     string
	Email                    string
	EmailVerificationExpires sql.NullString
	EmailVerificationToken   sql.NullString
	EmailVerificationSecret  []byte
	PasswordResetExpires     sql.NullString
	PasswordResetToken       sql.NullString
	PasswordResetSecret      []byte
}

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

func (*User) CreateResetToken added in v0.2.2

func (u *User) CreateResetToken() error

CreateResetToken creates a new reset token for the user

func (*User) CreateVerificationToken added in v0.2.2

func (u *User) CreateVerificationToken() error

CreateVerificationToken creates a new email verification token for the user

func (*User) GetPasswordResetExpires added in v0.2.3

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

GetPasswordResetExpires returns the expiration time of password verification token

func (*User) GetPasswordResetToken added in v0.2.3

func (u *User) GetPasswordResetToken() string

GetPasswordResetToken returns the password reset token if its valid

func (*User) GetVerificationExpires added in v0.2.2

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

GetVerificationExpires returns the expiration time of email verification token

func (*User) GetVerificationToken added in v0.2.2

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