feat: HTTP panel on :8000 with first admin setup
This commit is contained in:
@@ -0,0 +1,65 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/panelhosting/panel/internal/auth"
|
||||
"github.com/panelhosting/panel/internal/setup"
|
||||
)
|
||||
|
||||
type SetupHandler struct {
|
||||
svc *setup.Service
|
||||
}
|
||||
|
||||
func NewSetupHandler(svc *setup.Service) *SetupHandler {
|
||||
return &SetupHandler{svc: svc}
|
||||
}
|
||||
|
||||
func (h *SetupHandler) Status(w http.ResponseWriter, r *http.Request) {
|
||||
required, err := h.svc.Status(r.Context())
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "internal error")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]bool{"setup_required": required})
|
||||
}
|
||||
|
||||
func (h *SetupHandler) Register(w http.ResponseWriter, r *http.Request) {
|
||||
var in setup.RegisterInput
|
||||
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid json")
|
||||
return
|
||||
}
|
||||
|
||||
user, err := h.svc.RegisterFirstAdmin(r.Context(), in)
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, setup.ErrSetupCompleted):
|
||||
writeError(w, http.StatusConflict, "setup already completed")
|
||||
case errors.Is(err, auth.ErrPasswordTooShort),
|
||||
errors.Is(err, auth.ErrInvalidEmail),
|
||||
errors.Is(err, auth.ErrInvalidUsername):
|
||||
writeError(w, http.StatusBadRequest, err.Error())
|
||||
default:
|
||||
writeError(w, http.StatusInternalServerError, "registration failed")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusCreated, map[string]any{
|
||||
"message": "admin created",
|
||||
"user": user,
|
||||
})
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, v any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(v)
|
||||
}
|
||||
|
||||
func writeError(w http.ResponseWriter, status int, msg string) {
|
||||
writeJSON(w, status, map[string]string{"error": msg})
|
||||
}
|
||||
Reference in New Issue
Block a user