Files
picpeak/frontend/src/services/analytics.service.ts
T
paul 1773ed5f95
Mirror to GitHub / mirror (push) Successful in 26s
Test and Lint / backend-test (push) Successful in 1m11s
continuous-integration/drone/push Build is passing
Test and Lint / frontend-test (push) Successful in 2m28s
Version and Release / version-bump (push) Successful in 32s
Version and Release / trigger-drone (push) Has been skipped
Initial commit - Project start (July 17, 2025)
Original: feat: enhance security logging and ensure rate limit blocks are properly tracked

- Add comprehensive logging for rate limit blocks with full request details
  - IP address (with proper proxy detection), user agent, headers, timestamps
  - Rate limit info (current count, limit, remaining, reset time)
  - Separate tracking for auth vs general endpoints

- Enhance authentication failure logging
  - JWT validation failures with detailed error info
  - Admin auth attempts without token
  - Failed token validation with user context
  - All events include IP, path, method, user agent

- Improve Winston logger configuration for production
  - Add automatic log rotation (10MB errors, 50MB combined)
  - Create separate security.log for auth/rate limit events
  - Ensure logs directory exists automatically
  - Add structured JSON format for log aggregation
  - Support container logging with LOG_TO_CONSOLE env var

- Create comprehensive documentation
  - Security logging guide with examples
  - Monitoring recommendations
  - Configuration reference

- Add test script to verify logging functionality

All rate limit settings remain configurable via admin panel:
- Window duration, max requests, auth limits
- Skip authenticated requests option
- Public endpoints only option

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-07-24 16:57:07 +02:00

149 lines
4.0 KiB
TypeScript

// Umami Analytics Service
// Provides integration with Umami for tracking page views and events
interface UmamiConfig {
websiteId?: string;
hostUrl?: string;
autoTrack?: boolean;
doNotTrack?: boolean;
domains?: string[];
}
declare global {
interface Window {
umami?: {
track: (eventName: string, eventData?: any) => void;
trackView: (url?: string, referrer?: string, websiteId?: string) => void;
trackEvent: (
eventValue: string,
eventType: string,
url?: string,
websiteId?: string
) => void;
};
}
}
class AnalyticsService {
private initialized = false;
private websiteId: string | null = null;
// private hostUrl: string | null = null;
initialize(config: UmamiConfig) {
if (this.initialized) return;
const { websiteId, hostUrl, autoTrack = true, doNotTrack = true } = config;
if (!websiteId || !hostUrl) {
console.warn('Umami Analytics: Missing websiteId or hostUrl');
return;
}
this.websiteId = websiteId;
// this.hostUrl = hostUrl;
// Create and inject Umami script
const script = document.createElement('script');
script.async = true;
script.defer = true;
script.src = `${hostUrl}/script.js`;
script.setAttribute('data-website-id', websiteId);
if (!autoTrack) {
script.setAttribute('data-auto-track', 'false');
}
if (doNotTrack) {
script.setAttribute('data-do-not-track', 'true');
}
if (config.domains && config.domains.length > 0) {
script.setAttribute('data-domains', config.domains.join(','));
}
document.head.appendChild(script);
this.initialized = true;
}
// Check if analytics is initialized
isInitialized() {
return this.initialized;
}
// Track custom events
track(eventName: string, eventData?: Record<string, any>) {
if (!this.initialized || !window.umami) {
// Silently ignore if not initialized
return;
}
// Umami expects flat event data
window.umami.track(eventName, eventData);
}
// Track page views manually
trackPageView(url?: string, referrer?: string) {
if (!this.initialized || !window.umami) {
// Silently ignore if not initialized
return;
}
window.umami.trackView(url, referrer, this.websiteId || undefined);
}
// Gallery-specific tracking events
trackGalleryEvent(eventType: 'password_entry' | 'photo_view' | 'photo_download' | 'gallery_expired' | 'bulk_download', data?: any) {
this.track(`gallery_${eventType}`, data);
}
// Admin-specific tracking events
trackAdminEvent(eventType: 'login' | 'event_created' | 'event_archived' | 'event_deleted' | 'settings_updated', data?: any) {
this.track(`admin_${eventType}`, data);
}
// Track download events with more context
trackDownload(photoId: string | number, gallerySlug: string, isBulk: boolean = false) {
this.track('photo_download', {
photo_id: photoId,
gallery: gallerySlug,
bulk: isBulk,
timestamp: new Date().toISOString()
});
}
// Track expiration warning views
trackExpirationWarning(gallerySlug: string, daysRemaining: number) {
this.track('expiration_warning_viewed', {
gallery: gallerySlug,
days_remaining: daysRemaining,
timestamp: new Date().toISOString()
});
}
// Track search usage
trackSearch(query: string, resultsCount: number, context: 'gallery' | 'admin') {
this.track('search_performed', {
query_length: query.length,
results_count: resultsCount,
context,
timestamp: new Date().toISOString()
});
}
}
export const analyticsService = new AnalyticsService();
// Helper hook for React components
import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';
export const useAnalytics = () => {
const location = useLocation();
useEffect(() => {
// Track page views on route change
analyticsService.trackPageView(location.pathname + location.search);
}, [location]);
return analyticsService;
};