53 lines
1.3 KiB
Go
53 lines
1.3 KiB
Go
|
package api
|
||
|
|
||
|
import (
|
||
|
"net/http"
|
||
|
|
||
|
"forge.cadoles.com/wpetit/hydra-webauthn/internal/storage"
|
||
|
"github.com/pkg/errors"
|
||
|
"gitlab.com/wpetit/goweb/api"
|
||
|
"gitlab.com/wpetit/goweb/logger"
|
||
|
"gitlab.com/wpetit/goweb/middleware/container"
|
||
|
)
|
||
|
|
||
|
type CreateUserRequest struct {
|
||
|
Username string `json:"username" validate:"required"`
|
||
|
Attributes map[string]any `json:"attributes"`
|
||
|
}
|
||
|
|
||
|
type CreateUserResponse struct {
|
||
|
User *storage.User `json:"user"`
|
||
|
}
|
||
|
|
||
|
func CreateUser(w http.ResponseWriter, r *http.Request) {
|
||
|
createUserReq := &CreateUserRequest{}
|
||
|
if ok := api.Bind(w, r, createUserReq); !ok {
|
||
|
return
|
||
|
}
|
||
|
|
||
|
ctx := r.Context()
|
||
|
ctn := container.Must(ctx)
|
||
|
storageSrv := storage.Must(ctn)
|
||
|
|
||
|
user, err := storageSrv.User().CreateUser(ctx, createUserReq.Username, createUserReq.Attributes)
|
||
|
if err != nil {
|
||
|
if errors.Is(err, storage.ErrAlreadyExist) {
|
||
|
logger.Warn(ctx, "user already exists", logger.E(errors.WithStack(err)), logger.F("username", createUserReq.Username))
|
||
|
api.ErrorResponse(w, http.StatusConflict, ErrCodeAlreadyExist, nil)
|
||
|
|
||
|
return
|
||
|
}
|
||
|
|
||
|
logger.Error(ctx, "could not create user", logger.E(errors.WithStack(err)))
|
||
|
api.ErrorResponse(w, http.StatusInternalServerError, api.ErrCodeUnknownError, nil)
|
||
|
|
||
|
return
|
||
|
}
|
||
|
|
||
|
response := CreateUserResponse{
|
||
|
User: user,
|
||
|
}
|
||
|
|
||
|
api.DataResponse(w, http.StatusCreated, response)
|
||
|
}
|