From 77e12367f3371afd52112d362ee91fdcfdae31dc Mon Sep 17 00:00:00 2001 From: Jordon Bedwell Date: Fri, 23 Nov 2018 10:45:18 -0600 Subject: [PATCH] Add {{ randomPassword }} --- README.md | 8 +++++++ template/helpers/helpers.go | 40 ++++++++++++++++++++++++++++++++ template/helpers/helpers_test.go | 7 ++++++ 3 files changed, 55 insertions(+) diff --git a/README.md b/README.md index 2759fe3..81f38df 100644 --- a/README.md +++ b/README.md @@ -248,6 +248,14 @@ hello { {{ env [key] }} ``` +### randomPassword + +*Generate an alphanumeric password using cryptographically derived random numbers.* + +``` +{{ randomPassword [length] }} +``` + ## An Example Given you did diff --git a/template/helpers/helpers.go b/template/helpers/helpers.go index c035b3a..2b559db 100644 --- a/template/helpers/helpers.go +++ b/template/helpers/helpers.go @@ -5,7 +5,11 @@ package helpers import ( + "crypto/rand" "fmt" + "io" + "log" + "math/big" "os" "regexp" "strconv" @@ -159,6 +163,41 @@ func (h *Helpers) TemplateExists(s string) bool { return false } +var ( + letters = []rune( + "01234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", + ) +) + +func rngCheck() { + buf := make([]byte, 1) + _, err := io.ReadFull(rand.Reader, buf) + if err != nil { + log.Fatalln(err) + } +} + +// RandPass generates a password using +// cryptographically derived random numbers +func (h *Helpers) RandomPassword(n uint) string { + rngCheck() + + l, b := int64(len(letters)), make([]rune, n) + for i := range b { + n, err := rand.Int(rand.Reader, big.NewInt(l)) + if err != nil { + log.Fatalln(err) + } + + nn := n.Int64() + ll := letters[nn] + b[i] = ll + } + + return string(b) +} + +// New creates a new Funcs, and registers them func New(t *template.Template) *Helpers { return (&Helpers{ template: t, @@ -173,6 +212,7 @@ func (h *Helpers) RegisterFuncs() *Helpers { "chomp": strings.Trim, "indent": h.Indent, "addSpace": h.AddSpace, + "randomPassword": h.RandomPassword, "templateString": h.TemplateString, "strippedTemplate": h.StrippedTemplate, "fixIndentedTemplate": h.FixIndentedTemplate, diff --git a/template/helpers/helpers_test.go b/template/helpers/helpers_test.go index 68260bf..866a49b 100644 --- a/template/helpers/helpers_test.go +++ b/template/helpers/helpers_test.go @@ -327,3 +327,10 @@ func TestTemplateExists(t *testing.T) { ts.description) } } + +func TestRandomPassword(t *testing.T) { + h := New(template.New("envp")) + actual := h.RandomPassword(12) + assert.Equal(t, 12, len(actual)) + assert.NotNil(t, actual) +}