api

package
v0.0.0-...-449d51e Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2024 License: AGPL-3.0 Imports: 29 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// VerificationCodeLength is the length of the verification code in bytes
	VerificationCodeLength = 3
	// InvitationExpiration is the duration of the invitation code before it is
	// invalidated
	InvitationExpiration = 5 * 24 * time.Hour // 5 days
)

Variables

View Source
var (
	ErrUnauthorized                    = Error{Code: 40001, HTTPstatus: http.StatusUnauthorized, Err: fmt.Errorf("user not authorized")}
	ErrEmailMalformed                  = Error{Code: 40002, HTTPstatus: http.StatusBadRequest, Err: fmt.Errorf("email malformed")}
	ErrPasswordTooShort                = Error{Code: 40003, HTTPstatus: http.StatusBadRequest, Err: fmt.Errorf("password too short")}
	ErrMalformedBody                   = Error{Code: 40004, HTTPstatus: http.StatusBadRequest, Err: fmt.Errorf("malformed JSON body")}
	ErrDuplicateConflict               = Error{Code: 40901, HTTPstatus: http.StatusConflict, Err: fmt.Errorf("duplicate conflict")}
	ErrInvalidUserData                 = Error{Code: 40005, HTTPstatus: http.StatusBadRequest, Err: fmt.Errorf("invalid user data")}
	ErrCouldNotSignTransaction         = Error{Code: 40006, HTTPstatus: http.StatusBadRequest, Err: fmt.Errorf("could not sign transaction")}
	ErrInvalidTxFormat                 = Error{Code: 40007, HTTPstatus: http.StatusBadRequest, Err: fmt.Errorf("invalid transaction format")}
	ErrTxTypeNotAllowed                = Error{Code: 40008, HTTPstatus: http.StatusBadRequest, Err: fmt.Errorf("transaction type not allowed")}
	ErrOrganizationNotFound            = Error{Code: 40009, HTTPstatus: http.StatusNotFound, Err: fmt.Errorf("organization not found")}
	ErrMalformedURLParam               = Error{Code: 40010, HTTPstatus: http.StatusBadRequest, Err: fmt.Errorf("malformed URL parameter")}
	ErrNoOrganizationProvided          = Error{Code: 40011, HTTPstatus: http.StatusBadRequest, Err: fmt.Errorf("no organization provided")}
	ErrNoOrganizations                 = Error{Code: 40012, HTTPstatus: http.StatusNotFound, Err: fmt.Errorf("this user has not been assigned to any organization")}
	ErrInvalidOrganizationData         = Error{Code: 40013, HTTPstatus: http.StatusBadRequest, Err: fmt.Errorf("invalid organization data")}
	ErrUserNoVerified                  = Error{Code: 40014, HTTPstatus: http.StatusUnauthorized, Err: fmt.Errorf("user account not verified")}
	ErrUserAlreadyVerified             = Error{Code: 40015, HTTPstatus: http.StatusBadRequest, Err: fmt.Errorf("user account already verified")}
	ErrVerificationCodeExpired         = Error{Code: 40016, HTTPstatus: http.StatusUnauthorized, Err: fmt.Errorf("verification code expired")}
	ErrVerificationCodeValid           = Error{Code: 40017, HTTPstatus: http.StatusBadRequest, Err: fmt.Errorf("last verification code still valid")}
	ErrUserNotFound                    = Error{Code: 40018, HTTPstatus: http.StatusNotFound, Err: fmt.Errorf("user not found")}
	ErrInvitationExpired               = Error{Code: 40019, HTTPstatus: http.StatusUnauthorized, Err: fmt.Errorf("inviation code expired")}
	ErrNoOrganizationSubscription      = Error{Code: 40020, HTTPstatus: http.StatusNotFound, Err: fmt.Errorf("organization subscription not found")}
	ErrOganizationSubscriptionIncative = Error{Code: 40021, HTTPstatus: http.StatusBadRequest, Err: fmt.Errorf("organization subscription not active")}
	ErrNoDefaultPLan                   = Error{Code: 40022, HTTPstatus: http.StatusBadRequest, Err: fmt.Errorf("did not found default plan for organization")}
	ErPlanNotFound                     = Error{Code: 40023, HTTPstatus: http.StatusNotFound, Err: fmt.Errorf("plan not found")}

	ErrMarshalingServerJSONFailed  = Error{Code: 50001, HTTPstatus: http.StatusInternalServerError, Err: fmt.Errorf("marshaling (server-side) JSON failed")}
	ErrGenericInternalServerError  = Error{Code: 50002, HTTPstatus: http.StatusInternalServerError, Err: fmt.Errorf("internal server error")}
	ErrCouldNotCreateFaucetPackage = Error{Code: 50003, HTTPstatus: http.StatusInternalServerError, Err: fmt.Errorf("could not create faucet package")}
	ErrVochainRequestFailed        = Error{Code: 50004, HTTPstatus: http.StatusInternalServerError, Err: fmt.Errorf("vochain request failed")}
)

