VictoriaMetrics/lib/auth/auth.go
Dmytro Kozlov a266e3e136
lib/auth: add tests for NewToken function (#2921)
* lib/auth: add tests from NewToken function

* lib/auth: update test, fix problem with type conversion

* lib/auth: update test description

* lib/auth: simplify failure tests
2022-08-07 23:15:23 +03:00

36 lines
867 B
Go

package auth
import (
"fmt"
"strconv"
"strings"
)
// Token contains settings for request processing
type Token struct {
ProjectID uint32
AccountID uint32
}
// NewToken returns new Token for the given authToken
func NewToken(authToken string) (*Token, error) {
tmp := strings.Split(authToken, ":")
if len(tmp) > 2 {
return nil, fmt.Errorf("unexpected number of items in authToken %q; got %d; want 1 or 2", authToken, len(tmp))
}
var at Token
accountID, err := strconv.ParseUint(tmp[0], 10, 32)
if err != nil {
return nil, fmt.Errorf("cannot parse accountID from %q: %w", tmp[0], err)
}
at.AccountID = uint32(accountID)
if len(tmp) > 1 {
projectID, err := strconv.ParseUint(tmp[1], 10, 32)
if err != nil {
return nil, fmt.Errorf("cannot parse projectID from %q: %w", tmp[1], err)
}
at.ProjectID = uint32(projectID)
}
return &at, nil
}