UsernameFrom returns a best-effort username from the provided string. It first attempts to validate the incoming string, which will be returned if it is valid. It then will attempt to extract the username from an email address. If no success happens during these steps, a random username will be ret
(str string)
| 25 | // the username from an email address. If no success happens during |
| 26 | // these steps, a random username will be returned. |
| 27 | func UsernameFrom(str string) string { |
| 28 | if valid := NameValid(str); valid == nil { |
| 29 | return str |
| 30 | } |
| 31 | emailAt := strings.LastIndex(str, "@") |
| 32 | if emailAt >= 0 { |
| 33 | str = str[:emailAt] |
| 34 | } |
| 35 | str = usernameReplace.ReplaceAllString(str, "") |
| 36 | if valid := NameValid(str); valid == nil { |
| 37 | return str |
| 38 | } |
| 39 | return namesgenerator.NameDigitWith("-") |
| 40 | } |
| 41 | |
| 42 | // NameValid returns whether the input string is a valid name. |
| 43 | // It is a generic validator for any name (user, workspace, template, role name, etc.). |