The custom Error type satisfies the error interface. Error() returns a human-readable description of the error.

Error codes in the 40001-49999 range are the user's fault, and they return HTTP Status 400 or 404 (or even 204), whatever is most appropriate.

Error codes 50001-59999 are the server's fault and they return HTTP Status 500 or 503, or something else if appropriate.

The initial list of errors were more or less grouped by topic, but the list grows with time in a random fashion. NEVER change any of the current error codes, only append new errors after the current last 4XXX or 5XXX If you notice there's a gap (say, error code 4010, 4011 and 4013 exist, 4012 is missing) DON'T fill in the gap, that code was used in the past for some error (not anymore) and shouldn't be reused. There's no correlation between Code and HTTP Status, for example the fact that Code 4045 returns HTTP Status 404 Not Found is just a coincidence

Do note that HTTPstatus 204 No Content implies the response body will be empty, so the Code and Message will actually be discarded, never sent to the client

View Source
var VerificationCodeExpiration = 3 * time.Minute

VerificationCodeExpiration is the duration of the verification code before it is invalidated

Functions

This section is empty.

Types

type API

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

API type represents the API HTTP server with JWT authentication capabilities.

func New

func New(conf *APIConfig) *API

New creates a new API HTTP server. It does not start the server. Use Start() for that.

func (*API) Start

func (a *API) Start()

Start starts the API HTTP server (non blocking).

type APIConfig

type APIConfig struct {
	Host        string
	Port        int
	Secret      string
	Chain       string
	DB          *db.MongoStorage
	Client      *apiclient.HTTPclient
	Account     *account.Account
	MailService notifications.NotificationService
	WebAppURL   string
	// FullTransparentMode if true allows signing all transactions and does not
	// modify any of them.
	FullTransparentMode bool
	// Stripe secrets
	StripeClient *stripe.StripeClient
	// Subscriptions permissions manager
	Subscriptions *subscriptions.Subscriptions
}

type AcceptOrganizationInvitation

type AcceptOrganizationInvitation struct {
	Code string    `json:"code"`
	User *UserInfo `json:"user"`
}

AcceptOrganizationInvitation is the request to accept an invitation to an organization.

type Error

type Error struct {
	Err        error
	Code       int
	HTTPstatus int
}

Error is used by handler functions to wrap errors, assigning a unique error code and also specifying which HTTP Status should be used.

func (Error) Error

func (e Error) Error() string

Error returns the Message contained inside the APIerror

func (Error) MarshalJSON

func (e Error) MarshalJSON() ([]byte, error)

MarshalJSON returns a JSON containing Err.Error() and Code. Field HTTPstatus is ignored.

Example output: {"error":"account not found","code":4003}

func (Error) With

func (e Error) With(s string) Error

With returns a copy of APIerror with the string appended at the end of e.Err

func (Error) WithErr

func (e Error) WithErr(err error) Error

WithErr returns a copy of APIerror with err.Error() appended at the end of e.Err

func (Error) Withf

func (e Error) Withf(format string, args ...any) Error

Withf returns a copy of APIerror with the Sprintf formatted string appended at the end of e.Err

func (Error) Write

func (e Error) Write(w http.ResponseWriter)

Write serializes a JSON msg using APIerror.Message and APIerror.Code and passes that to ctx.Send()

type LoginResponse

type LoginResponse struct {
	Token    string    `json:"token"`
	Expirity time.Time `json:"expirity"`
}

LoginResponse is the response of the login request which includes the JWT token

type MessageSignature

type MessageSignature struct {
	Address   string         `json:"address"`
	Payload   []byte         `json:"payload,omitempty"`
	Signature types.HexBytes `json:"signature,omitempty"`
}

MessageSignature is the struct that contains the payload and the signature. Its used to receive and return a signed message.

type MetadataKey

type MetadataKey string

MetadataKey is a type to define the key for the metadata stored in the context.

type OrganizationAddresses

type OrganizationAddresses struct {
	Addresses []string `json:"addresses"`
}

