validate.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package saml
  2. import (
  3. "errors"
  4. "fmt"
  5. "net/http"
  6. "net/mail"
  7. "strings"
  8. "github.com/porter-dev/porter/api/server/handlers"
  9. "github.com/porter-dev/porter/api/server/shared"
  10. "github.com/porter-dev/porter/api/server/shared/apierrors"
  11. "github.com/porter-dev/porter/api/server/shared/config"
  12. "github.com/porter-dev/porter/api/types"
  13. "gorm.io/gorm"
  14. )
  15. type ValidateSAMLHandler struct {
  16. handlers.PorterHandlerReadWriter
  17. }
  18. func NewValidateSAMLHandler(
  19. config *config.Config,
  20. decoderValidator shared.RequestDecoderValidator,
  21. writer shared.ResultWriter,
  22. ) *ValidateSAMLHandler {
  23. return &ValidateSAMLHandler{
  24. PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
  25. }
  26. }
  27. func (h *ValidateSAMLHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  28. request := &types.ValidateSAMLRequest{}
  29. if ok := h.DecodeAndValidate(w, r, request); !ok {
  30. return
  31. }
  32. addr, err := mail.ParseAddress(request.Email)
  33. if err != nil {
  34. h.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(fmt.Errorf("invalid email address"), http.StatusBadRequest))
  35. return
  36. }
  37. domain := addr.Address[strings.Index(addr.Address, "@")+1:]
  38. integ, err := h.Repo().SAMLIntegration().ValidateSAMLIntegration(domain)
  39. if err != nil {
  40. if errors.Is(err, gorm.ErrRecordNotFound) {
  41. h.HandleAPIError(w, r, apierrors.NewErrNotFound(fmt.Errorf("no SAML integration found for this email")))
  42. return
  43. }
  44. h.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  45. return
  46. }
  47. http.Redirect(w, r, integ.SignOnURL, http.StatusFound)
  48. }