package httpapi import ( "net/http" "strconv" "github.com/gin-gonic/gin" ) // usersHandlers are the admin-only user management routes. type usersHandlers struct{ svc authService } func (h *usersHandlers) list(c *gin.Context) { users, err := h.svc.ListUsers(c.Request.Context()) if err != nil { writeAuthError(c, err) return } out := make([]userJSON, len(users)) for i, u := range users { out[i] = toUserJSON(u) } c.JSON(http.StatusOK, gin.H{"users": out}) } type createUserRequest struct { Email string `json:"email"` Password string `json:"password"` IsAdmin bool `json:"is_admin"` } func (h *usersHandlers) create(c *gin.Context) { var req createUserRequest if !bindJSON(c, &req) { return } user, err := h.svc.CreateUser(c.Request.Context(), req.Email, req.Password, req.IsAdmin) if err != nil { writeAuthError(c, err) return } c.JSON(http.StatusCreated, toUserJSON(user)) } type updateUserRequest struct { IsAdmin *bool `json:"is_admin"` // pointer: absent must not mean false } func (h *usersHandlers) update(c *gin.Context) { id, ok := pathID(c) if !ok { return } var req updateUserRequest if !bindJSON(c, &req) { return } if req.IsAdmin == nil { writeError(c, http.StatusBadRequest, "invalid_input", "is_admin is required") return } user, err := h.svc.SetAdmin(c.Request.Context(), id, *req.IsAdmin) if err != nil { writeAuthError(c, err) return } c.JSON(http.StatusOK, toUserJSON(user)) } type resetPasswordRequest struct { Password string `json:"password"` } func (h *usersHandlers) resetPassword(c *gin.Context) { id, ok := pathID(c) if !ok { return } var req resetPasswordRequest if !bindJSON(c, &req) { return } if err := h.svc.ResetPassword(c.Request.Context(), id, req.Password); err != nil { writeAuthError(c, err) return } c.Status(http.StatusNoContent) } func (h *usersHandlers) remove(c *gin.Context) { id, ok := pathID(c) if !ok { return } if err := h.svc.DeleteUser(c.Request.Context(), id); err != nil { writeAuthError(c, err) return } c.Status(http.StatusNoContent) } func pathID(c *gin.Context) (int64, bool) { id, err := strconv.ParseInt(c.Param("id"), 10, 64) if err != nil || id <= 0 { writeError(c, http.StatusBadRequest, "invalid_input", "id must be a positive number") return 0, false } return id, true }