add auth lib
This commit is contained in:
25
token/token.go
Normal file
25
token/token.go
Normal file
@@ -0,0 +1,25 @@
|
||||
package token
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
func GenerateURLSafe(size int) (string, error) {
|
||||
if size <= 0 {
|
||||
return "", fmt.Errorf("token size must be positive")
|
||||
}
|
||||
raw := make([]byte, size)
|
||||
if _, err := rand.Read(raw); err != nil {
|
||||
return "", fmt.Errorf("generate secure token: %w", err)
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString(raw), nil
|
||||
}
|
||||
|
||||
func HashSHA256(value string) string {
|
||||
sum := sha256.Sum256([]byte(value))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
38
token/token_test.go
Normal file
38
token/token_test.go
Normal file
@@ -0,0 +1,38 @@
|
||||
package token
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestGenerateURLSafe(t *testing.T) {
|
||||
t.Run("invalid size", func(t *testing.T) {
|
||||
if _, err := GenerateURLSafe(0); err == nil {
|
||||
t.Fatal("expected error for non-positive size")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("valid token decodes from raw url base64", func(t *testing.T) {
|
||||
got, err := GenerateURLSafe(32)
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateURLSafe: %v", err)
|
||||
}
|
||||
if got == "" {
|
||||
t.Fatal("expected non-empty token")
|
||||
}
|
||||
raw, err := base64.RawURLEncoding.DecodeString(got)
|
||||
if err != nil {
|
||||
t.Fatalf("token was not raw-url-base64: %v", err)
|
||||
}
|
||||
if len(raw) != 32 {
|
||||
t.Fatalf("expected 32 random bytes, got %d", len(raw))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestHashSHA256(t *testing.T) {
|
||||
const expected = "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
|
||||
if got := HashSHA256("hello"); got != expected {
|
||||
t.Fatalf("expected %q, got %q", expected, got)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user