Skip to content

Commit

Permalink
optimizing EncodeUserIdentifier (#415)
Browse files Browse the repository at this point in the history
* move regex compilation out of EncodeUserIdentifier

Signed-off-by: Francesco Ilario <[email protected]>

* remove regexp from EncodeUserIdentifier

Signed-off-by: Francesco Ilario <[email protected]>

---------

Signed-off-by: Francesco Ilario <[email protected]>
Co-authored-by: Alexey Kazakov <[email protected]>
  • Loading branch information
filariow and alexeykazakov authored Mar 19, 2024
1 parent 038a1e6 commit fde6df9
Showing 1 changed file with 24 additions and 18 deletions.
42 changes: 24 additions & 18 deletions pkg/signup/service/signup_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,7 @@ import (
)

const (
DNS1123NameMaximumLength = 63
DNS1123NotAllowedCharacters = "[^-a-z0-9]"
DNS1123NotAllowedStartCharacters = "^[^a-z0-9]+"
DNS1123NotAllowedEndCharacters = "[^a-z0-9]+$"
DNS1123NameMaximumLength = 63

// NoSpaceKey is the query key for specifying whether the UserSignup should be created without a Space
NoSpaceKey = "no-space"
Expand Down Expand Up @@ -236,20 +233,8 @@ func extractEmailHost(email string) string {
// resources. If a change is absolutely required, then all existing UserSignup instances must be migrated
// to the new value
func EncodeUserIdentifier(subject string) string {
// Convert to lower case
encoded := strings.ToLower(subject)

// Remove all invalid characters
nameNotAllowedChars := regexp.MustCompile(DNS1123NotAllowedCharacters)
encoded = nameNotAllowedChars.ReplaceAllString(encoded, "")

// Remove invalid start characters
nameNotAllowedStartChars := regexp.MustCompile(DNS1123NotAllowedStartCharacters)
encoded = nameNotAllowedStartChars.ReplaceAllString(encoded, "")

// Remove invalid end characters
nameNotAllowedEndChars := regexp.MustCompile(DNS1123NotAllowedEndCharacters)
encoded = nameNotAllowedEndChars.ReplaceAllString(encoded, "")
// Sanitize subject to be compliant with DNS labels format (RFC-1123)
encoded := sanitizeDNS1123(subject)

// Add a checksum prefix if the encoded value is different to the original subject value
if encoded != subject {
Expand All @@ -264,6 +249,27 @@ func EncodeUserIdentifier(subject string) string {
return encoded
}

func sanitizeDNS1123(str string) string {
// convert to lowercase
lstr := strings.ToLower(str)

// remove unwanted characters
b := strings.Builder{}
for _, r := range lstr {
switch {
case r >= '0' && r <= '9':
fallthrough
case r >= 'a' && r <= 'z':
fallthrough
case r == '-':
b.WriteRune(r)
}
}

// remove leading and trailing '-'
return strings.Trim(b.String(), "-")
}

// Signup reactivates the deactivated UserSignup resource or creates a new one with the specified username and userID
// if doesn't exist yet.
func (s *ServiceImpl) Signup(ctx *gin.Context) (*toolchainv1alpha1.UserSignup, error) {
Expand Down

0 comments on commit fde6df9

Please sign in to comment.