package user import ( "context" "encoding/json" "net/http" "gitea.local/admin/hspguard/internal/repository" "gitea.local/admin/hspguard/internal/util" "gitea.local/admin/hspguard/internal/web" "github.com/go-chi/chi/v5" ) type UserHandler struct { repo *repository.Queries } func NewUserHandler(repo *repository.Queries) *UserHandler { return &UserHandler{ repo: repo, } } func (h *UserHandler) RegisterRoutes(api chi.Router) { api.Post("/register", h.register) } type RegisterParams struct { FullName string `json:"full_name"` Email string `json:"email"` PhoneNumber string `json:"phone"` Password string `json:"password"` } func (h *UserHandler) register(w http.ResponseWriter, r *http.Request) { var params RegisterParams decoder := json.NewDecoder(r.Body) if err := decoder.Decode(¶ms); err != nil { web.Error(w, "failed to parse request body", http.StatusBadRequest) return } if params.Email == "" || params.FullName == "" || params.Password == "" { web.Error(w, "missing required fields", http.StatusBadRequest) return } _, err := h.repo.FindUserEmail(context.Background(), params.Email) if err == nil { web.Error(w, "user with provided email already exists", http.StatusBadRequest) return } hash, err := util.HashPassword(params.Password) if err != nil { web.Error(w, "failed to create user account", http.StatusInternalServerError) return } id, err := h.repo.InsertUser(context.Background(), repository.InsertUserParams{ FullName: params.FullName, Email: params.Email, PasswordHash: hash, IsAdmin: false, }) if err != nil { web.Error(w, "failed to create new user", http.StatusInternalServerError) return } encoder := json.NewEncoder(w) type Response struct { Id string `json:"id"` } if err := encoder.Encode(Response{ Id: id.String(), }); err != nil { web.Error(w, "failed to encode response", http.StatusInternalServerError) } }