Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(api): contact template validation #1100

Merged
merged 4 commits into from
Oct 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading