Untitled

mail@pastecode.io avatar
unknown
golang
a year ago
735 B
0
Indexable
Never

package privacyrules

import (
	"context"

	"github.com/vitorfalcaor/reInvest/ent"
	"github.com/vitorfalcaor/reInvest/ent/privacy"
	"github.com/vitorfalcaor/reInvest/viewer"
)

func AllowIfViewerIsOwner() privacy.QueryRule {
	return privacy.QueryRuleFunc(func(ctx context.Context, query ent.Query) error {
		var owner *ent.User
		ctx = privacy.DecisionContext(ctx, privacy.Allow)
		switch query := query.(type) {
		case *ent.OrderQuery:
			owner, _ = query.Clone().QueryOwner().Only(ctx)
		case *ent.ShareQuery:
			owner, _ = query.Clone().QueryOwner().Only(ctx)
		default:
			return privacy.Skip
		}
		vc := viewer.FromContext(ctx)
		if owner != nil && vc.GetID() == owner.ID {
			return privacy.Allow
		}
		return privacy.Skip
	})
}