Skip to content

Commit

Permalink
feat(api): contact template validation (#1100)
Browse files Browse the repository at this point in the history
  • Loading branch information
almostinf authored Oct 3, 2024
1 parent b4d3745 commit 1fd8c2f
Show file tree
Hide file tree
Showing 11 changed files with 442 additions and 73 deletions.
30 changes: 30 additions & 0 deletions api/controller/contact.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"errors"
"fmt"
"regexp"
"time"

"github.com/go-graphite/carbonapi/date"
Expand Down Expand Up @@ -53,6 +54,7 @@ func GetContactById(database moira.Database, contactID string) (*dto.Contact, *a
func CreateContact(
dataBase moira.Database,
auth *api.Authorization,
contactsTemplate []api.WebContact,
contact *dto.Contact,
userLogin,
teamID string,
Expand All @@ -74,6 +76,7 @@ func CreateContact(
Type: contact.Type,
Value: contact.Value,
}

if contactData.ID == "" {
uuid4, err := uuid.NewV4()
if err != nil {
Expand All @@ -90,19 +93,26 @@ func CreateContact(
}
}

if err := validateContact(contactsTemplate, contactData); err != nil {
return api.ErrorInvalidRequest(err)
}

if err := dataBase.SaveContact(&contactData); err != nil {
return api.ErrorInternalServer(err)
}

contact.User = contactData.User
contact.ID = contactData.ID
contact.TeamID = contactData.Team

return nil
}

// UpdateContact updates notification contact for current user.
func UpdateContact(
dataBase moira.Database,
auth *api.Authorization,
contactsTemplate []api.WebContact,
contactDTO dto.Contact,
contactData moira.ContactData,
) (dto.Contact, *api.ErrorResponse) {
Expand All @@ -119,6 +129,10 @@ func UpdateContact(
contactData.Team = contactDTO.TeamID
}

if err := validateContact(contactsTemplate, contactData); err != nil {
return contactDTO, api.ErrorInvalidRequest(err)
}

if err := dataBase.SaveContact(&contactData); err != nil {
return contactDTO, api.ErrorInternalServer(err)
}
Expand Down Expand Up @@ -265,3 +279,19 @@ func isAllowedToUseContactType(auth *api.Authorization, userLogin string, contac

return isAllowedContactType || isAdmin || !isAuthEnabled
}

func validateContact(contactsTemplate []api.WebContact, contact moira.ContactData) error {
var validationPattern string
for _, contactTemplate := range contactsTemplate {
if contactTemplate.ContactType == contact.Type {
validationPattern = contactTemplate.ValidationRegex
break
}
}

if matched, err := regexp.MatchString(validationPattern, contact.Value); !matched || err != nil {
return fmt.Errorf("contact value doesn't match regex: '%s'", validationPattern)
}

return nil
}
Loading

0 comments on commit 1fd8c2f

Please sign in to comment.