OrganizationAddresses is the struct that represents a list of addresses of organizations in the API.

type OrganizationInfo

type OrganizationInfo struct {
	Address      string                       `json:"address"`
	Website      string                       `json:"website"`
	CreatedAt    string                       `json:"createdAt"`
	Type         string                       `json:"type"`
	Size         string                       `json:"size"`
	Color        string                       `json:"color"`
	Subdomain    string                       `json:"subdomain"`
	Country      string                       `json:"country"`
	Timezone     string                       `json:"timezone"`
	Active       bool                         `json:"active"`
	Parent       *OrganizationInfo            `json:"parent"`
	Subscription *db.OrganizationSubscription `json:"subscription"`
	Counters     *db.OrganizationCounters     `json:"counters"`
}

Organization is the struct that represents an organization in the API

type OrganizationInvite

type OrganizationInvite struct {
	Email      string    `json:"email"`
	Role       string    `json:"role"`
	Expiration time.Time `json:"expiration"`
}

OrganizationInvite is the struct that represents an invitation to an organization in the API.

type OrganizationInviteList

type OrganizationInviteList struct {
	Invites []*OrganizationInvite `json:"pending"`
}

OrganizationInviteList is the struct that represents a list of invitations to organizations in the API.

type OrganizationMember

type OrganizationMember struct {
	Info *UserInfo `json:"info"`
	Role string    `json:"role"`
}

OrganizationMember is the struct that represents a members of organizations with his role in the API.

type OrganizationMembers

type OrganizationMembers struct {
	Members []*OrganizationMember `json:"members"`
}

OrganizationMembers is the struct that represents a list of members of organizations in the API.

type OrganizationRole

type OrganizationRole struct {
	Role            string `json:"role"`
	Name            string `json:"name"`
	WritePermission bool   `json:"writePermission"`
}

OrganizationRole is the struct that represents the role of an organization member in the API.

type OrganizationRoleList

type OrganizationRoleList struct {
	Roles []*OrganizationRole `json:"roles"`
}

OrganizationRoleList is the struct that represents a list of roles of an organization member in the API.

type OrganizationSubscriptionInfo

type OrganizationSubscriptionInfo struct {
	SubcriptionDetails *db.OrganizationSubscription `json:"subscriptionDetails"`
	Usage              *db.OrganizationCounters     `json:"usage"`
	Plan               *db.Plan                     `json:"plan"`
}

OrganizationSubscriptionInfo is the struct used to provide detailed information regaridng the subscription of an organization.

type OrganizationType

type OrganizationType struct {
	Type string `json:"type"`
	Name string `json:"name"`
}

OrganizationType is the struct that represents the type of an organization in the API.

type OrganizationTypeList

type OrganizationTypeList struct {
	Types []*OrganizationType `json:"types"`
}

OrganizationTypeList is the struct that represents a list of types of organizations in the API.

type TransactionData

type TransactionData struct {
	Address   string `json:"address"`
	TxPayload string `json:"txPayload"`
}

TransactionData is the struct that contains the data of a transaction to be signed, but also is used to return the signed transaction.

type UserInfo

type UserInfo struct {
	Email         string              `json:"email,omitempty"`
	Password      string              `json:"password,omitempty"`
	FirstName     string              `json:"firstName,omitempty"`
	LastName      string              `json:"lastName,omitempty"`
	Verified      bool                `json:"verified,omitempty"`
	Organizations []*UserOrganization `json:"organizations"`
}

UserInfo is the request to register a new user.

type UserOrganization

type UserOrganization struct {
	Role         string            `json:"role"`
	Organization *OrganizationInfo `json:"organization"`
}

UserOrganization is the struct that represents the organization of a user in the API, including the role of the user in the organization.

type UserPasswordReset

type UserPasswordReset struct {
	Email       string `json:"email"`
	Code        string `json:"code"`
	NewPassword string `json:"newPassword"`
}

type UserPasswordUpdate

type UserPasswordUpdate struct {
	OldPassword string `json:"oldPassword"`
	NewPassword string `json:"newPassword"`
}

UserPasswordUpdate is the request to update the password of a user.

type UserVerification

type UserVerification struct {
	Email      string    `json:"email,omitempty"`
	Code       string    `json:"code,omitempty"`
	Expiration time.Time `json:"expiration,omitempty"`
	Valid      bool      `json:"valid"`
}

UserVerificationRequest is the request to verify a user.

Jump to

Keyboard shortcuts

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