mirror of
https://github.com/steveiliop56/tinyauth.git
synced 2026-01-25 00:32:34 +00:00
feat: implement basic oidc functionality
This commit is contained in:
@@ -1,8 +1,11 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"math"
|
||||
"math/big"
|
||||
"net"
|
||||
"regexp"
|
||||
"strings"
|
||||
@@ -105,3 +108,28 @@ func GenerateUUID(str string) string {
|
||||
uuid := uuid.NewSHA1(uuid.NameSpaceURL, []byte(str))
|
||||
return uuid.String()
|
||||
}
|
||||
|
||||
// These could definitely be improved A LOT but at least they are cryptographically secure
|
||||
func GetRandomString(length int) (string, error) {
|
||||
if length < 1 {
|
||||
return "", errors.New("length must be greater than 0")
|
||||
}
|
||||
b := make([]byte, length)
|
||||
_, err := rand.Read(b)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
state := base64.RawURLEncoding.EncodeToString(b)
|
||||
return state[:length], nil
|
||||
}
|
||||
|
||||
func GetRandomInt(length int) (int64, error) {
|
||||
if length < 1 {
|
||||
return 0, errors.New("length must be greater than 0")
|
||||
}
|
||||
a, err := rand.Int(rand.Reader, big.NewInt(int64(math.Pow(10, float64(length)))))
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return a.Int64(), nil
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package utils_test
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strconv"
|
||||
"testing"
|
||||
|
||||
"github.com/steveiliop56/tinyauth/internal/utils"
|
||||
@@ -147,3 +148,25 @@ func TestGenerateUUID(t *testing.T) {
|
||||
id3 := utils.GenerateUUID("differentstring")
|
||||
assert.Assert(t, id1 != id3)
|
||||
}
|
||||
|
||||
func TestGetRandomString(t *testing.T) {
|
||||
// Test with normal length
|
||||
state, err := utils.GetRandomString(16)
|
||||
assert.NilError(t, err)
|
||||
assert.Equal(t, 16, len(state))
|
||||
|
||||
// Test with zero length
|
||||
state, err = utils.GetRandomString(0)
|
||||
assert.Error(t, err, "length must be greater than 0")
|
||||
}
|
||||
|
||||
func TestGetRandomInt(t *testing.T) {
|
||||
// Test with normal length
|
||||
state, err := utils.GetRandomInt(16)
|
||||
assert.NilError(t, err)
|
||||
assert.Equal(t, 16, len(strconv.Itoa(int(state))))
|
||||
|
||||
// Test with zero length
|
||||
state, err = utils.GetRandomInt(0)
|
||||
assert.Error(t, err, "length must be greater than 0")
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user