get.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package policy
  2. import (
  3. "errors"
  4. "fmt"
  5. "net/http"
  6. "github.com/porter-dev/porter/api/server/handlers"
  7. "github.com/porter-dev/porter/api/server/shared"
  8. "github.com/porter-dev/porter/api/server/shared/apierrors"
  9. "github.com/porter-dev/porter/api/server/shared/config"
  10. "github.com/porter-dev/porter/api/server/shared/requestutils"
  11. "github.com/porter-dev/porter/api/types"
  12. "github.com/porter-dev/porter/internal/models"
  13. "gorm.io/gorm"
  14. )
  15. type PolicyGetHandler struct {
  16. handlers.PorterHandlerReadWriter
  17. }
  18. func NewPolicyGetHandler(
  19. config *config.Config,
  20. decoderValidator shared.RequestDecoderValidator,
  21. writer shared.ResultWriter,
  22. ) *PolicyGetHandler {
  23. return &PolicyGetHandler{
  24. PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
  25. }
  26. }
  27. func (p *PolicyGetHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  28. proj, _ := r.Context().Value(types.ProjectScope).(*models.Project)
  29. // get the token id from the request
  30. policyID, reqErr := requestutils.GetURLParamString(r, types.URLParamPolicyID)
  31. if reqErr != nil {
  32. p.HandleAPIError(w, r, reqErr)
  33. return
  34. }
  35. policy, err := p.Repo().Policy().ReadPolicy(proj.ID, policyID)
  36. if err != nil {
  37. if errors.Is(err, gorm.ErrRecordNotFound) {
  38. p.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(
  39. fmt.Errorf("policy with id %s not found in project", policyID),
  40. http.StatusNotFound,
  41. ))
  42. return
  43. }
  44. p.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  45. return
  46. }
  47. res, err := policy.ToAPIPolicyType()
  48. if err != nil {
  49. p.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  50. return
  51. }
  52. p.WriteResult(w, r, res)
  53. }