diff options
author | ᴜɴᴋɴᴡᴏɴ <u@gogs.io> | 2020-04-14 09:41:54 +0800 |
---|---|---|
committer | GitHub <noreply@github.com> | 2020-04-14 09:41:54 +0800 |
commit | cb439a126aa6a2728e423bcfd0d5e948337b8ddb (patch) | |
tree | f7d09181fe5b96ea444f7544091673b3c668b9fe /internal/strutil | |
parent | 659acd48b1a131476fd98a54604fa6416b1cef9d (diff) |
db: add tests for two factors (#6099)
* Rename to TwoFactors.Create
* Use GORM to execute queries
* TwoFactor.GetByUserID
* Add tests
* Fix failing tests
* Add MD5 tests
* Add tests for RandomChars
Diffstat (limited to 'internal/strutil')
-rw-r--r-- | internal/strutil/strutil.go | 29 | ||||
-rw-r--r-- | internal/strutil/strutil_test.go | 14 |
2 files changed, 43 insertions, 0 deletions
diff --git a/internal/strutil/strutil.go b/internal/strutil/strutil.go index a2b84a20..b1de241f 100644 --- a/internal/strutil/strutil.go +++ b/internal/strutil/strutil.go @@ -5,6 +5,8 @@ package strutil import ( + "crypto/rand" + "math/big" "unicode" ) @@ -15,3 +17,30 @@ func ToUpperFirst(s string) string { } return "" } + +// RandomChars returns a generated string in given number of random characters. +func RandomChars(n int) (string, error) { + const alphanum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + + randomInt := func(max *big.Int) (int, error) { + r, err := rand.Int(rand.Reader, max) + if err != nil { + return 0, err + } + + return int(r.Int64()), nil + } + + buffer := make([]byte, n) + max := big.NewInt(int64(len(alphanum))) + for i := 0; i < n; i++ { + index, err := randomInt(max) + if err != nil { + return "", err + } + + buffer[i] = alphanum[index] + } + + return string(buffer), nil +} diff --git a/internal/strutil/strutil_test.go b/internal/strutil/strutil_test.go index d603533b..c4edf140 100644 --- a/internal/strutil/strutil_test.go +++ b/internal/strutil/strutil_test.go @@ -41,3 +41,17 @@ func TestToUpperFirst(t *testing.T) { }) } } + +func TestRandomChars(t *testing.T) { + cache := make(map[string]bool) + for i := 0; i < 100; i++ { + chars, err := RandomChars(10) + if err != nil { + t.Fatal(err) + } + if cache[chars] { + t.Fatalf("Duplicated chars %q", chars) + } + cache[chars] = true + } +} |