cic-custodial/internal/api/account.go

90 lines
2.1 KiB
Go
Raw Normal View History

2023-02-02 13:29:43 +01:00
package api
import (
2023-02-09 08:42:15 +01:00
"encoding/json"
2023-02-02 13:29:43 +01:00
"net/http"
"github.com/grassrootseconomics/cic-custodial/internal/keystore"
"github.com/grassrootseconomics/cic-custodial/internal/tasker"
2023-02-09 08:42:15 +01:00
"github.com/grassrootseconomics/cic-custodial/internal/tasker/task"
2023-02-02 13:29:43 +01:00
"github.com/grassrootseconomics/cic-custodial/pkg/keypair"
"github.com/labstack/echo/v4"
)
// CreateAccountHandler route.
2023-02-09 08:42:15 +01:00
// POST: /api/account/create
// JSON Body:
// trackingId -> Unique string
// Returns the public key.
2023-02-02 13:29:43 +01:00
func CreateAccountHandler(
keystore keystore.Keystore,
2023-02-09 08:42:15 +01:00
taskerClient *tasker.TaskerClient,
2023-02-02 13:29:43 +01:00
) func(echo.Context) error {
return func(c echo.Context) error {
2023-02-09 08:42:15 +01:00
var accountRequest struct {
TrackingId string `json:"trackingId" validate:"required"`
}
if err := c.Bind(&accountRequest); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, errResp{
Ok: false,
Code: INTERNAL_ERROR,
})
}
if err := c.Validate(accountRequest); err != nil {
return err
}
2023-02-02 13:29:43 +01:00
generatedKeyPair, err := keypair.Generate()
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, errResp{
Ok: false,
Code: INTERNAL_ERROR,
})
}
id, err := keystore.WriteKeyPair(c.Request().Context(), generatedKeyPair)
if err != nil {
2023-02-02 13:29:43 +01:00
return echo.NewHTTPError(http.StatusInternalServerError, errResp{
Ok: false,
Code: INTERNAL_ERROR,
})
}
2023-02-09 08:42:15 +01:00
taskPayload, err := json.Marshal(task.AccountPayload{
PublicKey: generatedKeyPair.Public,
TrackingId: accountRequest.TrackingId,
2023-02-02 13:29:43 +01:00
})
2023-02-09 08:42:15 +01:00
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, errResp{
Ok: false,
Code: INTERNAL_ERROR,
})
}
_, err = taskerClient.CreateTask(
tasker.PrepareAccountTask,
tasker.DefaultPriority,
&tasker.Task{
Id: accountRequest.TrackingId,
Payload: taskPayload,
},
)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, errResp{
Ok: false,
Code: INTERNAL_ERROR,
})
}
2023-02-02 13:29:43 +01:00
return c.JSON(http.StatusOK, okResp{
Ok: true,
2023-02-09 08:42:15 +01:00
Result: H{
"publicKey": generatedKeyPair.Public,
"custodialId": id,
},
2023-02-02 13:29:43 +01:00
})
}
}