Add token creation methods

Signed-off-by: Nikolai Rodionov <allanger@badhouseplants.net>
This commit is contained in:
2026-05-13 21:32:10 +02:00
parent 35c6689a2c
commit eb339f5495
5 changed files with 104 additions and 2 deletions

View File

@@ -0,0 +1,45 @@
// Package token should be used to generate secure tokens
package token
import (
"fmt"
"github.com/db-operator/can-haz-password/password"
)
const (
TokenPrefix = "sft"
)
// GenerateToken generates secure password string
func GenerateToken() (string, error) {
generator := password.NewGenerator(newTokenRule())
password, err := generator.Generate()
if err != nil {
return "", err
}
return fmt.Sprintf("%s_%s", TokenPrefix, password), nil
}
// Minimum length of 20 characters, maximum length of 30 characters.
// Varied composition including special characters and uppercase and lowercase letters.
// Excludes consecutive dashes (for hybris compatibility) and uses only url safe special characters.
type tokenRule struct{}
func newTokenRule() *tokenRule {
return &tokenRule{}
}
func (r *tokenRule) Config() *password.Configuration {
return &password.Configuration{
Length: 40,
CharacterClasses: []password.CharacterClassConfiguration{ // codespell:ignore
{Characters: password.LowercaseCharacters + password.UppercaseCharacters, Minimum: 10},
{Characters: password.DigitCharacters, Minimum: 8},
},
}
}
func (r *tokenRule) Valid(password []rune) bool {
return true
}

View File

@@ -0,0 +1,16 @@
package token_test
import (
"strings"
"testing"
"gitea.badhouseplants.net/softplayer/softplayer-backend/internal/helpers/token"
"github.com/stretchr/testify/assert"
)
func TestUnitTokenGeneration(t *testing.T) {
token, err := token.GenerateToken()
assert.NoError(t, err)
assert.Len(t, token, 44)
assert.True(t, strings.HasPrefix(token, "sft_"))
}