|
| 1 | +package pgs |
| 2 | + |
| 3 | +import ( |
| 4 | + "net/http" |
| 5 | + |
| 6 | + "github.com/picosh/pico/pkg/shared/router" |
| 7 | +) |
| 8 | + |
| 9 | +func handleAutoForm(w http.ResponseWriter, r *http.Request, cfg *PgsConfig) { |
| 10 | + formName := r.PathValue("fname") |
| 11 | + if r.Method != http.MethodPost { |
| 12 | + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) |
| 13 | + return |
| 14 | + } |
| 15 | + |
| 16 | + err := r.ParseForm() |
| 17 | + if err != nil { |
| 18 | + cfg.Logger.Error("failed to parse auto form", "err", err) |
| 19 | + http.Error(w, "failed to parse auto form", http.StatusBadRequest) |
| 20 | + return |
| 21 | + } |
| 22 | + |
| 23 | + formValues := make(map[string]interface{}) |
| 24 | + for key, values := range r.PostForm { |
| 25 | + if len(values) == 1 { |
| 26 | + formValues[key] = values[0] |
| 27 | + } else if len(values) > 1 { |
| 28 | + formValues[key] = values |
| 29 | + } |
| 30 | + } |
| 31 | + |
| 32 | + subdomain := router.GetSubdomainFromRequest(r, cfg.Domain, cfg.TxtPrefix) |
| 33 | + props, err := router.GetProjectFromSubdomain(subdomain) |
| 34 | + if err != nil { |
| 35 | + cfg.Logger.Error("could not get project from subdomain", "subdomain", subdomain, "err", err) |
| 36 | + http.Error(w, "not found", http.StatusNotFound) |
| 37 | + return |
| 38 | + } |
| 39 | + |
| 40 | + user, err := cfg.DB.FindUserByName(props.Username) |
| 41 | + if err != nil { |
| 42 | + cfg.Logger.Error("user not found", "username", props.Username) |
| 43 | + http.Error(w, "not found", http.StatusNotFound) |
| 44 | + return |
| 45 | + } |
| 46 | + |
| 47 | + err = cfg.DB.InsertFormEntry(user.ID, formName, formValues) |
| 48 | + if err != nil { |
| 49 | + cfg.Logger.Error("failed to save form data", "err", err) |
| 50 | + http.Error(w, "failed to save form data", http.StatusInternalServerError) |
| 51 | + return |
| 52 | + } |
| 53 | + |
| 54 | + serveAutoFormSubmitted(w, r, cfg) |
| 55 | +} |
| 56 | + |
| 57 | +type FormData struct { |
| 58 | + Error string |
| 59 | +} |
| 60 | + |
| 61 | +func serveAutoFormSubmitted(w http.ResponseWriter, r *http.Request, cfg *PgsConfig) { |
| 62 | + errorMsg := r.URL.Query().Get("error") |
| 63 | + data := loginFormData{ |
| 64 | + Error: errorMsg, |
| 65 | + } |
| 66 | + |
| 67 | + w.WriteHeader(http.StatusUnprocessableEntity) |
| 68 | + |
| 69 | + ts, err := renderTemplate(cfg, []string{cfg.StaticPath("html/auto_form.page.tmpl")}) |
| 70 | + if err != nil { |
| 71 | + cfg.Logger.Error("could not render auto form template", "err", err.Error()) |
| 72 | + http.Error(w, "Server error", http.StatusInternalServerError) |
| 73 | + return |
| 74 | + } |
| 75 | + |
| 76 | + err = ts.Execute(w, data) |
| 77 | + if err != nil { |
| 78 | + cfg.Logger.Error("could not execute login template", "err", err.Error()) |
| 79 | + http.Error(w, "Server error", http.StatusInternalServerError) |
| 80 | + } |
| 81 | +} |
0 commit comments