utils

package
v0.0.0-...-c214036 Latest Latest
Warning

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

Go to latest
Published: Feb 26, 2024 License: AGPL-3.0 Imports: 22 Imported by: 0

Documentation

Index

Constants

View Source
const AuthCookieName = "Authorization"

AuthCookieName is the name of the cookie used to store the session token.

View Source
const AuthDuration = time.Hour * 24 * 7 // 1 week

AuthDuration is the duration of the Authorization cookie it's also used for the token expiration.

Variables

View Source
var (
	ErrInternal           = NewError(http.StatusInternalServerError, "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.StatusUnauthorized, "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."},
			},
		},
	})
)

Recurring Errors

View Source
var (
	ErrInvalidHash         = fmt.Errorf("the encoded hash is not in the correct format")
	ErrIncompatibleVersion = fmt.Errorf("incompatible version of argon2")
)

Predefined errors for hash validation and processing.

View Source
var DefaultArgonParams = ArgonParams{
	// contains filtered or unexported fields
}

DefaultArgonParams provides default settings for Argon2 parameters.

Functions

func ClearAuth

func ClearAuth(c *fiber.Ctx)

ClearAuth clears the Authorization cookie by setting the MaxAge to 0 and replacing the value with an empty string.

func CompareHash

func CompareHash(password, encodedHash string) (match bool, err error)

CompareHash checks if a password matches the hash.

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 CreateHash

func CreateHash(password string) (encodedHash string, err error)

CreateHash generates a hash for a given password using Argon2.

func ErrorHandler

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

func GenerateRandomBytes

func GenerateRandomBytes(n uint32) ([]byte, error)

GenerateRandomBytes creates a slice of random bytes of specified length.

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 GetUserID

func GetUserID(c *fiber.Ctx) string

GetUserID returns the session from the Authorization cookie.

func ParseAndValidate

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

ParseAndValidate parses the request body into the provided struct and validates it. Returns a detailed error if validation fails.

func SetAuthCookie

func SetAuthCookie(c *fiber.Ctx, token string, expiration time.Time)

SetAuthCookie sets the Authorization cookie with the token and the 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 ArgonParams

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

ArgonParams defines the parameters for the Argon2 hashing algorithm.

func DecodeHash

func DecodeHash(encodedHash string) (p *ArgonParams, salt, hash []byte, err error)

DecodeHash extracts the parameters, salt, and hash from an encoded hash string.

type Error

type Error struct {
	Status  int           `json:"-"`
	Code    string        `json:"code"`
	Message string        `json:"message"`
	Details *ErrorDetails `json:"details"`
}

Error is the structure for an error responses.

func NewError

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

NewError is used to create a new error with the given status, message, and details and optional code.

func (Error) Error

func (e Error) Error() string

Error returns the data within the error for internal use.

type ErrorDetails

type ErrorDetails struct {
	Fields []ErrorField `json:"fields"`
}

ErrorDetails provides details about the error, such as fields but can be expanded to include more details.

type ErrorField

type ErrorField struct {
	Name   string   `json:"name"`
	Errors []string `json:"errors"`
}

ErrorField is a field that has an error, this is filled in by the validator.

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.

Jump to

Keyboard shortcuts

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