zrok/controller/util.go

59 lines
1.5 KiB
Go
Raw Normal View History

2022-07-25 19:17:52 +02:00
package controller
import (
"crypto/rand"
2022-07-27 19:38:35 +02:00
"crypto/x509"
2022-07-25 19:17:52 +02:00
"encoding/hex"
2022-07-27 20:50:46 +02:00
errors2 "github.com/go-openapi/errors"
"github.com/openziti-test-kitchen/zrok/rest_model_zrok"
2022-07-27 19:38:35 +02:00
"github.com/openziti/edge/rest_management_api_client"
"github.com/openziti/edge/rest_util"
2022-07-25 19:17:52 +02:00
"github.com/pkg/errors"
)
func ZrokAuthenticate(token string) (*rest_model_zrok.Principal, error) {
2022-07-29 21:28:40 +02:00
tx, err := str.Begin()
if err != nil {
return nil, err
}
defer func() { _ = tx.Rollback() }()
2022-07-29 21:28:40 +02:00
if a, err := str.FindAccountWithToken(token, tx); err == nil {
2022-07-28 18:12:50 +02:00
principal := rest_model_zrok.Principal{
ID: int64(a.Id),
Token: a.Token,
Username: a.Username,
}
return &principal, nil
} else {
2022-07-27 20:50:46 +02:00
return nil, errors2.New(401, "invalid api key")
}
}
2022-08-12 17:03:15 +02:00
func edgeClient(cfg *ZitiConfig) (*rest_management_api_client.ZitiEdgeManagement, error) {
caCerts, err := rest_util.GetControllerWellKnownCas(cfg.ApiEndpoint)
2022-07-27 19:38:35 +02:00
if err != nil {
return nil, err
}
caPool := x509.NewCertPool()
for _, ca := range caCerts {
caPool.AddCert(ca)
}
2022-08-12 17:03:15 +02:00
return rest_util.NewEdgeManagementClientWithUpdb(cfg.Username, cfg.Password, cfg.ApiEndpoint, caPool)
2022-07-27 19:38:35 +02:00
}
2022-07-25 19:17:52 +02:00
func generateApiToken() (string, error) {
bytes := make([]byte, 64)
if _, err := rand.Read(bytes); err != nil {
return "", errors.Wrap(err, "error generating random api token")
}
return hex.EncodeToString(bytes), nil
}
2022-07-26 22:21:49 +02:00
func randomId() (string, error) {
bytes := make([]byte, 8)
if _, err := rand.Read(bytes); err != nil {
return "", errors.Wrap(err, "error generating random identity id")
}
return hex.EncodeToString(bytes), nil
}