hooks

package
v0.10.13 Latest Latest
Warning

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

Go to latest
Published: May 2, 2025 License: Apache-2.0 Imports: 69 Imported by: 0

Documentation

Overview

Package hooks is middleware to alter the graphql mutation

Index

Constants

View Source
const (
	// AdminsGroup is the group name for all organization admins and owner, these users have full read and write access in the organization
	AdminsGroup = "Admins"
	// ViewersGroup is the group name for all organization members that only have view access in the organization
	ViewersGroup = "Viewers"
	// AllMembersGroup is the group name for all members of the organization, no matter their role
	AllMembersGroup = "All Members"
)

Variables

View Source
var (
	// ErrInternalServerError is returned when an internal error occurs.
	ErrInternalServerError = errors.New("internal server error")
	// ErrInvalidInput is returned when the input is invalid.
	ErrInvalidInput = errors.New("invalid input")
	// ErrPersonalOrgsNoChildren is returned when personal org attempts to add a child org
	ErrPersonalOrgsNoChildren = errors.New("personal organizations are not allowed to have child organizations")
	// ErrPersonalOrgsNoMembers is returned when personal org attempts to add members
	ErrPersonalOrgsNoMembers = errors.New("personal organizations are not allowed to have members other than the owner")
	// ErrOrgOwnerCannotBeDeleted is returned when an org owner is attempted to be deleted
	ErrOrgOwnerCannotBeDeleted = errors.New("organization owner cannot be deleted, it must be transferred to a new owner first")
	// ErrPersonalOrgsNoUser is returned when personal org has no user associated, so no permissions can be added
	ErrPersonalOrgsNoUser = errors.New("personal organizations missing user association")
	// ErrUserNotInOrg is returned when a user is not a member of an organization when trying to add them to a group
	ErrUserNotInOrg = errors.New("user not in organization")
	// ErrUnsupportedFGARole is returned when a role is assigned that is not supported in our fine grained authorization system
	ErrUnsupportedFGARole = errors.New("unsupported role")
	// ErrMissingRole is returned when an update request is made that contains no role
	ErrMissingRole = errors.New("missing role in update")
	// ErrUserAlreadyOrgMember is returned when an user attempts to be invited to an org they are already a member of
	ErrUserAlreadyOrgMember = errors.New("user already member of organization")
	// ErrUserAlreadySubscriber is returned when an user attempts to subscribe to an organization but is already a subscriber
	ErrUserAlreadySubscriber = errors.New("user already a subscriber")
	// ErrEmailRequired is returned when an email is required but not provided
	ErrEmailRequired = errors.New("email is required but not provided")
	// ErrMaxAttempts is returned when a user has reached the max attempts to resend an invitation to an org
	ErrMaxAttempts = errors.New("too many attempts to resend org invitation")
	// ErrMaxSubscriptionAttempts is returned when a user has reached the max attempts to subscribe to an org
	ErrMaxSubscriptionAttempts = errors.New("too many attempts to resend org subscription email")
	// ErrMissingRecipientEmail is returned when an email is required but not provided
	ErrMissingRecipientEmail = errors.New("recipient email is required but not provided")
	// ErrMissingRequiredName is returned when a name is required but not provided
	ErrMissingRequiredName = errors.New("name or display name is required but not provided")
	// ErrTooManyAvatarFiles is returned when a user attempts to upload more than one avatar file
	ErrTooManyAvatarFiles = errors.New("too many avatar files uploaded, only one is allowed")
	// ErrFailedToRegisterListener is returned when a listener fails to register
	ErrFailedToRegisterListener = errors.New("failed to register listener")
	// ErrNoControls is returned when a subcontrol has no controls assigned
	ErrNoControls = errors.New("subcontrol must have at least one control assigned")
	// ErrUnableToCast is returned when a type assertion fails
	ErrUnableToCast = errors.New("unable to cast")
	// ErrNoSubscriptions is returned when an organization has no subscriptions
	ErrNoSubscriptions = errors.New("organization has no subscriptions")
	// ErrTooManySubscriptions is returned when an organization has too many subscriptions
	ErrTooManySubscriptions = errors.New("organization has too many subscriptions")
	// ErrTooManyPrices is returned when an organization has too many subscriptions
	ErrTooManyPrices = errors.New("organization has too many prices on a subscription")
	// ErrNoPrices is returned when a subscription has no price
	ErrNoPrices = errors.New("subscription has no price")
	// ErrManagedGroup is returned when a user attempts to modify a managed group
	ErrManagedGroup = errors.New("managed groups cannot be modified")
	// ErrMaxAttemptsOrganization is returned when the max attempts have been reached to create an organization via onboarding
	ErrMaxAttemptsOrganization = errors.New("too many attempts to create organization")
	// ErrEmailDomainNotAllowed is returned when an email domain is not allowed to be used for an organization
	ErrEmailDomainNotAllowed = errors.New("email domain not allowed in organization")
	// ErrUserNotFound is returned when a user is not found in the system
	ErrUserNotFound = errors.New("user not found")
)
View Source
var OrgSubscriptionCreate = fmt.Sprintf("%s.%s", entgen.TypeOrgSubscription, entgen.OpCreate.String())
View Source
var OrganizationDelete = fmt.Sprintf("%s.%s", entgen.TypeOrganization, entgen.OpDelete.String())
View Source
var OrganizationDeleteOne = fmt.Sprintf("%s.%s", entgen.TypeOrganization, entgen.OpDeleteOne.String())
View Source
var OrganizationSettingUpdateOne = fmt.Sprintf("%s.%s", entgen.TypeOrganizationSetting, entgen.OpUpdateOne.String())

