forked from kyma-incubator/compass
/
generator.go
executable file
·39 lines (30 loc) · 906 Bytes
/
generator.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package tokens
import (
"crypto/rand"
"encoding/base64"
"github.com/kyma-incubator/compass/components/connector/internal/apperrors"
)
type TokenGenerator interface {
NewToken() (string, apperrors.AppError)
}
type tokenGenerator struct {
tokenLength int
}
func NewTokenGenerator(tokenLength int) TokenGenerator {
return &tokenGenerator{tokenLength: tokenLength}
}
func (tg *tokenGenerator) NewToken() (string, apperrors.AppError) {
return generateRandomString(tg.tokenLength)
}
func generateRandomBytes(number int) ([]byte, apperrors.AppError) {
bytes := make([]byte, number)
_, err := rand.Read(bytes)
if err != nil {
return nil, apperrors.Internal("Failed to generate random bytes: %s", err)
}
return bytes, nil
}
func generateRandomString(length int) (string, apperrors.AppError) {
bytes, err := generateRandomBytes(length)
return base64.URLEncoding.EncodeToString(bytes), err
}