-
-
Notifications
You must be signed in to change notification settings - Fork 7
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
refactor: Creare RandomPassword in random_utils and use in `slu rando…
…m password`
- Loading branch information
1 parent
46e64ea
commit c1ce0fd
Showing
2 changed files
with
64 additions
and
52 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,60 @@ | ||
package random_utils | ||
|
||
import ( | ||
"fmt" | ||
"strings" | ||
"unicode" | ||
) | ||
|
||
func RandomPassword() (string, error) { | ||
i := 0 | ||
for { | ||
s := RandomString(16, ALL) | ||
if containsLowercase(s) && containsUpercase(s) && containsDigit(s) { | ||
return addUnderscores(s), nil | ||
} | ||
if i > 20 { | ||
return "", fmt.Errorf("cannot generate password") | ||
} | ||
} | ||
} | ||
|
||
func containsLowercase(s string) bool { | ||
for _, r := range s { | ||
if unicode.IsLower(r) { | ||
return true | ||
} | ||
} | ||
return false | ||
} | ||
|
||
func containsUpercase(s string) bool { | ||
for _, r := range s { | ||
if unicode.IsLower(r) { | ||
return true | ||
} | ||
} | ||
return false | ||
} | ||
|
||
func containsDigit(s string) bool { | ||
for _, r := range s { | ||
if unicode.IsDigit(r) { | ||
return true | ||
} | ||
} | ||
return false | ||
} | ||
|
||
func addUnderscores(input string) string { | ||
var blocks []string | ||
for i := 0; i < len(input); i += 4 { | ||
end := i + 4 | ||
if end > len(input) { | ||
end = len(input) | ||
} | ||
blocks = append(blocks, input[i:end]) | ||
} | ||
|
||
return strings.Join(blocks, "_") | ||
} |