OrganizationSettingCreate and OrganizationSettingUpdateOne are the topics for the organization setting events; formatted as `type.operation`

Functions

func AddOrDeletePublicStandardTuple added in v0.8.3

func AddOrDeletePublicStandardTuple(ctx context.Context, m *generated.StandardMutation) (bool, bool, error)

AddOrDeletePublicStandardTuple determines whether to add or delete a standard tuple based on the mutation operation and field values.

Parameters: - ctx: The context for the operation. - m: The StandardMutation containing the mutation details.

Returns: - add: A boolean indicating whether to add the tuple. - delete: A boolean indicating whether to delete the tuple. - err: An error if any occurred during the operation.

The function handles the following mutation operations: - OpCreate: Adds the tuple if both systemOwned and isPublic are true. - OpDelete, OpDeleteOne: Deletes the tuple. - OpUpdateOne: Deletes the tuple if it's a soft delete or if isPublic fields has changed. Adds the tuple if both fields are true. - OpUpdate: Deletes the tuple if isPublic field has been cleared. Adds the tuple if both fields are true.

func AddPostMutationHook added in v0.5.0

func AddPostMutationHook[T any](hook func(ctx context.Context, v T) error)

The `AddPostMutationHook` function is used to add a post-mutation hook to the list of runtime hooks. This function takes a hook function as a parameter, which will be executed after a mutation operation is performed. The hook function is expected to take a context and a value of type `T` as input parameters and return an error if any

func Decrypt

func Decrypt(ctx context.Context, k *secrets.Keeper, u *generated.Hush) error

Decrypt decrypts the secret value

func EmitEventHook added in v0.4.1

func EmitEventHook(e *Eventer) ent.Hook

EmitEventHook emits an event to the event pool when a mutation is performed

func GetObjectIDFromEntValue added in v0.6.13

func GetObjectIDFromEntValue(m ent.Value) (string, error)

GetObjectIDFromEntValue extracts the object id from a generic ent value return type this function should be called after the mutation has been successful

func GetObjectIDsFromMutation added in v0.7.3

func GetObjectIDsFromMutation(ctx context.Context, m GenericMutation, v ent.Value) ([]string, error)

GetObjectIDsFromMutation gets the object ids from the mutation, if it is a create it will use the ent.Value to get the id, requiring the mutation be executed first For updates, it will use the `IDs()` function to get the IDs by querying the database and returning the entity ids that match the mutation's predicate.

func GetObjectTypeFromEntMutation added in v0.6.13

func GetObjectTypeFromEntMutation(m ent.Mutation) string

GetObjectTypeFromEntMutation gets the object type from the ent mutation

func HookContact added in v0.6.21

func HookContact() ent.Hook

HookContact runs on contact create mutations

func HookControlImplementation added in v0.8.10

func HookControlImplementation() ent.Hook

HookControlImplementation sets default values for the control implementation

func HookCreateAPIToken

func HookCreateAPIToken() ent.Hook

HookCreateAPIToken runs on api token mutations and sets the owner id

