Skip to content

Commit

Permalink
add web config to contact handler and validation web config
Browse files Browse the repository at this point in the history
  • Loading branch information
almostinf committed Sep 26, 2024
1 parent d51fffa commit c8fc4b4
Show file tree
Hide file tree
Showing 11 changed files with 447 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,
webConfig *api.WebConfig,
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(webConfig, 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,
webConfig *api.WebConfig,
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(webConfig, 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(webConfig *api.WebConfig, contact moira.ContactData) error {
var validationPattern string
for _, contactTemplate := range webConfig.Contacts {
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 c8fc4b4

Please sign in to comment.