Skip to content

Commit

Permalink
refactor: Creare RandomPassword in random_utils and use in `slu rando…
Browse files Browse the repository at this point in the history
…m password`
  • Loading branch information
ondrejsika committed Apr 8, 2024
1 parent 46e64ea commit c1ce0fd
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 52 deletions.
56 changes: 4 additions & 52 deletions cmd/random/password/password.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ package password
import (
"fmt"
"log"
"strings"
"unicode"

random_cmd "github.com/sikalabs/slu/cmd/random"
"github.com/sikalabs/slu/utils/random_utils"
Expand All @@ -18,60 +16,14 @@ var Cmd = &cobra.Command{
Aliases: []string{"pwd", "passwd", "pass"},
Args: cobra.NoArgs,
Run: func(c *cobra.Command, args []string) {
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")
}
password, err := random_utils.RandomPassword()
if err != nil {
log.Fatal(err)
}
fmt.Println(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, "_")
}
60 changes: 60 additions & 0 deletions utils/random_utils/random_password_utils.go
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, "_")
}

0 comments on commit c1ce0fd

Please sign in to comment.