func HookCreatePersonalAccessToken

func HookCreatePersonalAccessToken() ent.Hook

HookCreatePersonalAccessToken runs on access token mutations and sets the owner id

func HookDeleteUser

func HookDeleteUser() ent.Hook

HookDeleteUser runs on user deletions to clean up personal organizations

func HookEmailVerificationToken

func HookEmailVerificationToken() ent.Hook

HookEmailVerificationToken runs on email verification mutations and sets expires

func HookEnableTFA

func HookEnableTFA() ent.Hook

HookEnableTFA is a hook that generates the tfa secrets if the totp setting is set to allowed

func HookEntityCreate

func HookEntityCreate() ent.Hook

HookEntityCreate runs on entity mutations to set default values that are not provided

func HookEvidenceFiles added in v0.6.19

func HookEvidenceFiles() ent.Hook

HookEvidenceFiles runs on evidence mutations to check for uploaded files

func HookGroup

func HookGroup() ent.Hook

HookGroup runs on group mutations to set default values that are not provided

func HookGroupAuthz

func HookGroupAuthz() ent.Hook

HookGroupAuthz runs on group mutations to setup or remove relationship tuples

func HookGroupMembers

func HookGroupMembers() ent.Hook

func HookGroupPermissionsTuples added in v0.6.21

func HookGroupPermissionsTuples() ent.Hook

HookGroupPermissionsTuples is a hook that adds group permissions tuples for the object being created this is the reverse edge of the object owned tuples, meaning these run on group mutations whereas the other hooks run on the object mutations

func HookGroupSettingVisibility added in v0.7.0

func HookGroupSettingVisibility() ent.Hook

HookGroupSettingVisibility is a hook that updates the conditional tuples for group settings based on the visibility setting changing the initial tuple is set up on group creation

func HookHush

func HookHush() ent.Hook

HookHush runs on invite create mutations

func HookInvite

func HookInvite() ent.Hook

HookInvite runs on invite create mutations

func HookInviteAccepted

func HookInviteAccepted() ent.Hook

HookInviteAccepted adds the user to the organization when the status is accepted

func HookManagedGroups added in v0.6.11

func HookManagedGroups() ent.Hook

HookManagedGroups runs on group mutations to prevent updates to managed groups

func HookMembershipSelf added in v0.6.23

func HookMembershipSelf(table string) ent.Hook

HookMembershipSelf is a hook that runs on membership mutations to prevent users from updating their own membership

func HookNoteFiles added in v0.8.9

func HookNoteFiles() ent.Hook

HookNoteFiles runs on note mutations to check for uploaded files

func HookObjectOwnedTuples added in v0.3.4

func HookObjectOwnedTuples(parents []string, ownerRelation string) ent.Hook

HookObjectOwnedTuples is a hook that adds object owned tuples for the object being created given a set of parent id fields, it will add the user and parent permissions to the object on creation by default, it will always add a user permission to the object ownerRelation should normally be set to fgax.ParentRelation, but in some cases this is set to owner to account for different inherited permissions from parent objects vs. the user/service owner of the object (see notes as an example)

func HookOnboarding added in v0.6.24

func HookOnboarding() ent.Hook

HookOnboarding runs on onboarding mutations to create the organization and settings

func HookOrgMembers

func HookOrgMembers() ent.Hook

func HookOrgMembersDelete

func HookOrgMembersDelete() ent.Hook

HookOrgMembersDelete is a hook that runs during the delete operation of an org membership

func HookOrgOwnedTuples added in v0.4.2

func HookOrgOwnedTuples() ent.Hook

HookOrgOwnedTuples is a hook that adds organization owned tuples for the object being created it will add the user and parent (organization owner_id) permissions to the object on creation by default, it will always add an admin user permission to the object

func HookOrganization

func HookOrganization() ent.Hook

HookOrganization runs on org mutations to set default values that are not provided

func HookOrganizationCreatePolicy added in v0.7.0

func HookOrganizationCreatePolicy() ent.Hook

HookOrganizationCreatePolicy is used on organization and organization setting creation mutations if the allowed email domains are set, it will create a conditional tuple that restricts access to the organization based on the email domain

func HookOrganizationDelete

func HookOrganizationDelete() ent.Hook

HookOrganizationDelete runs on org delete mutations to ensure the org can be deleted

