github.com/greenpau/go-authcrunch@v1.1.4/internal/tests/random.go (about)

     1  // Copyright 2022 Paul Greenberg greenpau@outlook.com
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package tests
    16  
    17  import (
    18  	"crypto/rand"
    19  	"github.com/google/uuid"
    20  	"io"
    21  	mathrand "math/rand"
    22  	"strings"
    23  )
    24  
    25  // NewID returns a random ID to be used for user identification.
    26  func NewID() string {
    27  	return uuid.New().String()
    28  }
    29  
    30  // NewRandomString returns a random string.
    31  func NewRandomString(length int) string {
    32  	chars := []rune("abcdefghijklmnopqrstuvwxyz0123456789")
    33  	charsLen := byte(36)
    34  
    35  	if length == 0 {
    36  		length = 32
    37  	}
    38  
    39  	b := make([]byte, length)
    40  	if _, err := io.ReadFull(rand.Reader, b); err != nil {
    41  		var sb strings.Builder
    42  		for i := 0; i < length; i++ {
    43  			sb.WriteRune(chars[mathrand.Intn(len(chars))])
    44  		}
    45  		return sb.String()
    46  	}
    47  
    48  	for i, char := range b {
    49  		b[i] = byte(chars[char%charsLen])
    50  	}
    51  
    52  	return string(b)
    53  }