2022-07-25 23:05:44 +02:00
|
|
|
package controller
|
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/sha512"
|
|
|
|
"encoding/hex"
|
|
|
|
"github.com/go-openapi/runtime/middleware"
|
|
|
|
"github.com/openziti-test-kitchen/zrok/controller/store"
|
2022-07-26 21:16:02 +02:00
|
|
|
"github.com/openziti-test-kitchen/zrok/rest_model_zrok"
|
|
|
|
"github.com/openziti-test-kitchen/zrok/rest_server_zrok/operations/identity"
|
2022-07-25 23:05:44 +02:00
|
|
|
"github.com/sirupsen/logrus"
|
|
|
|
)
|
|
|
|
|
|
|
|
func createAccountHandler(params identity.CreateAccountParams) middleware.Responder {
|
|
|
|
logrus.Infof("received account request for username '%v'", params.Body.Username)
|
|
|
|
if params.Body == nil || params.Body.Username == "" || params.Body.Password == "" {
|
2022-07-27 19:38:35 +02:00
|
|
|
logrus.Errorf("missing username or password")
|
2022-08-02 19:23:31 +02:00
|
|
|
return identity.NewCreateAccountBadRequest().WithPayload("missing username or password")
|
2022-07-25 23:05:44 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
token, err := generateApiToken()
|
|
|
|
if err != nil {
|
|
|
|
logrus.Errorf("error generating api token: %v", err)
|
2022-07-27 19:38:35 +02:00
|
|
|
return identity.NewCreateAccountInternalServerError().WithPayload(rest_model_zrok.ErrorMessage(err.Error()))
|
2022-07-25 23:05:44 +02:00
|
|
|
}
|
|
|
|
a := &store.Account{
|
|
|
|
Username: params.Body.Username,
|
|
|
|
Password: hashPassword(params.Body.Password),
|
|
|
|
Token: token,
|
|
|
|
}
|
2022-07-29 21:28:40 +02:00
|
|
|
tx, err := str.Begin()
|
2022-07-25 23:05:44 +02:00
|
|
|
if err != nil {
|
|
|
|
logrus.Errorf("error starting transaction: %v", err)
|
2022-07-27 19:38:35 +02:00
|
|
|
return identity.NewCreateAccountInternalServerError().WithPayload(rest_model_zrok.ErrorMessage(err.Error()))
|
2022-07-25 23:05:44 +02:00
|
|
|
}
|
2022-07-29 21:28:40 +02:00
|
|
|
id, err := str.CreateAccount(a, tx)
|
2022-07-25 23:05:44 +02:00
|
|
|
if err != nil {
|
|
|
|
logrus.Errorf("error creating account: %v", err)
|
|
|
|
_ = tx.Rollback()
|
2022-07-27 19:38:35 +02:00
|
|
|
return identity.NewCreateAccountBadRequest().WithPayload(rest_model_zrok.ErrorMessage(err.Error()))
|
2022-07-25 23:05:44 +02:00
|
|
|
}
|
|
|
|
if err := tx.Commit(); err != nil {
|
|
|
|
logrus.Errorf("error comitting: %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
logrus.Infof("account created with id = '%v'", id)
|
2022-07-27 19:38:35 +02:00
|
|
|
return identity.NewCreateAccountCreated().WithPayload(&rest_model_zrok.AccountResponse{Token: token})
|
2022-07-25 23:05:44 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func hashPassword(raw string) string {
|
|
|
|
hash := sha512.New()
|
|
|
|
hash.Write([]byte(raw))
|
|
|
|
return hex.EncodeToString(hash.Sum(nil))
|
|
|
|
}
|