Skip to content

Commit

Permalink
Add {{ randomPassword }}
Browse files Browse the repository at this point in the history
  • Loading branch information
envygeeks committed Nov 23, 2018
1 parent 08558ea commit 77e1236
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 0 deletions.
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,14 @@ hello {
{{ env [key] }}
```

### randomPassword

*Generate an alphanumeric password using cryptographically derived random numbers.*

```
{{ randomPassword [length] }}
```

## An Example

Given you did
Expand Down
40 changes: 40 additions & 0 deletions template/helpers/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,11 @@
package helpers

import (
"crypto/rand"
"fmt"
"io"
"log"
"math/big"
"os"
"regexp"
"strconv"
Expand Down Expand Up @@ -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,
Expand All @@ -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,
Expand Down
7 changes: 7 additions & 0 deletions template/helpers/helpers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

0 comments on commit 77e1236

Please sign in to comment.