handlePostCrontabs handles POST requests to create a new crontab
(w http.ResponseWriter, r *http.Request)
| 2407 | |
| 2408 | // handlePostCrontabs handles POST requests to create a new crontab |
| 2409 | func handlePostCrontabs(w http.ResponseWriter, r *http.Request) { |
| 2410 | if r.Method != "POST" { |
| 2411 | http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) |
| 2412 | return |
| 2413 | } |
| 2414 | |
| 2415 | if isSafeModeEnabled { |
| 2416 | http.Error(w, "Crontab creation is disabled in safe mode", http.StatusForbidden) |
| 2417 | return |
| 2418 | } |
| 2419 | |
| 2420 | // Define a custom struct to capture all fields including comments |
| 2421 | type CrontabRequest struct { |
| 2422 | Filename string `json:"filename"` |
| 2423 | TimezoneLocationName *lib.TimezoneLocationName `json:"TimezoneLocationName"` |
| 2424 | Comments string `json:"comments"` |
| 2425 | } |
| 2426 | |
| 2427 | var request CrontabRequest |
| 2428 | if err := json.NewDecoder(r.Body).Decode(&request); err != nil { |
| 2429 | http.Error(w, "Invalid request body", http.StatusBadRequest) |
| 2430 | return |
| 2431 | } |
| 2432 | |
| 2433 | if request.Filename == "" { |
| 2434 | http.Error(w, "Filename is required", http.StatusBadRequest) |
| 2435 | return |
| 2436 | } |
| 2437 | |
| 2438 | // If creating in /etc/cron.d, build the full path |
| 2439 | if !strings.Contains(request.Filename, "/") && request.Filename != "/etc/crontab" && !strings.HasPrefix(request.Filename, "user:") { |
| 2440 | request.Filename = filepath.Join("/etc/cron.d", request.Filename) |
| 2441 | } |
| 2442 | |
| 2443 | // Try to load the crontab first to check if it exists |
| 2444 | existingCrontab, err := lib.GetCrontab(request.Filename) |
| 2445 | if err == nil { |
| 2446 | // Parse it to ensure lines are loaded |
| 2447 | if len(existingCrontab.Lines) == 0 && existingCrontab.Exists() { |
| 2448 | existingCrontab.Parse(true) |
| 2449 | } |
| 2450 | w.WriteHeader(http.StatusOK) |
| 2451 | json.NewEncoder(w).Encode(existingCrontab) |
| 2452 | return |
| 2453 | } |
| 2454 | |
| 2455 | // Create a new crontab |
| 2456 | username := "" |
| 2457 | if u, err := user.Current(); err == nil { |
| 2458 | username = u.Username |
| 2459 | } |
| 2460 | |
| 2461 | newCrontab := lib.CrontabFactory(username, request.Filename) |
| 2462 | |
| 2463 | // Build content with timezone and comments |
| 2464 | content := "" |
| 2465 | |
| 2466 | // Add timezone if provided |
no test coverage detected