lib

package
v0.0.0-...-1c7d376 Latest Latest
Warning

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

Go to latest
Published: Dec 19, 2023 License: AGPL-3.0 Imports: 25 Imported by: 0

Documentation

Index

Constants

View Source
const Version = "0.0.1"

Variables

View Source
var (
	ErrInternal           = NewError(http.StatusNotImplemented, "An internal server error occurred while attempting to process the request.", nil)
	ErrForbidden          = NewError(http.StatusForbidden, "You do not have permission to access the requested resource.", nil)
	ErrUnauthorised       = NewError(http.StatusUnauthorized, "You are not authorised to access this endpoint.", nil)
	ErrNotFound           = NewError(http.StatusNotFound, "The requested resource does not exist.", nil)
	ErrNotImplemented     = NewError(http.StatusNotImplemented, "A portion of this request has not been implemented.", nil)
	ErrInvalidCredentials = NewError(http.StatusBadRequest, "Invalid credentials. Please try again.", &ErrorDetails{
		Fields: []ErrorField{
			{Name: "email", Errors: []string{"Invalid credentials. Please try again."}},
			{Name: "password", Errors: []string{"Invalid credentials. Please try again."}},
		},
	})
	ErrInvalidCaptcha = NewError(http.StatusBadRequest, "The captcha response suggests this action was not performed by a human.", &ErrorDetails{
		Fields: []ErrorField{
			{Name: "captcha", Errors: []string{"The captcha response suggests this action was not performed by a human."}},
		},
	})
	ErrEmailExists = NewError(http.StatusConflict, "The email address provided has already been registered.", &ErrorDetails{
		Fields: []ErrorField{
			{Name: "email", Errors: []string{"The email address provided has already been registered."}},
		},
	})
)

Predefined errors for common API responses

View Source
var ArgonConfig = argon2id.Params{
	Memory:      64 * 1024,
	Iterations:  16,
	Parallelism: uint8(runtime.NumCPU()),
	SaltLength:  32,
	KeyLength:   128,
}
View Source
var BlankSuccess = Response{
	Success: true,
}

BlankSuccess provides a default successful response when no additional data is required.

View Source
var (
	DB *gorm.DB // DB is a global variable for the database connection
)

Functions

func CheckCaptcha

func CheckCaptcha(captcha string) error

CheckCaptcha verifies the reCAPTCHA response token.

func ClearAuth

func ClearAuth(c *fiber.Ctx)

ClearAuth removes the "Authorization" cookie from the client, effectively logging the user out.

func ComputeTOTP

func ComputeTOTP(secret string, timestamp int64) (string, error)

ComputeTOTP computes the TOTP value for a given secret and time, and returns an error if any.

func ErrorHandler

func ErrorHandler(c *fiber.Ctx, err error) error

ErrorHandler is a custom error handler for the Fiber application.

func FieldErrToMsg

func FieldErrToMsg(tag string, param string) string

FieldErrToMsg converts a validation tag and parameters to a user-friendly error message.

func GenerateSecureRandomBase32

func GenerateSecureRandomBase32(n int) (string, error)

GenerateSecureRandomBase32 generates a cryptographically secure random Base32 string of length n. It returns the generated string or an error if there was one.

func GenerateString

func GenerateString(length int) string

GenerateString produces a random string of the specified length.

func GenerateTOTP

func GenerateTOTP(secret string, stepType StepDurationType) (string, error)

GenerateTOTP provides a TOTP code for the current time and desired type (MFA or Email Verification).

func GetSession

func GetSession(c *fiber.Ctx) *models.Session

GetSession returns the session from the database using the auth token provided in the request.

func MigrateDB

func MigrateDB()

MigrateDB applies the auto migrations for the database models.

func NewDBTime

func NewDBTime() models.Timestamps

func ParseAndValidate

func ParseAndValidate(c *fiber.Ctx, body any) error

ParseAndValidate parses the request body into the given struct and performs validation.

func SetAuth

func SetAuth(c *fiber.Ctx, token string, exp time.Duration)

SetAuth sets the "Authorization" cookie to the provided token and expires it after the provided duration.

func ValidateTOTP

func ValidateTOTP(secret, code string, stepType StepDurationType) bool

ValidateTOTP verifies if the provided code matches the expected TOTP value for the given secret and duration type.

Types

type Error

type Error struct {
	Status  int           `json:"-"`                 // HTTP status code, not included in the response
	Code    string        `json:"code"`              // API-specific error code
	Message string        `json:"message"`           // Human-readable error message
	Details *ErrorDetails `json:"details,omitempty"` // Optional details about the error
}

Error represents a standardised error response for the API.

func NewError

func NewError(status int, message string, details *ErrorDetails, code ...string) Error

NewError creates a new Error with the provided status, message, and optional details.

func (Error) Error

func (e Error) Error() string

Error formats the error message string.

type ErrorDetails

type ErrorDetails struct {
	Fields []ErrorField `json:"fields,omitempty"` // Specific fields related to the error
	Debug  any          `json:"debug,omitempty"`  // Debug information, included only if debugging is enabled
}

ErrorDetails holds additional data about the error.

type ErrorField

type ErrorField struct {
	Name   string   `json:"name"`   // Name of the field
	Errors []string `json:"errors"` // List of error messages for the field
}

ErrorField provides detailed errors for specific fields in the request.

type Pagination

type Pagination struct {
	Page         int `json:"page"`          // The current page number
	PerPage      int `json:"per_page"`      // The number of items per page
	PreviousPage int `json:"previous_page"` // The previous page number, if applicable
	NextPage     int `json:"next_page"`     // The next page number, if applicable
	LastPage     int `json:"last_page"`     // The last page number based on total entries
	TotalEntries int `json:"total_entries"` // The total number of entries across all pages
}

Pagination details the structure for pagination metadata in list responses.

type Response

type Response struct {
	Success    bool        `json:"success"`              // Indicates if the request was successful
	Data       any         `json:"data,omitempty"`       // Holds the data payload of the response, if any
	Pagination *Pagination `json:"pagination,omitempty"` // Optional pagination details, included for list responses
}

Response represents the standard structure for API responses.

type SiteVerifyResponse

type SiteVerifyResponse struct {
	Success     bool      `json:"success"`      // Indicates if the captcha was successful
	Score       float64   `json:"score"`        // Score for the captcha action
	Action      string    `json:"action"`       // Action associated with the captcha
	ChallengeTS time.Time `json:"challenge_ts"` // Timestamp of the captcha challenge
	Hostname    string    `json:"hostname"`     // Hostname of the site where the captcha was solved
	ErrorCodes  []string  `json:"error-codes"`  // Any error codes returned by the verification
}

SiteVerifyResponse struct maps the JSON response from reCAPTCHA verification.

type StepDurationType

type StepDurationType int

StepDurationType defines the type of TOTP duration.

const (
	MFACode           StepDurationType = iota // For Multi-Factor Authentication.
	EmailVerification                         // For email code verification.
)

These constants represent the two types of durations.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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