invite.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package authz
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "github.com/porter-dev/porter/api/server/shared/apierrors"
  7. "github.com/porter-dev/porter/api/server/shared/config"
  8. "github.com/porter-dev/porter/api/types"
  9. "github.com/porter-dev/porter/internal/models"
  10. "gorm.io/gorm"
  11. )
  12. type InviteScopedFactory struct {
  13. config *config.Config
  14. }
  15. func NewInviteScopedFactory(
  16. config *config.Config,
  17. ) *InviteScopedFactory {
  18. return &InviteScopedFactory{config}
  19. }
  20. func (p *InviteScopedFactory) Middleware(next http.Handler) http.Handler {
  21. return &InviteScopedMiddleware{next, p.config}
  22. }
  23. type InviteScopedMiddleware struct {
  24. next http.Handler
  25. config *config.Config
  26. }
  27. func (p *InviteScopedMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  28. // read the project to check scopes
  29. proj, _ := r.Context().Value(types.ProjectScope).(*models.Project)
  30. // get the invite id from the URL param context
  31. reqScopes, _ := r.Context().Value(types.RequestScopeCtxKey).(map[types.PermissionScope]*types.RequestAction)
  32. inviteID := reqScopes[types.InviteScope].Resource.UInt
  33. invite, err := p.config.Repo.Invite().ReadInvite(proj.ID, inviteID)
  34. if err != nil {
  35. if err == gorm.ErrRecordNotFound {
  36. apierrors.HandleAPIError(p.config.Logger, p.config.Alerter, w, r, apierrors.NewErrForbidden(
  37. fmt.Errorf("invite with id %d not found in project %d", inviteID, proj.ID),
  38. ), true)
  39. } else {
  40. apierrors.HandleAPIError(p.config.Logger, p.config.Alerter, w, r, apierrors.NewErrInternal(err), true)
  41. }
  42. return
  43. }
  44. ctx := NewInviteContext(r.Context(), invite)
  45. r = r.Clone(ctx)
  46. p.next.ServeHTTP(w, r)
  47. }
  48. func NewInviteContext(ctx context.Context, invite *models.Invite) context.Context {
  49. return context.WithValue(ctx, types.InviteScope, invite)
  50. }