package internal import ( "fmt" "io" "net" "net/http" "os" "path/filepath" "strconv" "strings" "time" ) var ( MaxFailedAttempts = 3 BanDuration = 5 * time.Minute UploadDir = "" failedAttempts = make(map[string]int) bannedIPs = make(map[string]time.Time) ) func SetShit() { if maxAttempts, err := strconv.Atoi(os.Getenv("CCTV_MaxFailedAttempts")); err == nil { MaxFailedAttempts = maxAttempts } if banDuration, err := time.ParseDuration(os.Getenv("CCTV_BanDuration")); err == nil { BanDuration = banDuration * time.Minute } UploadDir = os.Getenv("CCTV_UploadDir") } func UploadHandler(w http.ResponseWriter, r *http.Request) { err := r.ParseMultipartForm(10 << 20) if err != nil { http.Error(w, "Error parsing form", http.StatusBadRequest) return } file, handler, err := r.FormFile("file") if err != nil { http.Error(w, "Error retrieving file", http.StatusBadRequest) return } defer file.Close() filePath := filepath.Join(UploadDir, handler.Filename) if _, err := os.Stat(filePath); err == nil { http.Error(w, "File already exists", http.StatusBadRequest) return } out, err := os.Create(filePath) if err != nil { http.Error(w, "Error creating file", http.StatusInternalServerError) return } defer out.Close() _, err = io.Copy(out, file) if err != nil { http.Error(w, "Error saving file", http.StatusInternalServerError) return } LogSuccessUpload(getClientIP(r), handler.Filename) } func AuthMiddleware(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { ip := getClientIP(r) mu.Lock() // Check if IP is banned if banTime, banned := bannedIPs[ip]; banned { fmt.Print("Banned IP: ", ip, " until ", banTime, "\n") if time.Now().Before(banTime) { bannedIPs[ip] = time.Now().Add(BanDuration) http.Error(w, "You are banned", http.StatusForbidden) mu.Unlock() return } delete(bannedIPs, ip) } mu.Unlock() authHeader := r.Header.Get("Authorization") if !strings.HasPrefix(authHeader, "Bearer ") || strings.TrimPrefix(authHeader, "Bearer ") != os.Getenv("CCTV_BearerToken") { LogFailedAttempt(ip) mu.Lock() failedAttempts[ip]++ if failedAttempts[ip] >= MaxFailedAttempts { bannedIPs[ip] = time.Now().Add(BanDuration) delete(failedAttempts, ip) LogBan(ip) } mu.Unlock() http.Error(w, "Unauthorized", http.StatusUnauthorized) return } mu.Lock() delete(failedAttempts, ip) mu.Unlock() next(w, r) } } func HealthHandler(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) } // Get client IP address from request func getClientIP(r *http.Request) string { ip, _, err := net.SplitHostPort(r.RemoteAddr) if err != nil { return r.RemoteAddr // Fallback } return ip }