func HookOrganizationUpdatePolicy added in v0.7.0

func HookOrganizationUpdatePolicy() ent.Hook

HookOrganizationUpdatePolicy is used on organization setting mutations where the allowed email domains are set in the request it will update the conditional tuple that restricts access to the organization based on the email domain

func HookPasswordResetToken

func HookPasswordResetToken() ent.Hook

HookPasswordResetToken runs on reset token mutations and sets expires

func HookProgramAuthz added in v0.3.5

func HookProgramAuthz() ent.Hook

HookProgramAuthz runs on program mutations to setup or remove relationship tuples

func HookProgramMembers added in v0.3.5

func HookProgramMembers() ent.Hook

HookProgramMembers is a hook that ensures that the user is a member of the organization before allowing them to be added to a program TODO (sfunk): can this be generic across all edges with users that are owned by an organization?

func HookRelationTuples added in v0.4.2

func HookRelationTuples(objects map[string]string, relation fgax.Relation) ent.Hook

HookRelationTuples is a hook that adds tuples for the object being created the objects input is a map of object id fields to the object type these tuples based are based on the direct relation, e.g. a group#member to another object this is the reverse of the HookGroupPermissionsTuples

func HookRevisionUpdate added in v0.7.5

func HookRevisionUpdate() ent.Hook

HookRevisionUpdate is a hook that runs on update mutations to handle the revision of an object It checks if the revision is set, and if not, it retrieves the current revision from the database and bumps the patch version If the revision is cleared, it sets the revision to the default value

func HookStandardCreate added in v0.8.3

func HookStandardCreate() ent.Hook

HookStandardCreate sets default values on creation, such as setting the short name to the name if it's not provided

func HookStandardPublicAccessTuples added in v0.7.3

func HookStandardPublicAccessTuples() ent.Hook

HookStandardPublicAccessTuples adds tuples for publicly available standards based on the system owned and isPublic fields; and deletes them when the fields are cleared. see AddOrDeleteStandardTuple for details on how the fields are checked and it's called functions for specifics on mutation types

func HookSubcontrolCreate added in v0.8.9

func HookSubcontrolCreate() ent.Hook

HookSubcontrolCreate sets default values for the subcontrol on creation

func HookSubcontrolUpdate added in v0.5.0

func HookSubcontrolUpdate() ent.Hook

HookSubcontrolUpdate ensures that there is at least 1 control assigned to the subcontrol

func HookSubscriberCreate added in v0.8.4

func HookSubscriberCreate() ent.Hook

HookSubscriberCreate runs on subscriber create mutations

func HookSubscriberUpdated added in v0.8.4

func HookSubscriberUpdated() ent.Hook

HookSubscriberUpdated runs on subscriber update mutations to set the active status to false if the user is unsubscribed

func HookTaskCreate added in v0.3.4

func HookTaskCreate() ent.Hook

HookTaskCreate runs on task create mutations to set default values that are not provided this will set the assigner to the current user if it is not provided

func HookTaskPermissions added in v0.7.1

func HookTaskPermissions() ent.Hook

HookTaskPermissions runs on task create and update mutations to add and remove the assignee tuple

func HookUpdateAPIToken

func HookUpdateAPIToken() ent.Hook

HookUpdateAPIToken runs on api token update and redacts the token

func HookUpdateManagedGroups added in v0.6.11

func HookUpdateManagedGroups() ent.Hook

HookUpdateManagedGroups runs when org members are added to add the users to the system managed groups

func HookUpdatePersonalAccessToken

func HookUpdatePersonalAccessToken() ent.Hook

HookUpdatePersonalAccessToken runs on access token update and redacts the token

func HookUser

func HookUser() ent.Hook

HookUser runs on user mutations validate and hash the password and set default values that are not provided

func HookUserPermissions added in v0.3.1

func HookUserPermissions() ent.Hook

HookUserPermissions runs on user creations to add user _self permissions these are used for parent inherited relations on other objects in the system

func HookUserSetting

func HookUserSetting() ent.Hook

HookUserSetting runs on user settings mutations and validates input on update

func HookVerifyTFA added in v0.6.12

func HookVerifyTFA() ent.Hook

HookVerifyTFA is a hook that will generate recovery codes and enable TFA for a user if the TFA has been verified

func HookWebauthnDelete added in v0.10.10

