Add token creation methods
Signed-off-by: Nikolai Rodionov <allanger@badhouseplants.net>
This commit is contained in:
45
internal/helpers/token/token.go
Normal file
45
internal/helpers/token/token.go
Normal 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
|
||||
}
|
||||
16
internal/helpers/token/token_test.go
Normal file
16
internal/helpers/token/token_test.go
Normal 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_"))
|
||||
}
|
||||
Reference in New Issue
Block a user