From cb439a126aa6a2728e423bcfd0d5e948337b8ddb Mon Sep 17 00:00:00 2001 From: ᴜɴᴋɴᴡᴏɴ Date: Tue, 14 Apr 2020 09:41:54 +0800 Subject: 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 --- internal/strutil/strutil.go | 29 +++++++++++++++++++++++++++++ internal/strutil/strutil_test.go | 14 ++++++++++++++ 2 files changed, 43 insertions(+) (limited to 'internal/strutil') 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 + } +} -- cgit v1.2.3