func HookWebauthnDelete() ent.Hook

HookWebauthnDelete runs on passkey delete mutations to ensure that we update the user's settings if needed

func IsUniqueConstraintError

func IsUniqueConstraintError(err error) bool

IsUniqueConstraintError reports if the error resulted from a DB uniqueness constraint violation. e.g. duplicate value in unique index.

func MetricsHook added in v0.9.0

func MetricsHook() ent.Hook

MetricsHook inits the collectors with count total at beginning, error on mutation error and a duration after the mutation

func RegisterGlobalHooks added in v0.4.1

func RegisterGlobalHooks(client *entgen.Client, e *Eventer)

RegisterGlobalHooks registers global event hooks for the entdb client and expects a pointer to an Eventer

func RegisterListeners added in v0.4.1

func RegisterListeners(e *Eventer) error

RegisterListeners is currently used to globally register what listeners get applied on the entdb client

func SetNewRevision added in v0.7.5

func SetNewRevision(ctx context.Context, mut MutationWithRevision) error

SetNewRevision sets the new revision for a mutation based on the current revision and the revision bump If the revision is set, it does nothing If the revision is not set, it retrieves the current revision from the database and bumps the version based on the revision bump If there is no revision bump set, it bumps the patch version

Types

type AvatarMutation added in v0.6.10

type AvatarMutation interface {
	SetAvatarLocalFileID(s string)
	ID() (id string, exists bool)
	Type() string
}

AvatarMutation is an interface for setting the local file ID for an avatar

type EventID added in v0.4.1

type EventID struct {
	ID string `json:"id,omitempty"`
}

EventID is used to marshall and unmarshall the ID out of a ent mutation

type Eventer added in v0.5.0

type Eventer struct {
	Emitter   *soiree.EventPool
	Listeners []soiree.Listener
	Topics    map[string]any
}

Eventer is a wrapper struct for having a soiree as well as a list of listeners

func NewEventer added in v0.5.0

func NewEventer(opts ...EventerOpts) *Eventer

NewEventer creates a new Eventer with the provided options

func NewEventerPool added in v0.5.0

func NewEventerPool(client interface{}) *Eventer

NewEventerPool initializes a new Eventer and takes a client to be used as the client for the soiree pool

type EventerOpts added in v0.5.0

type EventerOpts (func(*Eventer))

EventerOpts is a functional options wrapper

func WithEventerEmitter added in v0.5.0

func WithEventerEmitter(emitter *soiree.EventPool) EventerOpts

WithEventerEmitter sets the emitter for the Eventer if there's an existing soiree pool that needs to be passed in

func WithEventerListeners added in v0.5.0

func WithEventerListeners(topic string, listeners []soiree.Listener) EventerOpts

WithEventerListeners takes a single topic and appends an array of listeners to the Eventer

func WithEventerTopics added in v0.5.0

func WithEventerTopics(topics map[string]any) EventerOpts

WithEventerTopics sets the topics for the Eventer

type GenericMutation added in v0.7.1

type GenericMutation interface {
	ID() (id string, exists bool)
	IDs(ctx context.Context) ([]string, error)
	Type() string
	Op() ent.Op
	Client() *generated.Client
}

GenericMutation is an interface for getting a mutation ID and type

type ManagedContextKey added in v0.6.11

type ManagedContextKey struct{}

ManagedContextKey is the context key name for managed group updates

type MutationMember added in v0.6.23

type MutationMember interface {
	UserIDs() []string
	UserID() (string, bool)
	ID() (string, bool)
	IDs(ctx context.Context) ([]string, error)
}

MutationMember is an interface that can be implemented by a member mutation to get IDs

type MutationWithRevision added in v0.7.5

type MutationWithRevision interface {
	Revision() (string, bool)
	RevisionCleared() bool
	OldRevision(ctx context.Context) (string, error)
	SetRevision(s string)

	GenericMutation
}

MutationWithRevision is an interface that defines the methods required for a mutation to be able to handle revisions It includes methods for getting and setting the revision

type OrgMember added in v0.6.11

type OrgMember struct {
	// UserID is the user ID of the org member
	UserID string
	// Role is the role of the org member
	Role enums.Role
	// OrgID is the organization ID of the org member
	OrgID string
}

OrgMember is a struct to hold the org member details

Jump to

Keyboard shortcuts

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