Skip to content

Commit

Permalink
feat(cmd/random/password): Generate password with random case and wit…
Browse files Browse the repository at this point in the history
…h underscores instead of dashes
  • Loading branch information
ondrejsika committed Sep 2, 2023
1 parent ac10b67 commit 59af796
Showing 1 changed file with 54 additions and 6 deletions.
60 changes: 54 additions & 6 deletions cmd/random/password/password.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ package password

import (
"fmt"
"log"
"strings"
"unicode"

random_cmd "github.com/sikalabs/slu/cmd/random"
"github.com/sikalabs/slu/utils/random_utils"
Expand All @@ -15,15 +18,60 @@ var Cmd = &cobra.Command{
Aliases: []string{"pwd", "passwd", "pass"},
Args: cobra.NoArgs,
Run: func(c *cobra.Command, args []string) {
fmt.Println(
random_utils.RandomString(4, random_utils.LOWER) + "-" +
random_utils.RandomString(4, random_utils.UPPER) + "-" +
random_utils.RandomString(4, random_utils.DIGITS) + "-" +
random_utils.RandomString(4, ""),
)
i := 0
for {
s := random_utils.RandomString(16, random_utils.ALL)
if containsLowercase(s) && containsUpercase(s) && containsDigit(s) {
fmt.Println(addUnderscores(s))
break
}
if i > 20 {
log.Fatalln("Cannot generate password")
}
}
},
}

func init() {
random_cmd.Cmd.AddCommand(Cmd)
}

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, "_")
}

0 comments on commit 59af796

Please sign in to comment.