package main import ( "crypto/tls" "encoding/json" "fmt" "io" "log" "net/http" "net/http/httputil" "net/url" "os" "os/exec" "path/filepath" "strings" "time" "github.com/gorilla/mux" "gopkg.in/gomail.v2" ) type App struct { ID string `json:"id"` Name string `json:"name"` URL string `json:"url"` Description string `json:"description,omitempty"` Icon string `json:"icon,omitempty"` CreatedAt string `json:"created_at"` UpdatedAt string `json:"updated_at"` } type TripEntry struct { Name string `json:"name"` Vehicle string `json:"vehicle"` Destination string `json:"destination"` DateStart string `json:"date_start"` TimeStart string `json:"time_start"` DateEnd string `json:"date_end"` TimeEnd string `json:"time_end"` Purpose string `json:"purpose"` KmStart int `json:"km_start"` KmEnd int `json:"km_end"` Coordinates *GeoCoords `json:"coordinates,omitempty"` } type GeoCoords struct { Lat string `json:"lat"` Lng string `json:"lng"` } func main() { log.SetFlags(log.LstdFlags | log.Lshortfile) // Create necessary directories if err := os.MkdirAll("data", 0755); err != nil { log.Fatalf("Failed to create data directory: %v", err) } if err := os.MkdirAll("uploads", 0755); err != nil { log.Fatalf("Failed to create uploads directory: %v", err) } r := mux.NewRouter() // Set up reverse proxy to kontakt service kontaktURL, _ := url.Parse("http://webportal:8080") kontaktProxy := httputil.NewSingleHostReverseProxy(kontaktURL) // Public routes r.PathPrefix("/kontakt/").Handler(http.StripPrefix("/kontakt", kontaktProxy)) r.PathPrefix("/uploads/").Handler(http.StripPrefix("/uploads/", http.FileServer(http.Dir("./uploads")))) r.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.Write([]byte(`{"status":"ok"}`)) }).Methods("GET", "OPTIONS") // Authentication routes r.HandleFunc("/api/login", LoginHandler).Methods("POST", "OPTIONS") // Protected API routes api := r.PathPrefix("/api").Subrouter() api.Use(AuthMiddleware) api.HandleFunc("/submit", handleSubmit).Methods("POST") api.HandleFunc("/banner/update", UpdateBannerHandler).Methods("POST", "OPTIONS") // App management routes api.HandleFunc("/apps", GetAppsHandler).Methods("GET") api.HandleFunc("/apps", CreateAppHandler).Methods("POST") api.HandleFunc("/apps/{id}", GetAppHandler).Methods("GET") api.HandleFunc("/apps/{id}", UpdateAppHandler).Methods("PUT") api.HandleFunc("/apps/{id}", DeleteAppHandler).Methods("DELETE") // Public endpoints r.HandleFunc("/api/banner", GetBannerHandler).Methods("GET", "OPTIONS") // Important: This public submit endpoint must be defined BEFORE the static file server r.HandleFunc("/submit", handleSubmit).Methods("POST", "OPTIONS") // Public submit endpoint for evidence-aut.html // Add CORS middleware for API r.Use(func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Access-Control-Allow-Origin", "*") w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS") w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization") if r.Method == "OPTIONS" { w.WriteHeader(http.StatusOK) return } next.ServeHTTP(w, r) }) }) // Admin routes r.HandleFunc("/admin", func(w http.ResponseWriter, r *http.Request) { http.ServeFile(w, r, "admin.html") }).Methods("GET") r.HandleFunc("/admin/dashboard", func(w http.ResponseWriter, r *http.Request) { http.ServeFile(w, r, "admin-dashboard.html") }).Methods("GET") // Redirect root to index.html r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/" { http.ServeFile(w, r, "index.html") } }).Methods("GET") // Public route for evidence-aut.html r.HandleFunc("/evidence-aut", func(w http.ResponseWriter, r *http.Request) { http.ServeFile(w, r, "evidence-aut.html") }).Methods("GET") // Static file server for public files - must be the last route defined fs := http.FileServer(http.Dir(".")) r.PathPrefix("/").Handler(fs) r.HandleFunc("/kontakt", func(w http.ResponseWriter, r *http.Request) { // Check if kontakt service is already running resp, err := http.Get("http://webportal:8080/health") if err == nil && resp.StatusCode == 200 { http.Redirect(w, r, "http://webportal:8080/", http.StatusFound) return } // Start the service if not running cmd := exec.Command("make", "dev") cmd.Dir = "kontakt" err = cmd.Start() if err != nil { http.Error(w, "Failed to start kontakt service", http.StatusInternalServerError) return } // Wait briefly for service to start time.Sleep(2 * time.Second) http.Redirect(w, r, "http://webportal:8080/", http.StatusFound) }).Methods("GET") // Apply CORS middleware to all routes handler := enableCORS(r) port := os.Getenv("PORT") if port == "" { port = "80" } log.Printf("Server běží na portu %s", port) err := http.ListenAndServe(":"+port, handler) if err != nil { log.Fatalf("Chyba při spuštění serveru: %v", err) } } func enableCORS(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Access-Control-Allow-Origin", "*") w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE") w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization") if r.Method == "OPTIONS" { w.WriteHeader(http.StatusOK) return } next.ServeHTTP(w, r) }) } // In-memory store for apps (in a real app, use a database) var appsStore = make(map[string]App) var lastAppID = 0 // App Handlers func GetAppsHandler(w http.ResponseWriter, r *http.Request) { // Convert map to slice appsList := make([]App, 0, len(appsStore)) for _, app := range appsStore { appsList = append(appsList, app) } // If no apps, return empty array instead of null if appsList == nil { appsList = []App{} } w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(appsList) } func GetAppHandler(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) id := vars["id"] app, exists := appsStore[id] if !exists { http.Error(w, "App not found", http.StatusNotFound) return } w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(app) } func generateUniqueID() string { lastAppID++ return fmt.Sprintf("%d", lastAppID) } func handleFileUpload(r *http.Request, fieldName string) (string, error) { file, handler, err := r.FormFile(fieldName) if err != nil { // No file was uploaded return "", nil } defer file.Close() // Create uploads directory if it doesn't exist if err := os.MkdirAll("uploads", 0755); err != nil { return "", fmt.Errorf("failed to create uploads directory: %v", err) } // Generate a unique filename ext := filepath.Ext(handler.Filename) filename := fmt.Sprintf("%d%s", time.Now().UnixNano(), ext) filepath := filepath.Join("uploads", filename) // Create the file out, err := os.Create(filepath) if err != nil { return "", fmt.Errorf("failed to create file: %v", err) } defer out.Close() // Copy the file content _, err = io.Copy(out, file) if err != nil { return "", fmt.Errorf("failed to save file: %v", err) } return filename, nil } func CreateAppHandler(w http.ResponseWriter, r *http.Request) { // Parse form data err := r.ParseMultipartForm(10 << 20) // 10 MB max file size if err != nil { http.Error(w, "Error parsing form data: "+err.Error(), http.StatusBadRequest) return } // Get form values name := r.FormValue("name") url := r.FormValue("url") description := r.FormValue("description") // Validate required fields if name == "" || url == "" { http.Error(w, "Name and URL are required", http.StatusBadRequest) return } // Handle file upload icon, err := handleFileUpload(r, "icon") if err != nil { http.Error(w, "Error uploading icon: "+err.Error(), http.StatusInternalServerError) return } // Create new app now := time.Now().Format(time.RFC3339) app := App{ ID: generateUniqueID(), Name: name, URL: url, Description: description, Icon: icon, CreatedAt: now, UpdatedAt: now, } // Save to in-memory store appsStore[app.ID] = app // Return the created app w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusCreated) json.NewEncoder(w).Encode(app) // Get form values name := r.FormValue("name") url := r.FormValue("url") description := r.FormValue("description") // Handle file upload var iconPath string file, handler, err := r.FormFile("icon") if err == nil { defer file.Close() // Create uploads directory if it doesn't exist if _, err := os.Stat("uploads"); os.IsNotExist(err) { os.Mkdir("uploads", 0755) } // Generate a unique filename ext := "" if parts := strings.Split(handler.Filename, "."); len(parts) > 1 { ext = "." + parts[len(parts)-1] } iconPath = fmt.Sprintf("icon_%d%s", time.Now().UnixNano(), ext) // Create the file f, err := os.Create(filepath.Join("uploads", iconPath)) if err != nil { http.Error(w, "Error saving file", http.StatusInternalServerError) return } defer f.Close() // Copy the uploaded file to the created file _, err = io.Copy(f, file) if err != nil { http.Error(w, "Error saving file", http.StatusInternalServerError) return } } // In a real app, this would save to a database app := App{ ID: fmt.Sprintf("%d", time.Now().UnixNano()), Name: name, URL: url, Description: description, Icon: iconPath, CreatedAt: time.Now().Format(time.RFC3339), UpdatedAt: time.Now().Format(time.RFC3339), } w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusCreated) json.NewEncoder(w).Encode(app) } func UpdateAppHandler(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) id := vars["id"] // In a real app, this would update in a database if id != "1" { http.Error(w, "App not found", http.StatusNotFound) return } // Parse form data err := r.ParseMultipartForm(10 << 20) // 10 MB max file size if err != nil { http.Error(w, "Error parsing form data", http.StatusBadRequest) return } // Get form values name := r.FormValue("name") url := r.FormValue("url") description := r.FormValue("description") // Handle file upload if a new file is provided var iconPath string file, handler, err := r.FormFile("icon") if err == nil { defer file.Close() // Create uploads directory if it doesn't exist if _, err := os.Stat("uploads"); os.IsNotExist(err) { os.Mkdir("uploads", 0755) } // Generate a unique filename ext := "" if parts := strings.Split(handler.Filename, "."); len(parts) > 1 { ext = "." + parts[len(parts)-1] } iconPath = fmt.Sprintf("icon_%d%s", time.Now().UnixNano(), ext) // Create the file f, err := os.Create(filepath.Join("uploads", iconPath)) if err != nil { http.Error(w, "Error saving file", http.StatusInternalServerError) return } defer f.Close() // Copy the uploaded file to the created file _, err = io.Copy(f, file) if err != nil { http.Error(w, "Error saving file", http.StatusInternalServerError) return } } // In a real app, this would update in a database app := App{ ID: id, Name: name, URL: url, Description: description, Icon: iconPath, // This would be updated only if a new file was uploaded CreatedAt: time.Now().Format(time.RFC3339), // In a real app, this would be fetched from the database UpdatedAt: time.Now().Format(time.RFC3339), } w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(app) } func DeleteAppHandler(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) id := vars["id"] // In a real app, this would delete from a database if id != "1" { http.Error(w, "App not found", http.StatusNotFound) return } w.WriteHeader(http.StatusNoContent) } func handleSubmit(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") if r.Method != http.MethodPost { if r.Method == http.MethodOptions { w.WriteHeader(http.StatusOK) return } w.WriteHeader(http.StatusMethodNotAllowed) w.Write([]byte(`{"error":"Only POST method is allowed"}`)) return } body, err := io.ReadAll(r.Body) if err != nil { log.Printf("Chyba při čtení těla požadavku: %v", err) w.WriteHeader(http.StatusBadRequest) w.Write([]byte(`{"error":"Failed to read request body"}`)) return } defer r.Body.Close() log.Printf("Přijatá data: %s", string(body)) var entry TripEntry err = json.Unmarshal(body, &entry) if err != nil { log.Printf("Chyba při parsování JSON: %v", err) w.WriteHeader(http.StatusBadRequest) w.Write([]byte(fmt.Sprintf(`{"error":"Failed to parse JSON: %v"}`, err))) return } if entry.Name == "" || entry.Destination == "" || entry.DateStart == "" || entry.DateEnd == "" || entry.Purpose == "" { log.Printf("Chybějící povinná pole: %+v", entry) w.WriteHeader(http.StatusBadRequest) w.Write([]byte(`{"error":"Missing required fields"}`)) return } if entry.KmEnd < entry.KmStart { log.Printf("Neplatný stav tachometru: %d -> %d", entry.KmStart, entry.KmEnd) w.WriteHeader(http.StatusBadRequest) w.Write([]byte(`{"error":"End kilometers must be greater than or equal to start kilometers"}`)) return } // Formátování dat do českého formátu czechMonths := []string{ "ledna", "února", "března", "dubna", "května", "června", "července", "srpna", "září", "října", "listopadu", "prosince", } // Zpracování začátku cesty parsedDateStart, err := time.Parse("2006-01-02", entry.DateStart) if err != nil { log.Printf("Chyba při parsování data začátku: %v", err) } // Zpracování konce cesty parsedDateEnd, err := time.Parse("2006-01-02", entry.DateEnd) if err != nil { log.Printf("Chyba při parsování data konce: %v", err) } err = sendEmail(entry, parsedDateStart, parsedDateEnd, czechMonths) if err != nil { log.Printf("Chyba při odesílání emailu: %v", err) w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(fmt.Sprintf(`{"error":"Failed to send email: %v"}`, err))) return } w.WriteHeader(http.StatusOK) w.Write([]byte(`{"message":"Záznam byl úspěšně uložen a email odeslán"}`)) } func sendEmail(entry TripEntry, parsedDateStart, parsedDateEnd time.Time, czechMonths []string) error { smtpHost := "mail.pp-kunovice.cz" smtpPort := 465 sender := "sluzebnicek@pp-kunovice.cz" password := "7g}qznB5bj" recipient := "sluzebnicek@pp-kunovice.cz" m := gomail.NewMessage() m.SetHeader("From", sender) m.SetHeader("To", recipient) m.SetHeader("Subject", "Nový záznam o jízdě služebním autem") var htmlContent strings.Builder htmlContent.WriteString(`