snapshot of https://github.com/traggo/server.git (master, 2026-09-16; blobs > 131072B omitted)
Some checks failed
build / build (push) Failing after 3s
Some checks failed
build / build (push) Failing after 3s
This commit is contained in:
43
auth/rand/random.go
Normal file
43
auth/rand/random.go
Normal file
@@ -0,0 +1,43 @@
|
||||
package rand
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
var (
|
||||
chars = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
|
||||
|
||||
randRead = rand.Read
|
||||
)
|
||||
|
||||
func init() {
|
||||
// exits with 1 when crypto/rand is not available
|
||||
Token(1)
|
||||
}
|
||||
|
||||
func randBytes(count int) ([]byte, error) {
|
||||
bytes := make([]byte, count)
|
||||
_, err := randRead(bytes)
|
||||
return bytes, err
|
||||
}
|
||||
|
||||
// Token returns a random token.
|
||||
func Token(count int) string {
|
||||
bytes, err := randBytes(count)
|
||||
if err != nil {
|
||||
log.Panic().Msg("crypto/rand is not available")
|
||||
}
|
||||
return bytesToString(bytes, count)
|
||||
}
|
||||
|
||||
func bytesToString(bytes []byte, count int) string {
|
||||
token := make([]rune, count)
|
||||
|
||||
for index, item := range bytes {
|
||||
token[index] = chars[int(item)%len(chars)]
|
||||
}
|
||||
|
||||
return string(token)
|
||||
}
|
||||
30
auth/rand/random_test.go
Normal file
30
auth/rand/random_test.go
Normal file
@@ -0,0 +1,30 @@
|
||||
package rand
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestToken(t *testing.T) {
|
||||
for i := 1; i < 10; i++ {
|
||||
assert.Len(t, Token(i), i)
|
||||
}
|
||||
assert.Len(t, Token(120), 120)
|
||||
assert.Len(t, Token(222), 222)
|
||||
assert.Len(t, Token(555665), 555665)
|
||||
}
|
||||
|
||||
func TestToken_panics(t *testing.T) {
|
||||
old := randRead
|
||||
defer func() {
|
||||
randRead = old
|
||||
}()
|
||||
randRead = func(b []byte) (n int, err error) {
|
||||
return 0, errors.New("oops")
|
||||
}
|
||||
assert.Panics(t, func() {
|
||||
Token(1)
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user