Compare commits
43 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| ad9c6d63d3 | |||
| 8c77b30de6 | |||
| e51347d0a1 | |||
| 71e7179145 | |||
| bda76ff513 | |||
| 097ce2c205 | |||
| 1d8be3d840 | |||
| aebb8e66cb | |||
| ed2a278da2 | |||
| db2f5da66a | |||
| 19f8facc49 | |||
| b03760ab01 | |||
| 526dcd8dfc | |||
| 5b2561b6f1 | |||
| 3a6d06192a | |||
| 4b64b80b20 | |||
| ff89f96e31 | |||
| 465f997752 | |||
| 6948aaa92a | |||
| 4c7b49a5f6 | |||
| 6368f1027f | |||
| d64e7d08de | |||
| eb3751cb52 | |||
| 9fda54bd06 | |||
| 0d77a3a0a8 | |||
| 0618b78725 | |||
| 0178e71c67 | |||
| aa9b3a0227 | |||
| 410a33fecf | |||
| 05ebaaeedb | |||
| 84d0f63d36 | |||
| 6a4b549d9f | |||
| f3604b438b | |||
| 531831e84b | |||
| 90bb21e38b | |||
| 2f1a137342 | |||
| adf576fbe1 | |||
| 4264026bbe | |||
| 24b4a314a9 | |||
| ba825823a0 | |||
| fb16b7bbb8 | |||
| 8404125ff0 | |||
| 61ad2d61c1 |
@@ -53,6 +53,12 @@ VITE_API_URL=/api
|
||||
# Timezone
|
||||
TZ=UTC
|
||||
|
||||
# Runtime user mapping for Docker (optional)
|
||||
# Set these to your host user's UID/GID to avoid permission issues on bind mounts.
|
||||
# Run `id -u` and `id -g` on host to get values. Defaults to 1001.
|
||||
PUID=1001
|
||||
PGID=1001
|
||||
|
||||
# Analytics (Optional - Umami)
|
||||
VITE_UMAMI_URL=
|
||||
VITE_UMAMI_WEBSITE_ID=
|
||||
|
||||
@@ -43,6 +43,8 @@ jobs:
|
||||
|
||||
- name: Log in to Container Registry
|
||||
if: github.event_name != 'pull_request' || github.event.inputs.push == 'true'
|
||||
id: login-ghcr
|
||||
continue-on-error: true
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
@@ -73,7 +75,8 @@ jobs:
|
||||
with:
|
||||
context: ./backend
|
||||
file: ./backend/Dockerfile
|
||||
push: ${{ github.event_name != 'pull_request' || github.event.inputs.push == 'true' }}
|
||||
# Always build; only push when registry login succeeded
|
||||
push: ${{ (github.event_name != 'pull_request' || github.event.inputs.push == 'true') && steps.login-ghcr.outcome == 'success' }}
|
||||
tags: ${{ steps.meta-backend.outputs.tags }}
|
||||
labels: ${{ steps.meta-backend.outputs.labels }}
|
||||
platforms: linux/amd64,linux/arm64
|
||||
@@ -86,7 +89,7 @@ jobs:
|
||||
VERSION=${{ steps.meta-backend.outputs.version }}
|
||||
|
||||
- name: Run Trivy vulnerability scanner
|
||||
if: github.event_name != 'pull_request'
|
||||
if: github.event_name != 'pull_request' && steps.login-ghcr.outcome == 'success'
|
||||
uses: aquasecurity/trivy-action@master
|
||||
with:
|
||||
image-ref: ${{ env.REGISTRY }}/${{ env.BACKEND_IMAGE_NAME }}:${{ steps.meta-backend.outputs.version }}
|
||||
@@ -96,7 +99,7 @@ jobs:
|
||||
timeout: '10m'
|
||||
|
||||
- name: Upload Trivy scan results to GitHub Security tab
|
||||
if: github.event_name != 'pull_request'
|
||||
if: github.event_name != 'pull_request' && steps.login-ghcr.outcome == 'success'
|
||||
uses: github/codeql-action/upload-sarif@v3
|
||||
with:
|
||||
sarif_file: 'trivy-backend.sarif'
|
||||
@@ -120,6 +123,8 @@ jobs:
|
||||
|
||||
- name: Log in to Container Registry
|
||||
if: github.event_name != 'pull_request' || github.event.inputs.push == 'true'
|
||||
id: login-ghcr
|
||||
continue-on-error: true
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
@@ -150,7 +155,8 @@ jobs:
|
||||
with:
|
||||
context: ./frontend
|
||||
file: ./frontend/Dockerfile
|
||||
push: ${{ github.event_name != 'pull_request' || github.event.inputs.push == 'true' }}
|
||||
# Always build; only push when registry login succeeded
|
||||
push: ${{ (github.event_name != 'pull_request' || github.event.inputs.push == 'true') && steps.login-ghcr.outcome == 'success' }}
|
||||
tags: ${{ steps.meta-frontend.outputs.tags }}
|
||||
labels: ${{ steps.meta-frontend.outputs.labels }}
|
||||
platforms: linux/amd64,linux/arm64
|
||||
@@ -163,7 +169,7 @@ jobs:
|
||||
VERSION=${{ steps.meta-frontend.outputs.version }}
|
||||
|
||||
- name: Run Trivy vulnerability scanner
|
||||
if: github.event_name != 'pull_request'
|
||||
if: github.event_name != 'pull_request' && steps.login-ghcr.outcome == 'success'
|
||||
uses: aquasecurity/trivy-action@master
|
||||
with:
|
||||
image-ref: ${{ env.REGISTRY }}/${{ env.FRONTEND_IMAGE_NAME }}:${{ steps.meta-frontend.outputs.version }}
|
||||
@@ -173,7 +179,7 @@ jobs:
|
||||
timeout: '10m'
|
||||
|
||||
- name: Upload Trivy scan results to GitHub Security tab
|
||||
if: github.event_name != 'pull_request'
|
||||
if: github.event_name != 'pull_request' && steps.login-ghcr.outcome == 'success'
|
||||
uses: github/codeql-action/upload-sarif@v3
|
||||
with:
|
||||
sarif_file: 'trivy-frontend.sarif'
|
||||
@@ -220,4 +226,4 @@ jobs:
|
||||
echo "- PR number (for pull requests)" >> $GITHUB_STEP_SUMMARY
|
||||
echo "- Version tags (for releases)" >> $GITHUB_STEP_SUMMARY
|
||||
echo "- Short SHA with branch prefix" >> $GITHUB_STEP_SUMMARY
|
||||
echo "- \`latest\` (for main branch)" >> $GITHUB_STEP_SUMMARY
|
||||
echo "- \`latest\` (for main branch)" >> $GITHUB_STEP_SUMMARY
|
||||
|
||||
@@ -72,6 +72,14 @@ docker-compose up -d
|
||||
# Access at http://localhost:3005
|
||||
```
|
||||
|
||||
Note on Docker file permissions (PUID/PGID)
|
||||
- When using bind mounts (e.g., `./storage`, `./data`, `./logs`, `./events`), ensure the container user can write to these host folders. The backend runs as a non‑root user by default.
|
||||
- Set `PUID` and `PGID` in your `.env` to match your host user’s UID/GID (run `id -u` and `id -g` on the host). Compose maps the container user to these values.
|
||||
- Example in `.env`:
|
||||
- `PUID=1000`
|
||||
- `PGID=1000`
|
||||
- Without this, creating events, uploads, thumbnails, or logs can fail with “Permission denied”.
|
||||
|
||||
## 📖 Documentation
|
||||
|
||||
- 📘 [**Deployment Guide**](DEPLOYMENT_GUIDE.md) - Detailed installation instructions
|
||||
@@ -201,6 +209,7 @@ These features are currently in beta testing and may have limited functionality
|
||||
| **Gallery Feedback** | Allow guests to like, rate, and comment on photos with admin notifications and moderation | Medium | ✅ Implemented |
|
||||
| **Video Support** | Upload and display videos alongside photos in galleries with streaming support | Low | 🔄 Open |
|
||||
| **Multiple Administrators** | Support for multiple admin accounts with role-based permissions and activity tracking | Low | 📋 Planned |
|
||||
| **Filtering & Export Options** | Add filters to show only rated, liked, or marked photos and export filtered selections for Capture One or Lightroom workflows | Low | 🔄 Open |
|
||||
|
||||
**Status Legend:** ✅ Implemented | 🚧 In Progress | 🔄 Open | 📋 Planned
|
||||
|
||||
|
||||
@@ -292,6 +292,7 @@ sudo systemctl stop picpeak-backend picpeak-workers
|
||||
sudo systemctl restart picpeak-backend picpeak-workers
|
||||
|
||||
# Update PicPeak
|
||||
# (reruns migrations to pick up schema fixes for native installs)
|
||||
sudo ./setup.sh --update
|
||||
```
|
||||
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
const logger = require('../../src/utils/logger');
|
||||
|
||||
async function ensureColumn(knex, tableName, columnName, alterFn) {
|
||||
const exists = await knex.schema.hasColumn(tableName, columnName);
|
||||
if (!exists) {
|
||||
logger.info(`Adding column ${tableName}.${columnName}`);
|
||||
await knex.schema.table(tableName, alterFn);
|
||||
}
|
||||
}
|
||||
|
||||
exports.up = async function(knex) {
|
||||
await ensureColumn(knex, 'events', 'host_name', (table) => {
|
||||
table.string('host_name');
|
||||
});
|
||||
|
||||
await ensureColumn(knex, 'events', 'allow_user_uploads', (table) => {
|
||||
table.boolean('allow_user_uploads').defaultTo(false);
|
||||
});
|
||||
|
||||
await ensureColumn(knex, 'events', 'upload_category_id', (table) => {
|
||||
table.integer('upload_category_id');
|
||||
});
|
||||
|
||||
await ensureColumn(knex, 'events', 'allow_downloads', (table) => {
|
||||
table.boolean('allow_downloads').defaultTo(true);
|
||||
});
|
||||
|
||||
await ensureColumn(knex, 'events', 'disable_right_click', (table) => {
|
||||
table.boolean('disable_right_click').defaultTo(false);
|
||||
});
|
||||
|
||||
await ensureColumn(knex, 'events', 'watermark_downloads', (table) => {
|
||||
table.boolean('watermark_downloads').defaultTo(false);
|
||||
});
|
||||
|
||||
await ensureColumn(knex, 'events', 'watermark_text', (table) => {
|
||||
table.text('watermark_text');
|
||||
});
|
||||
|
||||
await ensureColumn(knex, 'events', 'hero_photo_id', (table) => {
|
||||
table.integer('hero_photo_id').references('id').inTable('photos').onDelete('SET NULL');
|
||||
});
|
||||
|
||||
await ensureColumn(knex, 'photos', 'uploaded_by', (table) => {
|
||||
table.string('uploaded_by').defaultTo('admin');
|
||||
});
|
||||
};
|
||||
|
||||
exports.down = async function() {
|
||||
// Non destructive migration; no rollback
|
||||
};
|
||||
Generated
+30
-7
@@ -1,21 +1,22 @@
|
||||
{
|
||||
"name": "picpeak-backend",
|
||||
"version": "1.0.116",
|
||||
"version": "1.0.129",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "picpeak-backend",
|
||||
"version": "1.0.116",
|
||||
"version": "1.0.129",
|
||||
"dependencies": {
|
||||
"@aws-sdk/client-s3": "^3.850.0",
|
||||
"@aws-sdk/lib-storage": "^3.850.0",
|
||||
"@aws-sdk/s3-request-presigner": "^3.850.0",
|
||||
"adm-zip": "^0.5.16",
|
||||
"archiver": "^5.3.1",
|
||||
"axios": "^1.10.0",
|
||||
"axios": "^1.12.2",
|
||||
"bcrypt": "6.0.0",
|
||||
"chokidar": "4.0.3",
|
||||
"cookie-parser": "^1.4.7",
|
||||
"cors": "^2.8.5",
|
||||
"dotenv": "^16.0.3",
|
||||
"express": "^4.18.2",
|
||||
@@ -3889,13 +3890,13 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/axios": {
|
||||
"version": "1.10.0",
|
||||
"resolved": "https://registry.npmjs.org/axios/-/axios-1.10.0.tgz",
|
||||
"integrity": "sha512-/1xYAC4MP/HEG+3duIhFr4ZQXR4sQXOIe+o6sdqzeykGLx6Upp/1p8MHqhINOvGeP7xyNHe7tsiJByc4SSVUxw==",
|
||||
"version": "1.12.2",
|
||||
"resolved": "https://registry.npmjs.org/axios/-/axios-1.12.2.tgz",
|
||||
"integrity": "sha512-vMJzPewAlRyOgxV2dU0Cuz2O8zzzx9VYtbJOaBgXFeLc4IV/Eg50n4LowmehOOR61S8ZMpc2K5Sa7g6A4jfkUw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"follow-redirects": "^1.15.6",
|
||||
"form-data": "^4.0.0",
|
||||
"form-data": "^4.0.4",
|
||||
"proxy-from-env": "^1.1.0"
|
||||
}
|
||||
},
|
||||
@@ -4727,6 +4728,28 @@
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/cookie-parser": {
|
||||
"version": "1.4.7",
|
||||
"resolved": "https://registry.npmjs.org/cookie-parser/-/cookie-parser-1.4.7.tgz",
|
||||
"integrity": "sha512-nGUvgXnotP3BsjiLX2ypbQnWoGUPIIfHQNZkkC668ntrzGWEZVW70HDEB1qnNGMicPje6EttlIgzo51YSwNQGw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"cookie": "0.7.2",
|
||||
"cookie-signature": "1.0.6"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/cookie-parser/node_modules/cookie": {
|
||||
"version": "0.7.2",
|
||||
"resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz",
|
||||
"integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/cookie-signature": {
|
||||
"version": "1.0.6",
|
||||
"resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "picpeak-backend",
|
||||
"version": "1.0.116",
|
||||
"version": "1.0.129",
|
||||
"description": "Backend for PicPeak event photo sharing platform",
|
||||
"main": "server.js",
|
||||
"scripts": {
|
||||
@@ -17,9 +17,10 @@
|
||||
"@aws-sdk/s3-request-presigner": "^3.850.0",
|
||||
"adm-zip": "^0.5.16",
|
||||
"archiver": "^5.3.1",
|
||||
"axios": "^1.10.0",
|
||||
"axios": "^1.12.2",
|
||||
"bcrypt": "6.0.0",
|
||||
"chokidar": "4.0.3",
|
||||
"cookie-parser": "^1.4.7",
|
||||
"cors": "^2.8.5",
|
||||
"dotenv": "^16.0.3",
|
||||
"express": "^4.18.2",
|
||||
|
||||
@@ -36,4 +36,4 @@ async function setAdminPassword() {
|
||||
}
|
||||
}
|
||||
|
||||
setAdminPassword();
|
||||
setAdminPassword();
|
||||
|
||||
+86
-22
@@ -26,6 +26,11 @@ const { startScheduledBackups } = require('./src/services/databaseBackup');
|
||||
const { maintenanceMiddleware } = require('./src/middleware/maintenance');
|
||||
const { sessionTimeoutMiddleware } = require('./src/middleware/sessionTimeout');
|
||||
const { createRateLimiter, createAuthRateLimiter } = require('./src/services/rateLimitService');
|
||||
const cookieParser = require('cookie-parser');
|
||||
const {
|
||||
getAdminTokenFromRequest,
|
||||
getGalleryTokenFromRequest,
|
||||
} = require('./src/utils/tokenUtils');
|
||||
|
||||
// Import routes
|
||||
const authRoutes = require('./src/routes/auth-enhanced');
|
||||
@@ -43,25 +48,59 @@ const PORT = process.env.PORT || 3000;
|
||||
app.set('trust proxy', 'loopback, linklocal, uniquelocal');
|
||||
|
||||
// Security middleware with custom CSP
|
||||
// In native HTTP installs, do NOT force HTTPS for subresources.
|
||||
const enableHsts = process.env.ENABLE_HSTS === 'true';
|
||||
const cspDirectives = {
|
||||
defaultSrc: ["'self'"],
|
||||
scriptSrc: [
|
||||
"'self'",
|
||||
'https://www.google.com',
|
||||
'https://www.gstatic.com'
|
||||
],
|
||||
styleSrc: ["'self'", "'unsafe-inline'", "https:"], // Required for styled components
|
||||
imgSrc: ["'self'", "data:", "https:", "blob:"], // Allow data URLs and external images
|
||||
connectSrc: ["'self'", 'https://www.google.com', 'https://www.gstatic.com'], // API connections
|
||||
fontSrc: ["'self'", "https:", "data:"], // Web fonts
|
||||
objectSrc: ["'none'"], // Disable plugins
|
||||
mediaSrc: ["'self'"], // Audio/video
|
||||
frameSrc: ["'self'", 'https://www.google.com'],
|
||||
};
|
||||
// Only upgrade insecure requests when HSTS explicitly enabled (HTTPS deployment)
|
||||
if (enableHsts) {
|
||||
// In helmet, an empty array enables the directive
|
||||
cspDirectives.upgradeInsecureRequests = [];
|
||||
}
|
||||
|
||||
app.use(cookieParser());
|
||||
|
||||
app.use((req, res, next) => {
|
||||
if (!req.headers.authorization) {
|
||||
const slugMatch = req.path.match(/\/api\/(?:gallery|secure-images)\/([^\/]+)/);
|
||||
const slug = slugMatch ? slugMatch[1] : req.requestedSlug;
|
||||
const galleryToken = getGalleryTokenFromRequest(req, slug);
|
||||
const adminToken = getAdminTokenFromRequest(req);
|
||||
|
||||
if (galleryToken) {
|
||||
req.headers.authorization = `Bearer ${galleryToken}`;
|
||||
} else if (adminToken) {
|
||||
req.headers.authorization = `Bearer ${adminToken}`;
|
||||
}
|
||||
}
|
||||
|
||||
next();
|
||||
});
|
||||
|
||||
app.use(helmet({
|
||||
contentSecurityPolicy: {
|
||||
directives: {
|
||||
defaultSrc: ["'self'"],
|
||||
scriptSrc: ["'self'", "'unsafe-inline'"], // Required for React
|
||||
styleSrc: ["'self'", "'unsafe-inline'", "https:"], // Required for styled components
|
||||
imgSrc: ["'self'", "data:", "https:", "blob:"], // Allow data URLs and external images
|
||||
connectSrc: ["'self'"], // API connections
|
||||
fontSrc: ["'self'", "https:", "data:"], // Web fonts
|
||||
objectSrc: ["'none'"], // Disable plugins
|
||||
mediaSrc: ["'self'"], // Audio/video
|
||||
frameSrc: ["'none'"], // Disable iframes
|
||||
},
|
||||
// Avoid helmet adding defaults like upgrade-insecure-requests when not desired
|
||||
useDefaults: false,
|
||||
directives: cspDirectives,
|
||||
},
|
||||
hsts: {
|
||||
hsts: enableHsts ? {
|
||||
maxAge: 31536000, // 1 year
|
||||
includeSubDomains: true,
|
||||
preload: true
|
||||
},
|
||||
} : false,
|
||||
permittedCrossDomainPolicies: false,
|
||||
referrerPolicy: { policy: "strict-origin-when-cross-origin" }
|
||||
}));
|
||||
@@ -73,14 +112,14 @@ app.use((req, res, next) => {
|
||||
next();
|
||||
});
|
||||
|
||||
// CORS configuration
|
||||
// CORS configuration (apply only to API routes)
|
||||
const corsOptions = {
|
||||
origin: function (origin, callback) {
|
||||
const allowedOrigins = [
|
||||
process.env.FRONTEND_URL || 'http://localhost:3005',
|
||||
process.env.ADMIN_URL || 'http://localhost:3005'
|
||||
];
|
||||
|
||||
|
||||
// In development, also allow localhost origins
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
allowedOrigins.push(
|
||||
@@ -90,18 +129,22 @@ const corsOptions = {
|
||||
'http://localhost:3000' // Direct backend access
|
||||
);
|
||||
}
|
||||
|
||||
// Allow requests with no origin (like mobile apps or curl)
|
||||
|
||||
// Allow requests with no origin (like curl) and allow-listed origins
|
||||
if (!origin || allowedOrigins.indexOf(origin) !== -1) {
|
||||
callback(null, true);
|
||||
} else {
|
||||
callback(new Error('Not allowed by CORS'));
|
||||
// Do not error globally; just omit CORS headers on disallowed origins
|
||||
callback(null, false);
|
||||
}
|
||||
},
|
||||
credentials: true
|
||||
};
|
||||
|
||||
app.use(cors(corsOptions));
|
||||
// Only attach CORS to API endpoints, not static assets
|
||||
app.use('/api', cors(corsOptions));
|
||||
// Handle preflight explicitly for API paths
|
||||
app.options('/api/*', cors(corsOptions));
|
||||
|
||||
// Initialize rate limiters (they will be created dynamically)
|
||||
let generalRateLimiter;
|
||||
@@ -125,6 +168,22 @@ async function initializeRateLimiters() {
|
||||
app.use(express.json({ limit: '100mb' }));
|
||||
app.use(express.urlencoded({ extended: true, limit: '100mb' }));
|
||||
|
||||
// Request logging for API routes (with timestamps)
|
||||
const apiRequestLogger = (req, res, next) => {
|
||||
try {
|
||||
const started = Date.now();
|
||||
const ts = new Date().toISOString();
|
||||
logger.info(`[${ts}] ${req.method} ${req.originalUrl}`);
|
||||
res.on('finish', () => {
|
||||
const ms = Date.now() - started;
|
||||
const tsDone = new Date().toISOString();
|
||||
logger.info(`[${tsDone}] ${req.method} ${req.originalUrl} -> ${res.statusCode} (${ms}ms)`);
|
||||
});
|
||||
} catch (_) {}
|
||||
next();
|
||||
};
|
||||
app.use('/api', apiRequestLogger);
|
||||
|
||||
// Maintenance mode middleware - add after body parsing but before routes
|
||||
app.use(maintenanceMiddleware);
|
||||
|
||||
@@ -222,15 +281,20 @@ app.use('/api/secure-images', secureImagesRoutes);
|
||||
|
||||
// Optional: Serve built frontend (native installs)
|
||||
try {
|
||||
const serveFrontend = process.env.SERVE_FRONTEND === 'true';
|
||||
const serveFrontendEnv = process.env.SERVE_FRONTEND; // 'true' | 'false' | undefined
|
||||
const frontendDir = process.env.FRONTEND_DIR || path.join(__dirname, '../frontend/dist');
|
||||
if (serveFrontend && fs.existsSync(frontendDir)) {
|
||||
const indexPath = path.join(frontendDir, 'index.html');
|
||||
// Auto-serve when dist exists unless explicitly disabled
|
||||
const shouldServe = (serveFrontendEnv === 'true') || ((serveFrontendEnv === undefined || serveFrontendEnv === 'auto') && fs.existsSync(indexPath));
|
||||
if (shouldServe) {
|
||||
logger.info(`Serving frontend from ${frontendDir}`);
|
||||
app.use(express.static(frontendDir));
|
||||
// SPA fallback for non-API routes
|
||||
app.get([ '/', '/admin', '/admin/*', '/gallery/*' ], (req, res) => {
|
||||
res.sendFile(path.join(frontendDir, 'index.html'));
|
||||
res.sendFile(indexPath);
|
||||
});
|
||||
} else {
|
||||
logger.info('Frontend static serving disabled or dist not found', { serveFrontendEnv, frontendDir });
|
||||
}
|
||||
} catch (e) {
|
||||
logger.warn('Failed to enable frontend static serving', { error: e.message });
|
||||
|
||||
+151
-2
@@ -75,6 +75,13 @@ async function initializeDatabase() {
|
||||
table.boolean('is_archived').defaultTo(false);
|
||||
table.string('archive_path');
|
||||
table.datetime('archived_at');
|
||||
table.boolean('allow_user_uploads').defaultTo(false);
|
||||
table.integer('upload_category_id');
|
||||
table.boolean('allow_downloads').defaultTo(true);
|
||||
table.boolean('disable_right_click').defaultTo(false);
|
||||
table.boolean('watermark_downloads').defaultTo(false);
|
||||
table.text('watermark_text');
|
||||
table.integer('hero_photo_id').references('id').inTable('photos').onDelete('SET NULL');
|
||||
});
|
||||
} else {
|
||||
// Check if color_theme needs to be updated to TEXT type
|
||||
@@ -104,11 +111,39 @@ async function initializeDatabase() {
|
||||
archive_path TEXT,
|
||||
archived_at DATETIME,
|
||||
allow_user_uploads BOOLEAN DEFAULT 0,
|
||||
upload_category_id INTEGER
|
||||
upload_category_id INTEGER,
|
||||
allow_downloads BOOLEAN DEFAULT 1,
|
||||
disable_right_click BOOLEAN DEFAULT 0,
|
||||
watermark_downloads BOOLEAN DEFAULT 0,
|
||||
watermark_text TEXT,
|
||||
hero_photo_id INTEGER
|
||||
)
|
||||
`);
|
||||
|
||||
await db.raw('INSERT INTO events_new SELECT * FROM events');
|
||||
const pragmaRows = await db.raw("PRAGMA table_info('events')");
|
||||
const existingColumns = pragmaRows.map(row => row.name);
|
||||
const selectColumns = existingColumns.map((col) => {
|
||||
switch (col) {
|
||||
case 'allow_user_uploads':
|
||||
return "COALESCE(allow_user_uploads, 0) as allow_user_uploads";
|
||||
case 'upload_category_id':
|
||||
return "upload_category_id";
|
||||
case 'allow_downloads':
|
||||
return "COALESCE(allow_downloads, 1) as allow_downloads";
|
||||
case 'disable_right_click':
|
||||
return "COALESCE(disable_right_click, 0) as disable_right_click";
|
||||
case 'watermark_downloads':
|
||||
return "COALESCE(watermark_downloads, 0) as watermark_downloads";
|
||||
case 'watermark_text':
|
||||
return 'watermark_text';
|
||||
case 'hero_photo_id':
|
||||
return 'hero_photo_id';
|
||||
default:
|
||||
return col;
|
||||
}
|
||||
});
|
||||
|
||||
await db.raw(`INSERT INTO events_new (${existingColumns.join(', ')}) SELECT ${selectColumns.join(', ')} FROM events`);
|
||||
await db.raw('DROP TABLE events');
|
||||
await db.raw('ALTER TABLE events_new RENAME TO events');
|
||||
} catch (error) {
|
||||
@@ -129,6 +164,7 @@ async function initializeDatabase() {
|
||||
table.string('thumbnail_path');
|
||||
table.string('type').notNullable(); // 'collage' or 'individual'
|
||||
table.integer('size_bytes');
|
||||
table.string('uploaded_by').defaultTo('admin');
|
||||
table.datetime('uploaded_at').defaultTo(db.fn.now());
|
||||
table.integer('view_count').defaultTo(0);
|
||||
table.integer('download_count').defaultTo(0);
|
||||
@@ -159,11 +195,24 @@ async function initializeDatabase() {
|
||||
table.string('email_type').notNullable(); // 'creation', 'warning', 'expiration', 'archive_complete'
|
||||
table.json('email_data');
|
||||
table.string('status').defaultTo('pending'); // 'pending', 'sent', 'failed'
|
||||
table.datetime('created_at').defaultTo(db.fn.now());
|
||||
table.datetime('scheduled_at').defaultTo(db.fn.now());
|
||||
table.datetime('sent_at');
|
||||
table.text('error_message');
|
||||
table.integer('retry_count').defaultTo(0);
|
||||
});
|
||||
} else {
|
||||
const hasCreatedAt = await db.schema.hasColumn('email_queue', 'created_at');
|
||||
if (!hasCreatedAt) {
|
||||
await db.schema.alterTable('email_queue', (table) => {
|
||||
table.datetime('created_at').defaultTo(db.fn.now());
|
||||
});
|
||||
try {
|
||||
await db('email_queue').whereNull('created_at').update({ created_at: db.fn.now() });
|
||||
} catch (updateError) {
|
||||
logger.debug('Email queue created_at backfill skipped', { error: updateError.message });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Admin users table
|
||||
@@ -181,6 +230,7 @@ async function initializeDatabase() {
|
||||
table.datetime('updated_at').defaultTo(db.fn.now());
|
||||
table.datetime('last_login');
|
||||
table.string('last_login_ip');
|
||||
table.string('language', 2).defaultTo('en');
|
||||
});
|
||||
} else {
|
||||
// Check if updated_at column exists
|
||||
@@ -216,6 +266,13 @@ async function initializeDatabase() {
|
||||
table.string('last_login_ip');
|
||||
});
|
||||
}
|
||||
|
||||
const hasLanguage = await db.schema.hasColumn('admin_users', 'language');
|
||||
if (!hasLanguage) {
|
||||
await db.schema.table('admin_users', (table) => {
|
||||
table.string('language', 2).defaultTo('en');
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Token revocation tables
|
||||
@@ -291,6 +348,18 @@ async function initializeDatabase() {
|
||||
table.datetime('updated_at').defaultTo(db.fn.now());
|
||||
});
|
||||
}
|
||||
|
||||
const defaultLanguageSetting = await db('app_settings')
|
||||
.where('setting_key', 'default_language')
|
||||
.first();
|
||||
if (!defaultLanguageSetting) {
|
||||
await db('app_settings').insert({
|
||||
setting_key: 'default_language',
|
||||
setting_value: JSON.stringify('en'),
|
||||
setting_type: 'general',
|
||||
updated_at: new Date(),
|
||||
});
|
||||
}
|
||||
|
||||
// Activity logs table
|
||||
const hasActivityLogsTable = await db.schema.hasTable('activity_logs');
|
||||
@@ -315,6 +384,86 @@ async function initializeDatabase() {
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
await ensureGlobalCategories();
|
||||
}
|
||||
|
||||
// Ensure photo categories exist for new deployments
|
||||
async function ensureGlobalCategories() {
|
||||
const hasPhotoCategoriesTable = await db.schema.hasTable('photo_categories');
|
||||
if (!hasPhotoCategoriesTable) {
|
||||
await db.schema.createTable('photo_categories', (table) => {
|
||||
table.increments('id').primary();
|
||||
table.string('name', 100).notNullable();
|
||||
table.string('slug', 100).notNullable();
|
||||
table.boolean('is_global').defaultTo(true);
|
||||
table.integer('event_id').references('id').inTable('events').onDelete('CASCADE');
|
||||
table.timestamp('created_at').defaultTo(db.fn.now());
|
||||
table.unique(['slug', 'event_id']);
|
||||
});
|
||||
}
|
||||
|
||||
const hasCategoryIdColumn = await db.schema.hasColumn('photos', 'category_id');
|
||||
if (!hasCategoryIdColumn) {
|
||||
await db.schema.alterTable('photos', (table) => {
|
||||
table.integer('category_id').references('id').inTable('photo_categories');
|
||||
});
|
||||
}
|
||||
|
||||
const hasCmsPagesTable = await db.schema.hasTable('cms_pages');
|
||||
if (!hasCmsPagesTable) {
|
||||
await db.schema.createTable('cms_pages', (table) => {
|
||||
table.increments('id').primary();
|
||||
table.string('slug', 100).unique().notNullable();
|
||||
table.text('title_en');
|
||||
table.text('title_de');
|
||||
table.text('content_en');
|
||||
table.text('content_de');
|
||||
table.timestamp('updated_at').defaultTo(db.fn.now());
|
||||
});
|
||||
}
|
||||
|
||||
const categoryCountRow = await db('photo_categories').count({ count: 'id' }).first();
|
||||
const categoryCount = categoryCountRow ? Number(categoryCountRow.count) : 0;
|
||||
if (categoryCount === 0) {
|
||||
const defaultCategories = [
|
||||
{ name: 'Ceremony', slug: 'ceremony', is_global: true },
|
||||
{ name: 'Reception', slug: 'reception', is_global: true },
|
||||
{ name: 'Portraits', slug: 'portraits', is_global: true },
|
||||
{ name: 'Group Photos', slug: 'group-photos', is_global: true },
|
||||
{ name: 'Details', slug: 'details', is_global: true },
|
||||
{ name: 'Party', slug: 'party', is_global: true },
|
||||
];
|
||||
|
||||
await db('photo_categories').insert(defaultCategories);
|
||||
}
|
||||
|
||||
const cmsPages = await db('cms_pages').select('slug');
|
||||
const existingSlugs = cmsPages.map((page) => page.slug);
|
||||
const defaultPages = [
|
||||
{
|
||||
slug: 'impressum',
|
||||
title_en: 'Legal Notice',
|
||||
title_de: 'Impressum',
|
||||
content_en: '<h2>Legal Notice</h2><p>Please edit this content in the admin panel.</p>',
|
||||
content_de: '<h2>Impressum</h2><p>Bitte bearbeiten Sie diesen Inhalt im Admin-Panel.</p>',
|
||||
updated_at: new Date(),
|
||||
},
|
||||
{
|
||||
slug: 'datenschutz',
|
||||
title_en: 'Privacy Policy',
|
||||
title_de: 'Datenschutzerklärung',
|
||||
content_en: '<h2>Privacy Policy</h2><p>Please edit this content in the admin panel.</p>',
|
||||
content_de: '<h2>Datenschutzerklärung</h2><p>Bitte bearbeiten Sie diesen Inhalt im Admin-Panel.</p>',
|
||||
updated_at: new Date(),
|
||||
},
|
||||
];
|
||||
|
||||
for (const page of defaultPages) {
|
||||
if (!existingSlugs.includes(page.slug)) {
|
||||
await db('cms_pages').insert(page);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Helper function to log activities
|
||||
|
||||
@@ -3,13 +3,14 @@ const { db } = require('../database/db');
|
||||
const { formatBoolean } = require('../utils/dbCompat');
|
||||
const { isTokenRevoked } = require('../utils/tokenRevocation');
|
||||
const logger = require('../utils/logger');
|
||||
const { getAdminTokenFromRequest, getGalleryTokenFromRequest } = require('../utils/tokenUtils');
|
||||
|
||||
/**
|
||||
* Enhanced admin authentication middleware with revocation checking
|
||||
*/
|
||||
async function adminAuth(req, res, next) {
|
||||
try {
|
||||
const token = req.headers.authorization?.split(' ')[1];
|
||||
const token = getAdminTokenFromRequest(req);
|
||||
if (!token) {
|
||||
return res.status(401).json({ error: 'No token provided' });
|
||||
}
|
||||
@@ -97,7 +98,8 @@ async function adminAuth(req, res, next) {
|
||||
*/
|
||||
async function galleryAuth(req, res, next) {
|
||||
try {
|
||||
const token = req.headers.authorization?.split(' ')[1];
|
||||
const slug = req.params?.slug || req.requestedSlug;
|
||||
const token = getGalleryTokenFromRequest(req, slug);
|
||||
if (!token) {
|
||||
return res.status(401).json({ error: 'No token provided' });
|
||||
}
|
||||
@@ -164,4 +166,4 @@ module.exports = {
|
||||
adminAuth,
|
||||
galleryAuth,
|
||||
// ... other exports
|
||||
};
|
||||
};
|
||||
|
||||
@@ -2,6 +2,7 @@ const jwt = require('jsonwebtoken');
|
||||
const { db } = require('../database/db');
|
||||
const { formatBoolean } = require('../utils/dbCompat');
|
||||
const logger = require('../utils/logger');
|
||||
const { getAdminTokenFromRequest, getGalleryTokenFromRequest } = require('../utils/tokenUtils');
|
||||
|
||||
/**
|
||||
* Enhanced admin authentication middleware
|
||||
@@ -9,7 +10,7 @@ const logger = require('../utils/logger');
|
||||
*/
|
||||
async function adminAuth(req, res, next) {
|
||||
try {
|
||||
const token = req.headers.authorization?.split(' ')[1];
|
||||
const token = getAdminTokenFromRequest(req);
|
||||
if (!token) {
|
||||
return res.status(401).json({ error: 'No token provided' });
|
||||
}
|
||||
@@ -89,7 +90,8 @@ async function adminAuth(req, res, next) {
|
||||
*/
|
||||
async function galleryAuth(req, res, next) {
|
||||
try {
|
||||
const token = req.headers.authorization?.split(' ')[1];
|
||||
const slug = req.params?.slug || req.requestedSlug;
|
||||
const token = getGalleryTokenFromRequest(req, slug);
|
||||
if (!token) {
|
||||
return res.status(401).json({ error: 'No token provided' });
|
||||
}
|
||||
@@ -151,7 +153,8 @@ async function galleryAuth(req, res, next) {
|
||||
*/
|
||||
async function photoAuth(req, res, next) {
|
||||
try {
|
||||
const token = req.headers.authorization?.split(' ')[1];
|
||||
const slug = req.params?.slug || req.requestedSlug;
|
||||
const token = getAdminTokenFromRequest(req) || getGalleryTokenFromRequest(req, slug);
|
||||
if (!token) {
|
||||
return res.status(401).json({ error: 'Authentication required' });
|
||||
}
|
||||
@@ -235,4 +238,4 @@ module.exports = {
|
||||
galleryAuth,
|
||||
photoAuth,
|
||||
verifyGalleryAccess
|
||||
};
|
||||
};
|
||||
|
||||
@@ -2,10 +2,11 @@ const jwt = require('jsonwebtoken');
|
||||
const { db } = require('../database/db');
|
||||
const { formatBoolean } = require('../utils/dbCompat');
|
||||
const logger = require('../utils/logger');
|
||||
const { getAdminTokenFromRequest } = require('../utils/tokenUtils');
|
||||
|
||||
async function adminAuth(req, res, next) {
|
||||
try {
|
||||
const token = req.headers.authorization?.split(' ')[1];
|
||||
const token = getAdminTokenFromRequest(req);
|
||||
if (!token) {
|
||||
const clientIp = req.headers['x-forwarded-for']?.split(',')[0]?.trim() ||
|
||||
req.headers['x-real-ip'] ||
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
const jwt = require('jsonwebtoken');
|
||||
const { db, withRetry } = require('../database/db');
|
||||
const { formatBoolean } = require('../utils/dbCompat');
|
||||
const { getGalleryTokenFromRequest } = require('../utils/tokenUtils');
|
||||
|
||||
// Middleware to verify gallery access
|
||||
async function verifyGalleryAccess(req, res, next) {
|
||||
try {
|
||||
const authHeader = req.headers.authorization;
|
||||
const token = authHeader?.split(' ')[1];
|
||||
const requestedSlug = req.params.slug || req.requestedSlug;
|
||||
const token = getGalleryTokenFromRequest(req, requestedSlug);
|
||||
if (!token) {
|
||||
return res.status(401).json({ error: 'No token provided' });
|
||||
}
|
||||
|
||||
|
||||
// Try to verify with issuer first, fallback to no issuer for backward compatibility
|
||||
let decoded;
|
||||
try {
|
||||
@@ -29,8 +29,6 @@ async function verifyGalleryAccess(req, res, next) {
|
||||
console.log('[verifyGalleryAccess] Token decoded successfully, eventId:', decoded.eventId);
|
||||
|
||||
// If we have a slug in the URL params or from pre-middleware, verify it matches
|
||||
const requestedSlug = req.params.slug || req.requestedSlug;
|
||||
|
||||
let event;
|
||||
if (requestedSlug) {
|
||||
// Verify by slug and ensure it matches the token's event
|
||||
@@ -84,10 +82,10 @@ async function verifyGalleryAccess(req, res, next) {
|
||||
next();
|
||||
} catch (error) {
|
||||
console.error('Error verifying gallery access:', error);
|
||||
res.status(401).json({ error: 'Invalid token', details: error.message });
|
||||
res.status(401).json({ error: 'Invalid token' });
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
verifyGalleryAccess
|
||||
};
|
||||
};
|
||||
|
||||
@@ -2,6 +2,7 @@ const bcrypt = require('bcrypt');
|
||||
const jwt = require('jsonwebtoken');
|
||||
const { db } = require('../database/db');
|
||||
const { formatBoolean } = require('../utils/dbCompat');
|
||||
const { getGalleryTokenFromRequest } = require('../utils/tokenUtils');
|
||||
|
||||
async function photoAuth(req, res, next) {
|
||||
try {
|
||||
@@ -20,9 +21,9 @@ async function photoAuth(req, res, next) {
|
||||
}
|
||||
|
||||
// First check for JWT token (from gallery access)
|
||||
const authHeader = req.headers.authorization;
|
||||
if (authHeader && authHeader.startsWith('Bearer ')) {
|
||||
const token = authHeader.replace('Bearer ', '');
|
||||
const tokenFromRequest = getGalleryTokenFromRequest(req, eventSlug);
|
||||
if (tokenFromRequest) {
|
||||
const token = tokenFromRequest;
|
||||
try {
|
||||
// Try to verify with issuer first, fallback to no issuer for backward compatibility
|
||||
let decoded;
|
||||
@@ -88,7 +89,7 @@ async function photoAuth(req, res, next) {
|
||||
// Check for password header (legacy support)
|
||||
const password = req.headers['x-gallery-password'];
|
||||
|
||||
if (!password && !authHeader) {
|
||||
if (!password && !tokenFromRequest) {
|
||||
return res.status(401).json({ error: 'Authentication required' });
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
const jwt = require('jsonwebtoken');
|
||||
const { db } = require('../database/db');
|
||||
const { getAdminTokenFromRequest } = require('../utils/tokenUtils');
|
||||
|
||||
// In-memory session tracking (in production, use Redis)
|
||||
const sessions = new Map();
|
||||
@@ -67,11 +68,7 @@ async function getSessionTimeout() {
|
||||
|
||||
async function sessionTimeoutMiddleware(req, res, next) {
|
||||
// Skip for non-authenticated routes
|
||||
if (!req.headers.authorization) {
|
||||
return next();
|
||||
}
|
||||
|
||||
const token = req.headers.authorization.split(' ')[1];
|
||||
const token = getAdminTokenFromRequest(req);
|
||||
if (!token) {
|
||||
return next();
|
||||
}
|
||||
@@ -150,4 +147,4 @@ module.exports = {
|
||||
sessionTimeoutMiddleware,
|
||||
endSession,
|
||||
getActiveSessions
|
||||
};
|
||||
};
|
||||
|
||||
@@ -221,7 +221,11 @@ router.post('/test-connection', adminAuth, async (req, res) => {
|
||||
await fs.access(config.path, fs.constants.W_OK);
|
||||
res.json({ success: true, message: 'Local path is writable' });
|
||||
} catch (error) {
|
||||
res.json({ success: false, message: 'Cannot write to local path: ' + error.message });
|
||||
logger.warn('Local backup path not writable', {
|
||||
path: config.path,
|
||||
error: error.message
|
||||
});
|
||||
res.json({ success: false, message: 'Cannot write to local path. Check server logs for details.' });
|
||||
}
|
||||
break;
|
||||
|
||||
@@ -243,7 +247,11 @@ router.post('/test-connection', adminAuth, async (req, res) => {
|
||||
const { stdout } = await execAsync(testCommand);
|
||||
res.json({ success: true, message: 'Rsync connection successful' });
|
||||
} catch (error) {
|
||||
res.json({ success: false, message: 'Rsync connection failed: ' + error.message });
|
||||
logger.warn('Rsync connection test failed', {
|
||||
destination: config.host || config.destination,
|
||||
error: error.message
|
||||
});
|
||||
res.json({ success: false, message: 'Rsync connection failed. Check server logs for details.' });
|
||||
}
|
||||
break;
|
||||
|
||||
@@ -274,7 +282,7 @@ router.get('/manifest/:backupRunId', adminAuth, async (req, res) => {
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error('Failed to get backup manifest:', error);
|
||||
res.status(404).json({ error: error.message || 'Backup manifest not found' });
|
||||
res.status(404).json({ error: 'Backup manifest not found' });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -327,7 +335,7 @@ router.get('/manifest/:backupRunId/download', adminAuth, async (req, res) => {
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error('Failed to download backup manifest:', error);
|
||||
res.status(404).json({ error: error.message || 'Backup manifest not found' });
|
||||
res.status(404).json({ error: 'Backup manifest not found' });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -344,7 +352,7 @@ router.get('/manifests/:backupId', adminAuth, async (req, res) => {
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error('Failed to get backup manifest:', error);
|
||||
res.status(404).json({ error: error.message || 'Backup manifest not found' });
|
||||
res.status(404).json({ error: 'Backup manifest not found' });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -375,7 +383,7 @@ router.get('/manifests/:backupId/download', adminAuth, async (req, res) => {
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error('Failed to download backup manifest:', error);
|
||||
res.status(404).json({ error: error.message || 'Backup manifest not found' });
|
||||
res.status(404).json({ error: 'Backup manifest not found' });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -436,7 +444,7 @@ router.get('/s3/buckets', adminAuth, async (req, res) => {
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error('Failed to list S3 buckets:', error);
|
||||
res.status(500).json({ error: 'Failed to list S3 buckets: ' + error.message });
|
||||
res.status(500).json({ error: 'Failed to list S3 buckets' });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -473,7 +481,7 @@ router.get('/s3/files', adminAuth, async (req, res) => {
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error('Failed to list S3 files:', error);
|
||||
res.status(500).json({ error: 'Failed to list S3 files: ' + error.message });
|
||||
res.status(500).json({ error: 'Failed to list S3 files' });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -535,7 +543,7 @@ router.delete('/s3/cleanup', adminAuth, async (req, res) => {
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error('Failed to cleanup S3 backups:', error);
|
||||
res.status(500).json({ error: 'Failed to cleanup S3 backups: ' + error.message });
|
||||
res.status(500).json({ error: 'Failed to cleanup S3 backups' });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -587,7 +595,7 @@ router.post('/s3/test-upload', adminAuth, async (req, res) => {
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error('S3 upload test failed:', error);
|
||||
res.status(500).json({ error: 'S3 upload test failed: ' + error.message });
|
||||
res.status(500).json({ error: 'S3 upload test failed' });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -675,7 +683,7 @@ router.get('/download/:backupId', adminAuth, async (req, res) => {
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error('Failed to download backup:', error);
|
||||
res.status(500).json({ error: 'Failed to download backup: ' + error.message });
|
||||
res.status(500).json({ error: 'Failed to download backup' });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -744,7 +752,7 @@ router.get('/checksums', adminAuth, async (req, res) => {
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error('Failed to get file checksums:', error);
|
||||
res.status(500).json({ error: 'Failed to get file checksums: ' + error.message });
|
||||
res.status(500).json({ error: 'Failed to get file checksums' });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -847,7 +855,7 @@ router.post('/estimate', adminAuth, async (req, res) => {
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error('Failed to estimate backup size:', error);
|
||||
res.status(500).json({ error: 'Failed to estimate backup size: ' + error.message });
|
||||
res.status(500).json({ error: 'Failed to estimate backup size' });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -945,12 +953,13 @@ async function validateManifestData(manifestData) {
|
||||
}
|
||||
};
|
||||
} catch (error) {
|
||||
logger.error('Manifest validation error', { error: error.message });
|
||||
return {
|
||||
valid: false,
|
||||
error: `Validation error: ${error.message}`,
|
||||
details: { error: error.message }
|
||||
error: 'Validation error encountered while processing manifest',
|
||||
details: { hint: 'See server logs for diagnostic details.' }
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = router;
|
||||
module.exports = router;
|
||||
|
||||
@@ -515,13 +515,11 @@ router.delete('/:id', adminAuth, async (req, res) => {
|
||||
// Provide more specific error messages
|
||||
if (error.message && error.message.includes('foreign key constraint')) {
|
||||
res.status(500).json({
|
||||
error: 'Cannot delete event due to existing references. Please contact support.',
|
||||
details: error.message
|
||||
error: 'Cannot delete event due to existing references. Please contact support.'
|
||||
});
|
||||
} else {
|
||||
res.status(500).json({
|
||||
error: 'Failed to delete event',
|
||||
details: process.env.NODE_ENV === 'development' ? error.message : undefined
|
||||
error: 'Failed to delete event'
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -780,7 +778,7 @@ router.post('/bulk-archive', adminAuth, [
|
||||
results.failed.push({
|
||||
id: event.id,
|
||||
name: event.event_name,
|
||||
error: error.message
|
||||
error: 'Failed to archive event. Check server logs for details.'
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -806,4 +804,4 @@ router.post('/bulk-archive', adminAuth, [
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
module.exports = router;
|
||||
|
||||
@@ -4,6 +4,7 @@ const fs = require('fs').promises;
|
||||
const { adminAuth } = require('../middleware/auth');
|
||||
const { list, resolveExternalPath, getExternalMediaRoot } = require('../services/externalMediaService');
|
||||
const { db, logActivity } = require('../database/db');
|
||||
const logger = require('../utils/logger');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
@@ -14,7 +15,11 @@ router.get('/list', adminAuth, async (req, res) => {
|
||||
const result = await list(relPath);
|
||||
res.json(result);
|
||||
} catch (error) {
|
||||
res.status(400).json({ error: 'Invalid path', details: error.message });
|
||||
logger.warn('Invalid external media path requested', {
|
||||
path: req.query.path,
|
||||
error: error.message
|
||||
});
|
||||
res.status(400).json({ error: 'Invalid external media path' });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -104,9 +109,13 @@ router.post('/events/:id/import-external', adminAuth, async (req, res) => {
|
||||
|
||||
res.json({ imported, skipped, thumbnailsQueued: 0 });
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: 'Failed to import external media', details: error.message });
|
||||
logger.error('External media import failed', {
|
||||
eventId: req.params.id,
|
||||
externalPath: req.body?.external_path,
|
||||
error: error.message
|
||||
});
|
||||
res.status(500).json({ error: 'Failed to import external media' });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
|
||||
|
||||
@@ -368,7 +368,7 @@ router.post('/word-filters',
|
||||
res.json({ success: true });
|
||||
} catch (error) {
|
||||
if (error.message === 'Word filter already exists') {
|
||||
return res.status(409).json({ error: error.message });
|
||||
return res.status(409).json({ error: 'Word filter already exists' });
|
||||
}
|
||||
logger.error('Error adding word filter:', error);
|
||||
res.status(500).json({ error: 'Failed to add word filter' });
|
||||
@@ -430,4 +430,4 @@ function convertToCSV(data) {
|
||||
return [csvHeaders, ...csvRows].join('\n');
|
||||
}
|
||||
|
||||
module.exports = router;
|
||||
module.exports = router;
|
||||
|
||||
@@ -802,7 +802,8 @@ router.get('/:eventId/debug', adminAuth, async (req, res) => {
|
||||
storagePath: getStoragePath()
|
||||
});
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: error.message });
|
||||
console.error('Error fetching admin photo debug data:', error);
|
||||
res.status(500).json({ error: 'Failed to fetch photo debug data' });
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -82,7 +82,7 @@ router.post('/validate', [
|
||||
logger.error('Restore validation failed:', error);
|
||||
res.status(400).json({
|
||||
success: false,
|
||||
error: error.message,
|
||||
error: 'Restore validation failed',
|
||||
logs: restoreService.restoreLog
|
||||
});
|
||||
}
|
||||
@@ -162,7 +162,7 @@ router.post('/start', [
|
||||
logger.error('Failed to start restore:', error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
error: error.message
|
||||
error: 'Failed to start restore operation'
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -458,4 +458,4 @@ async function getBackupConfig() {
|
||||
return config;
|
||||
}
|
||||
|
||||
module.exports = router;
|
||||
module.exports = router;
|
||||
|
||||
@@ -5,6 +5,7 @@ const fs = require('fs').promises;
|
||||
const path = require('path');
|
||||
const os = require('os');
|
||||
const { formatBoolean } = require('../utils/dbCompat');
|
||||
const logger = require('../utils/logger');
|
||||
const router = express.Router();
|
||||
|
||||
// Get system version
|
||||
@@ -208,10 +209,14 @@ router.get('/database', adminAuth, async (req, res) => {
|
||||
});
|
||||
} catch (error) {
|
||||
// Table might not exist
|
||||
logger.warn('Failed to retrieve table info', {
|
||||
table,
|
||||
error: error.message
|
||||
});
|
||||
tableInfo.push({
|
||||
name: table,
|
||||
rows: 0,
|
||||
error: error.message
|
||||
error: 'Unable to retrieve table details'
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -226,4 +231,4 @@ router.get('/database', adminAuth, async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
module.exports = router;
|
||||
|
||||
@@ -14,6 +14,14 @@ const {
|
||||
} = require('../utils/authSecurity');
|
||||
const { endSession } = require('../middleware/sessionTimeout');
|
||||
const logger = require('../utils/logger');
|
||||
const {
|
||||
setAdminAuthCookie,
|
||||
clearAdminAuthCookie,
|
||||
setGalleryAuthCookies,
|
||||
clearGalleryAuthCookies,
|
||||
getAdminTokenFromRequest,
|
||||
getGalleryTokenFromRequest,
|
||||
} = require('../utils/tokenUtils');
|
||||
const router = express.Router();
|
||||
|
||||
// Admin login with enhanced security
|
||||
@@ -91,6 +99,8 @@ router.post('/admin/login', [
|
||||
expiresIn: '24h',
|
||||
issuer: 'picpeak-auth'
|
||||
});
|
||||
|
||||
setAdminAuthCookie(res, token);
|
||||
|
||||
res.json({
|
||||
token,
|
||||
@@ -110,13 +120,14 @@ router.post('/admin/login', [
|
||||
// Logout endpoint
|
||||
router.post('/logout', async (req, res) => {
|
||||
try {
|
||||
const token = req.headers.authorization?.split(' ')[1];
|
||||
|
||||
const adminToken = getAdminTokenFromRequest(req);
|
||||
const galleryToken = getGalleryTokenFromRequest(req);
|
||||
const token = adminToken || galleryToken;
|
||||
|
||||
if (token) {
|
||||
// End the session
|
||||
endSession(token);
|
||||
|
||||
// Log the logout
|
||||
|
||||
try {
|
||||
const decoded = jwt.verify(token, process.env.JWT_SECRET);
|
||||
logger.info('User logged out', {
|
||||
@@ -124,11 +135,23 @@ router.post('/logout', async (req, res) => {
|
||||
username: decoded.username,
|
||||
type: decoded.type
|
||||
});
|
||||
|
||||
if (decoded.type === 'admin') {
|
||||
clearAdminAuthCookie(res);
|
||||
} else if (decoded.type === 'gallery') {
|
||||
clearGalleryAuthCookies(res, decoded.eventSlug);
|
||||
}
|
||||
} catch (err) {
|
||||
// Token might be invalid, but still process logout
|
||||
// Token might be invalid, but still process logout and clear cookies
|
||||
clearAdminAuthCookie(res);
|
||||
clearGalleryAuthCookies(res);
|
||||
}
|
||||
} else {
|
||||
// No token found, but ensure cookies are cleared
|
||||
clearAdminAuthCookie(res);
|
||||
clearGalleryAuthCookies(res);
|
||||
}
|
||||
|
||||
|
||||
res.json({ message: 'Logged out successfully' });
|
||||
} catch (error) {
|
||||
logger.error('Logout error:', error);
|
||||
@@ -209,6 +232,8 @@ router.post('/gallery/verify', [
|
||||
expiresIn: '24h',
|
||||
issuer: 'picpeak-auth'
|
||||
});
|
||||
|
||||
setGalleryAuthCookies(res, token, event.slug);
|
||||
|
||||
res.json({
|
||||
token,
|
||||
@@ -230,15 +255,94 @@ router.post('/gallery/verify', [
|
||||
}
|
||||
});
|
||||
|
||||
// Share link authentication (token-based)
|
||||
router.post('/gallery/share-login', [
|
||||
body('slug').notEmpty().trim(),
|
||||
body('token').notEmpty()
|
||||
], async (req, res) => {
|
||||
try {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) {
|
||||
return res.status(400).json({ errors: errors.array() });
|
||||
}
|
||||
|
||||
const { slug, token } = req.body;
|
||||
const ipAddress = req.ip || req.connection.remoteAddress;
|
||||
const userAgent = req.headers['user-agent'] || '';
|
||||
|
||||
const event = await db('events')
|
||||
.where({ slug, is_active: formatBoolean(true), is_archived: formatBoolean(false) })
|
||||
.first();
|
||||
|
||||
if (!event) {
|
||||
return res.status(404).json({ error: 'Gallery not found' });
|
||||
}
|
||||
|
||||
let expectedToken = event.share_link;
|
||||
if (expectedToken && expectedToken.includes('/')) {
|
||||
expectedToken = expectedToken.split('/').pop();
|
||||
}
|
||||
|
||||
if (!expectedToken || token !== expectedToken) {
|
||||
return res.status(401).json({ error: 'Invalid or expired share link' });
|
||||
}
|
||||
|
||||
const jwtToken = jwt.sign({
|
||||
eventId: event.id,
|
||||
eventSlug: event.slug,
|
||||
type: 'gallery',
|
||||
ip: ipAddress,
|
||||
loginTime: Date.now()
|
||||
}, process.env.JWT_SECRET, {
|
||||
expiresIn: '24h',
|
||||
issuer: 'picpeak-auth'
|
||||
});
|
||||
|
||||
await trackSuccessfulLogin(`gallery:${slug}:share`, ipAddress, userAgent);
|
||||
setGalleryAuthCookies(res, jwtToken, event.slug);
|
||||
|
||||
res.json({
|
||||
token: jwtToken,
|
||||
event: {
|
||||
id: event.id,
|
||||
event_name: event.event_name,
|
||||
event_type: event.event_type,
|
||||
event_date: event.event_date,
|
||||
welcome_message: event.welcome_message,
|
||||
color_theme: event.color_theme,
|
||||
expires_at: event.expires_at,
|
||||
allow_user_uploads: event.allow_user_uploads,
|
||||
upload_category_id: event.upload_category_id
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error('Share link authentication error:', error);
|
||||
res.status(500).json({ error: 'Share link login failed' });
|
||||
}
|
||||
});
|
||||
|
||||
// Gallery logout to clear cookies
|
||||
router.post('/gallery/logout', async (req, res) => {
|
||||
try {
|
||||
const { slug } = req.body || {};
|
||||
clearGalleryAuthCookies(res, slug);
|
||||
res.json({ message: 'Logged out successfully' });
|
||||
} catch (error) {
|
||||
logger.error('Gallery logout error:', error);
|
||||
res.status(500).json({ error: 'Logout failed' });
|
||||
}
|
||||
});
|
||||
|
||||
// Get current session info
|
||||
router.get('/session', async (req, res) => {
|
||||
try {
|
||||
const token = req.headers.authorization?.split(' ')[1];
|
||||
const { slug } = req.query;
|
||||
const token = getAdminTokenFromRequest(req) || getGalleryTokenFromRequest(req, slug);
|
||||
|
||||
if (!token) {
|
||||
return res.status(401).json({ error: 'No token provided' });
|
||||
}
|
||||
|
||||
|
||||
try {
|
||||
const decoded = jwt.verify(token, process.env.JWT_SECRET);
|
||||
|
||||
@@ -250,7 +354,9 @@ router.get('/session', async (req, res) => {
|
||||
valid: true,
|
||||
type: decoded.type,
|
||||
expiresIn: Math.floor(remainingTime),
|
||||
user: decoded.username || decoded.eventSlug
|
||||
user: decoded.username || decoded.eventSlug,
|
||||
eventSlug: decoded.eventSlug,
|
||||
adminUsername: decoded.username
|
||||
});
|
||||
} catch (err) {
|
||||
res.json({
|
||||
@@ -263,4 +369,4 @@ router.get('/session', async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
module.exports = router;
|
||||
|
||||
+120
-39
@@ -37,7 +37,7 @@ router.get('/:slug/verify-token/:token', async (req, res) => {
|
||||
res.json({ valid: true });
|
||||
} catch (error) {
|
||||
console.error('Error verifying token:', error);
|
||||
res.status(500).json({ error: 'Failed to verify token', details: error.message });
|
||||
res.status(500).json({ error: 'Failed to verify token' });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -90,7 +90,7 @@ router.get('/:slug/info', async (req, res) => {
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error fetching gallery info:', error);
|
||||
res.status(500).json({ error: 'Failed to fetch gallery info', details: error.message });
|
||||
res.status(500).json({ error: 'Failed to fetch gallery info' });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -107,30 +107,39 @@ router.get('/:slug/photos', verifyGalleryAccess, async (req, res) => {
|
||||
.select('photos.*')
|
||||
.orderBy('photos.uploaded_at', 'desc');
|
||||
|
||||
// Apply filtering if requested
|
||||
if (filter && guest_id) {
|
||||
let filters = {};
|
||||
|
||||
// Parse filter parameter
|
||||
if (filter === 'liked') {
|
||||
filters.liked = true;
|
||||
} else if (filter === 'favorited') {
|
||||
filters.favorited = true;
|
||||
} else if (filter === 'liked,favorited' || filter === 'favorited,liked') {
|
||||
filters.liked = true;
|
||||
filters.favorited = true;
|
||||
filters.operator = 'OR';
|
||||
// Apply filtering if requested (global, based on aggregate counts)
|
||||
if (filter) {
|
||||
const f = String(filter).toLowerCase();
|
||||
const parts = f.split(',').map(s => s.trim());
|
||||
const include = new Set();
|
||||
|
||||
// Helper to include IDs for a predicate
|
||||
const includeBy = (predicate) => {
|
||||
photos.forEach(p => { if (predicate(p)) include.add(p.id); });
|
||||
};
|
||||
|
||||
if (parts.includes('liked')) {
|
||||
includeBy(p => (p.like_count || 0) > 0);
|
||||
}
|
||||
if (parts.includes('favorited')) {
|
||||
includeBy(p => (p.favorite_count || 0) > 0);
|
||||
}
|
||||
if (parts.includes('rated')) {
|
||||
includeBy(p => (p.average_rating || 0) > 0);
|
||||
}
|
||||
if (parts.includes('commented')) {
|
||||
// Query commented photo IDs
|
||||
const commented = await db('photo_feedback')
|
||||
.where({ event_id: req.event.id, feedback_type: 'comment', is_approved: true, is_hidden: false })
|
||||
.groupBy('photo_id')
|
||||
.select('photo_id');
|
||||
const commentedIds = new Set(commented.map(c => c.photo_id));
|
||||
includeBy(p => commentedIds.has(p.id));
|
||||
}
|
||||
|
||||
if (include.size > 0) {
|
||||
photos = photos.filter(p => include.has(p.id));
|
||||
}
|
||||
|
||||
// Get filtered photo IDs
|
||||
const filteredPhotoIds = await feedbackService.getFilteredPhotos(
|
||||
req.event.id,
|
||||
guest_id,
|
||||
filters
|
||||
);
|
||||
|
||||
// Filter photos to only include those with feedback
|
||||
photos = photos.filter(photo => filteredPhotoIds.includes(photo.id));
|
||||
}
|
||||
|
||||
// Then get comment counts separately
|
||||
@@ -230,7 +239,7 @@ router.get('/:slug/photos', verifyGalleryAccess, async (req, res) => {
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error fetching photos:', error);
|
||||
res.status(500).json({ error: 'Failed to fetch photos', details: error.message });
|
||||
res.status(500).json({ error: 'Failed to fetch photos' });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -384,6 +393,87 @@ router.get('/:slug/download-all', verifyGalleryAccess, async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
// Download selected photos as ZIP
|
||||
router.post('/:slug/download-selected', verifyGalleryAccess, async (req, res) => {
|
||||
try {
|
||||
// Check if downloads are allowed for this event
|
||||
if (req.event.allow_downloads === false) {
|
||||
return res.status(403).json({ error: 'Downloads are disabled for this gallery' });
|
||||
}
|
||||
|
||||
const ids = Array.isArray(req.body?.photo_ids) ? req.body.photo_ids : [];
|
||||
if (!ids.length) {
|
||||
return res.status(400).json({ error: 'photo_ids is required (non-empty array)' });
|
||||
}
|
||||
|
||||
// Clean IDs
|
||||
const photoIds = ids
|
||||
.map((v) => parseInt(v, 10))
|
||||
.filter((v) => Number.isInteger(v))
|
||||
.slice(0, 500);
|
||||
|
||||
if (photoIds.length === 0) {
|
||||
return res.status(400).json({ error: 'No valid photo IDs provided' });
|
||||
}
|
||||
|
||||
// Fetch photos
|
||||
const photos = await db('photos')
|
||||
.where('photos.event_id', req.event.id)
|
||||
.whereIn('photos.id', photoIds)
|
||||
.select('photos.*')
|
||||
.orderBy('photos.uploaded_at', 'desc');
|
||||
|
||||
if (photos.length === 0) {
|
||||
return res.status(404).json({ error: 'No photos found for selected IDs' });
|
||||
}
|
||||
|
||||
const archiveName = `${req.event.slug}-selected.zip`;
|
||||
res.setHeader('Content-Type', 'application/zip');
|
||||
res.setHeader('Content-Disposition', `attachment; filename="${archiveName}"`);
|
||||
|
||||
const archive = archiver('zip', { zlib: { level: 5 } });
|
||||
archive.on('error', (err) => {
|
||||
console.error('Zip error:', err);
|
||||
try { res.status(500).end(); } catch (e) {}
|
||||
});
|
||||
archive.pipe(res);
|
||||
|
||||
const { resolvePhotoFilePath } = require('../services/photoResolver');
|
||||
const fs = require('fs');
|
||||
// Check watermark settings similar to download-all
|
||||
const watermarkSettings = await watermarkService.getWatermarkSettings();
|
||||
for (const photo of photos) {
|
||||
try {
|
||||
const filePath = resolvePhotoFilePath(req.event, photo);
|
||||
if (filePath && fs.existsSync(filePath)) {
|
||||
const name = photo.filename || `photo-${photo.id}.jpg`;
|
||||
if (watermarkSettings && watermarkSettings.enabled) {
|
||||
// Apply watermark like download-all
|
||||
const watermarkedBuffer = await watermarkService.applyWatermark(filePath, watermarkSettings);
|
||||
archive.append(watermarkedBuffer, { name });
|
||||
} else {
|
||||
archive.file(filePath, { name });
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
// skip missing/inaccessible files
|
||||
}
|
||||
}
|
||||
|
||||
await archive.finalize();
|
||||
|
||||
await db('access_logs').insert({
|
||||
event_id: req.event.id,
|
||||
ip_address: req.ip,
|
||||
user_agent: req.headers['user-agent'],
|
||||
action: 'download_selected'
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error in download-selected:', error);
|
||||
res.status(500).json({ error: 'Failed to download selected photos' });
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
// View single photo (with watermark if enabled)
|
||||
router.get('/:slug/photo/:photoId',
|
||||
@@ -413,18 +503,9 @@ router.get('/:slug/photo/:photoId',
|
||||
});
|
||||
}
|
||||
|
||||
// Photo path should be in storage/events/active directory
|
||||
// Handle both legacy paths (just slug/filename) and new paths (events/active/slug/filename)
|
||||
const storagePath = getStoragePath();
|
||||
|
||||
let filePath;
|
||||
if (photo.path.startsWith('events/active/')) {
|
||||
// New format: path already includes events/active/ prefix
|
||||
filePath = path.join(storagePath, photo.path);
|
||||
} else {
|
||||
// Legacy format: path is just slug/filename
|
||||
filePath = path.join(storagePath, 'events/active', photo.path);
|
||||
}
|
||||
// Resolve the absolute file path for this photo, supporting both managed and external reference modes
|
||||
const { resolvePhotoFilePath } = require('../services/photoResolver');
|
||||
const filePath = resolvePhotoFilePath(req.event, photo);
|
||||
|
||||
|
||||
// Log access - temporarily disabled for debugging
|
||||
@@ -466,7 +547,7 @@ router.get('/:slug/photo/:photoId',
|
||||
photoId: req.params.photoId,
|
||||
eventId: req.event?.id
|
||||
});
|
||||
res.status(500).json({ error: 'Failed to serve photo', details: error.message });
|
||||
res.status(500).json({ error: 'Failed to serve photo' });
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
@@ -2,6 +2,7 @@ const rateLimit = require('express-rate-limit');
|
||||
const jwt = require('jsonwebtoken');
|
||||
const { db } = require('../database/db');
|
||||
const logger = require('../utils/logger');
|
||||
const { getAdminTokenFromRequest, getGalleryTokenFromRequest } = require('../utils/tokenUtils');
|
||||
|
||||
// Cache for rate limit settings
|
||||
let settingsCache = null;
|
||||
@@ -95,12 +96,9 @@ function clearSettingsCache() {
|
||||
*/
|
||||
function isAuthenticated(req) {
|
||||
try {
|
||||
const authHeader = req.headers.authorization;
|
||||
if (!authHeader || !authHeader.startsWith('Bearer ')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const token = authHeader.substring(7);
|
||||
const slugMatch = req.path.match(/\/api\/(?:gallery|secure-images)\/([^\/]+)/);
|
||||
const slug = slugMatch ? slugMatch[1] : req.requestedSlug;
|
||||
const token = getAdminTokenFromRequest(req) || getGalleryTokenFromRequest(req, slug);
|
||||
const decoded = jwt.verify(token, process.env.JWT_SECRET);
|
||||
|
||||
// Check if token is valid
|
||||
@@ -280,4 +278,4 @@ module.exports = {
|
||||
createAuthRateLimiter,
|
||||
isAuthenticated,
|
||||
shouldSkipRateLimit
|
||||
};
|
||||
};
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
const ADMIN_COOKIE_NAME = 'admin_token';
|
||||
const GALLERY_COOKIE_NAME = 'gallery_token';
|
||||
const GALLERY_COOKIE_PREFIX = 'gallery_token_';
|
||||
|
||||
const DEFAULT_MAX_AGE_MS = 24 * 60 * 60 * 1000; // 24 hours
|
||||
|
||||
const secureCookie = (() => {
|
||||
if (typeof process.env.COOKIE_SECURE === 'string') {
|
||||
return process.env.COOKIE_SECURE.toLowerCase() === 'true';
|
||||
}
|
||||
// Default to false so native HTTP installs stay functional. Operators can
|
||||
// opt-in via COOKIE_SECURE=true when serving behind HTTPS.
|
||||
return false;
|
||||
})();
|
||||
const sameSiteDefault = process.env.COOKIE_SAMESITE || 'Lax';
|
||||
const cookieDomain = process.env.COOKIE_DOMAIN;
|
||||
|
||||
function buildCookieBaseOptions() {
|
||||
const options = {
|
||||
httpOnly: true,
|
||||
secure: secureCookie,
|
||||
sameSite: sameSiteDefault,
|
||||
path: '/',
|
||||
};
|
||||
|
||||
if (cookieDomain) {
|
||||
options.domain = cookieDomain;
|
||||
}
|
||||
|
||||
return options;
|
||||
}
|
||||
|
||||
function buildCookieOptionsWithExpiry(maxAgeMs = DEFAULT_MAX_AGE_MS) {
|
||||
return {
|
||||
...buildCookieBaseOptions(),
|
||||
maxAge: maxAgeMs,
|
||||
};
|
||||
}
|
||||
|
||||
function sanitizeSlugForCookie(slug = '') {
|
||||
return String(slug).replace(/[^A-Za-z0-9_-]/g, '_');
|
||||
}
|
||||
|
||||
function setAdminAuthCookie(res, token) {
|
||||
if (!token) return;
|
||||
res.cookie(ADMIN_COOKIE_NAME, token, buildCookieOptionsWithExpiry());
|
||||
}
|
||||
|
||||
function clearAdminAuthCookie(res) {
|
||||
res.clearCookie(ADMIN_COOKIE_NAME, buildCookieBaseOptions());
|
||||
}
|
||||
|
||||
function setGalleryAuthCookies(res, token, slug) {
|
||||
if (!token) return;
|
||||
const options = buildCookieOptionsWithExpiry();
|
||||
res.cookie(GALLERY_COOKIE_NAME, token, options);
|
||||
if (slug) {
|
||||
const cookieName = `${GALLERY_COOKIE_PREFIX}${sanitizeSlugForCookie(slug)}`;
|
||||
res.cookie(cookieName, token, options);
|
||||
}
|
||||
}
|
||||
|
||||
function clearGalleryAuthCookies(res, slug) {
|
||||
const baseOptions = buildCookieBaseOptions();
|
||||
res.clearCookie(GALLERY_COOKIE_NAME, baseOptions);
|
||||
|
||||
const cookies = res.req?.cookies || {};
|
||||
|
||||
if (slug) {
|
||||
const cookieName = `${GALLERY_COOKIE_PREFIX}${sanitizeSlugForCookie(slug)}`;
|
||||
res.clearCookie(cookieName, baseOptions);
|
||||
} else {
|
||||
Object.keys(cookies).forEach((name) => {
|
||||
if (name.startsWith(GALLERY_COOKIE_PREFIX)) {
|
||||
res.clearCookie(name, baseOptions);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function getAdminTokenFromRequest(req) {
|
||||
const header = req.headers?.authorization;
|
||||
if (header && header.startsWith('Bearer ')) {
|
||||
return header.substring(7);
|
||||
}
|
||||
return req.cookies?.[ADMIN_COOKIE_NAME] || null;
|
||||
}
|
||||
|
||||
function getGalleryTokenFromRequest(req, slug) {
|
||||
const header = req.headers?.authorization;
|
||||
if (header && header.startsWith('Bearer ')) {
|
||||
return header.substring(7);
|
||||
}
|
||||
|
||||
if (!req.cookies) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (slug) {
|
||||
const cookieName = `${GALLERY_COOKIE_PREFIX}${sanitizeSlugForCookie(slug)}`;
|
||||
if (req.cookies[cookieName]) {
|
||||
return req.cookies[cookieName];
|
||||
}
|
||||
}
|
||||
|
||||
if (req.cookies[GALLERY_COOKIE_NAME]) {
|
||||
return req.cookies[GALLERY_COOKIE_NAME];
|
||||
}
|
||||
|
||||
const prefixed = Object.keys(req.cookies).find((name) => name.startsWith(GALLERY_COOKIE_PREFIX));
|
||||
if (prefixed) {
|
||||
return req.cookies[prefixed];
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
ADMIN_COOKIE_NAME,
|
||||
GALLERY_COOKIE_NAME,
|
||||
GALLERY_COOKIE_PREFIX,
|
||||
sanitizeSlugForCookie,
|
||||
setAdminAuthCookie,
|
||||
clearAdminAuthCookie,
|
||||
setGalleryAuthCookies,
|
||||
clearGalleryAuthCookies,
|
||||
getAdminTokenFromRequest,
|
||||
getGalleryTokenFromRequest,
|
||||
};
|
||||
+8
-1
@@ -11,6 +11,7 @@ services:
|
||||
- JWT_SECRET=${JWT_SECRET}
|
||||
- ADMIN_USERNAME=${ADMIN_USERNAME:-admin}
|
||||
- ADMIN_EMAIL=${ADMIN_EMAIL:-admin@example.com}
|
||||
- ADMIN_PASSWORD=${ADMIN_PASSWORD}
|
||||
- DATABASE_CLIENT=pg
|
||||
- DATABASE_URL=postgresql://${DB_USER}:${DB_PASSWORD}@postgres:5432/${DB_NAME}
|
||||
- DB_TYPE=postgresql
|
||||
@@ -19,6 +20,7 @@ services:
|
||||
- DB_USER=${DB_USER}
|
||||
- DB_PASSWORD=${DB_PASSWORD}
|
||||
- DB_NAME=${DB_NAME}
|
||||
- EXTERNAL_MEDIA_ROOT=${EXTERNAL_MEDIA_ROOT:-/app/storage/external-media}
|
||||
- SMTP_HOST=${SMTP_HOST}
|
||||
- SMTP_PORT=${SMTP_PORT}
|
||||
- SMTP_SECURE=${SMTP_SECURE:-false}
|
||||
@@ -29,6 +31,11 @@ services:
|
||||
- ADMIN_URL=${ADMIN_URL:-http://localhost:3001}
|
||||
- TZ=${TZ:-UTC}
|
||||
- STORAGE_PATH=/app/storage
|
||||
# Optional: run container as matching host user to avoid bind mount permission issues
|
||||
- PUID=${PUID:-1001}
|
||||
- PGID=${PGID:-1001}
|
||||
# Use host-matching user ID/GID so bind-mounted folders are writable
|
||||
user: "${PUID:-1001}:${PGID:-1001}"
|
||||
volumes:
|
||||
- ./events:/app/events
|
||||
- ./data:/app/data
|
||||
@@ -122,4 +129,4 @@ volumes:
|
||||
|
||||
networks:
|
||||
picpeak-network:
|
||||
driver: bridge
|
||||
driver: bridge
|
||||
|
||||
Generated
+36
-47
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "picpeak-frontend",
|
||||
"version": "1.0.116",
|
||||
"version": "1.0.128",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "picpeak-frontend",
|
||||
"version": "1.0.116",
|
||||
"version": "1.0.128",
|
||||
"dependencies": {
|
||||
"@tanstack/react-query": "^5.0.0",
|
||||
"@tiptap/extension-character-count": "^2.26.1",
|
||||
@@ -20,14 +20,14 @@
|
||||
"@types/dompurify": "^3.0.5",
|
||||
"@types/lodash": "^4.17.20",
|
||||
"@types/react-google-recaptcha": "^2.1.9",
|
||||
"axios": "^1.3.2",
|
||||
"axios": "^1.12.2",
|
||||
"clsx": "^2.0.0",
|
||||
"date-fns": "4.1.0",
|
||||
"dompurify": "^3.2.6",
|
||||
"i18next": "^25.3.1",
|
||||
"i18next-browser-languagedetector": "^8.2.0",
|
||||
"i18next-http-backend": "^3.0.2",
|
||||
"js-cookie": "^3.0.5",
|
||||
"linkifyjs": "^4.3.2",
|
||||
"lodash": "^4.17.21",
|
||||
"lowlight": "^2.9.0",
|
||||
"lucide-react": "0.525.0",
|
||||
@@ -44,7 +44,6 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.29.0",
|
||||
"@types/js-cookie": "^3.0.6",
|
||||
"@types/react": "^18.3.12",
|
||||
"@types/react-dom": "^18.3.1",
|
||||
"@vitejs/plugin-react": "^4.5.2",
|
||||
@@ -57,7 +56,7 @@
|
||||
"tailwindcss": "^3.3.0",
|
||||
"typescript": "~5.8.3",
|
||||
"typescript-eslint": "^8.34.1",
|
||||
"vite": "^7.0.0"
|
||||
"vite": "^7.1.6"
|
||||
}
|
||||
},
|
||||
"node_modules/@alloc/quick-lru": {
|
||||
@@ -2014,13 +2013,6 @@
|
||||
"@types/unist": "^2"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/js-cookie": {
|
||||
"version": "3.0.6",
|
||||
"resolved": "https://registry.npmjs.org/@types/js-cookie/-/js-cookie-3.0.6.tgz",
|
||||
"integrity": "sha512-wkw9yd1kEXOPnvEeEV1Go1MmxtBJL0RR79aOTAApecWFVu7w0NNXNqhcWgvw2YgZDYadliXkl14pa3WXw5jlCQ==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/json-schema": {
|
||||
"version": "7.0.15",
|
||||
"resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz",
|
||||
@@ -2549,13 +2541,13 @@
|
||||
}
|
||||
},
|
||||
"node_modules/axios": {
|
||||
"version": "1.10.0",
|
||||
"resolved": "https://registry.npmjs.org/axios/-/axios-1.10.0.tgz",
|
||||
"integrity": "sha512-/1xYAC4MP/HEG+3duIhFr4ZQXR4sQXOIe+o6sdqzeykGLx6Upp/1p8MHqhINOvGeP7xyNHe7tsiJByc4SSVUxw==",
|
||||
"version": "1.12.2",
|
||||
"resolved": "https://registry.npmjs.org/axios/-/axios-1.12.2.tgz",
|
||||
"integrity": "sha512-vMJzPewAlRyOgxV2dU0Cuz2O8zzzx9VYtbJOaBgXFeLc4IV/Eg50n4LowmehOOR61S8ZMpc2K5Sa7g6A4jfkUw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"follow-redirects": "^1.15.6",
|
||||
"form-data": "^4.0.0",
|
||||
"form-data": "^4.0.4",
|
||||
"proxy-from-env": "^1.1.0"
|
||||
}
|
||||
},
|
||||
@@ -3903,15 +3895,6 @@
|
||||
"jiti": "bin/jiti.js"
|
||||
}
|
||||
},
|
||||
"node_modules/js-cookie": {
|
||||
"version": "3.0.5",
|
||||
"resolved": "https://registry.npmjs.org/js-cookie/-/js-cookie-3.0.5.tgz",
|
||||
"integrity": "sha512-cEiJEAEoIbWfCZYKWhVwFuvPX1gETRYPw6LlaTKoxD3s2AkXzkCjnp6h0V77ozyqj0jakteJ4YqDJT830+lVGw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
}
|
||||
},
|
||||
"node_modules/js-tokens": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
|
||||
@@ -4032,9 +4015,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/linkifyjs": {
|
||||
"version": "4.3.1",
|
||||
"resolved": "https://registry.npmjs.org/linkifyjs/-/linkifyjs-4.3.1.tgz",
|
||||
"integrity": "sha512-DRSlB9DKVW04c4SUdGvKK5FR6be45lTU9M76JnngqPeeGDqPwYc0zdUErtsNVMtxPXgUWV4HbXbnC4sNyBxkYg==",
|
||||
"version": "4.3.2",
|
||||
"resolved": "https://registry.npmjs.org/linkifyjs/-/linkifyjs-4.3.2.tgz",
|
||||
"integrity": "sha512-NT1CJtq3hHIreOianA8aSXn6Cw0JzYOuDQbOrSPe7gqFnCpKP++MQe3ODgO3oh2GJFORkAAdqredOa60z63GbA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/locate-path": {
|
||||
@@ -5524,14 +5507,14 @@
|
||||
}
|
||||
},
|
||||
"node_modules/tinyglobby": {
|
||||
"version": "0.2.14",
|
||||
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.14.tgz",
|
||||
"integrity": "sha512-tX5e7OM1HnYr2+a2C/4V0htOcSQcoSTH9KgJnVvNm5zm/cyEWKJ7j7YutsH9CxMdtOkkLFy2AHrMci9IM8IPZQ==",
|
||||
"version": "0.2.15",
|
||||
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz",
|
||||
"integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"fdir": "^6.4.4",
|
||||
"picomatch": "^4.0.2"
|
||||
"fdir": "^6.5.0",
|
||||
"picomatch": "^4.0.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12.0.0"
|
||||
@@ -5541,11 +5524,14 @@
|
||||
}
|
||||
},
|
||||
"node_modules/tinyglobby/node_modules/fdir": {
|
||||
"version": "6.4.6",
|
||||
"resolved": "https://registry.npmjs.org/fdir/-/fdir-6.4.6.tgz",
|
||||
"integrity": "sha512-hiFoqpyZcfNm1yc4u8oWCf9A2c4D3QjCrks3zmoVKVxpQRzmPNar1hUJcBG2RQHvEVGDN+Jm81ZheVLAQMK6+w==",
|
||||
"version": "6.5.0",
|
||||
"resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
|
||||
"integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=12.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"picomatch": "^3 || ^4"
|
||||
},
|
||||
@@ -5731,18 +5717,18 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/vite": {
|
||||
"version": "7.0.5",
|
||||
"resolved": "https://registry.npmjs.org/vite/-/vite-7.0.5.tgz",
|
||||
"integrity": "sha512-1mncVwJxy2C9ThLwz0+2GKZyEXuC3MyWtAAlNftlZZXZDP3AJt5FmwcMit/IGGaNZ8ZOB2BNO/HFUB+CpN0NQw==",
|
||||
"version": "7.1.6",
|
||||
"resolved": "https://registry.npmjs.org/vite/-/vite-7.1.6.tgz",
|
||||
"integrity": "sha512-SRYIB8t/isTwNn8vMB3MR6E+EQZM/WG1aKmmIUCfDXfVvKfc20ZpamngWHKzAmmu9ppsgxsg4b2I7c90JZudIQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"esbuild": "^0.25.0",
|
||||
"fdir": "^6.4.6",
|
||||
"picomatch": "^4.0.2",
|
||||
"fdir": "^6.5.0",
|
||||
"picomatch": "^4.0.3",
|
||||
"postcss": "^8.5.6",
|
||||
"rollup": "^4.40.0",
|
||||
"tinyglobby": "^0.2.14"
|
||||
"rollup": "^4.43.0",
|
||||
"tinyglobby": "^0.2.15"
|
||||
},
|
||||
"bin": {
|
||||
"vite": "bin/vite.js"
|
||||
@@ -5806,11 +5792,14 @@
|
||||
}
|
||||
},
|
||||
"node_modules/vite/node_modules/fdir": {
|
||||
"version": "6.4.6",
|
||||
"resolved": "https://registry.npmjs.org/fdir/-/fdir-6.4.6.tgz",
|
||||
"integrity": "sha512-hiFoqpyZcfNm1yc4u8oWCf9A2c4D3QjCrks3zmoVKVxpQRzmPNar1hUJcBG2RQHvEVGDN+Jm81ZheVLAQMK6+w==",
|
||||
"version": "6.5.0",
|
||||
"resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
|
||||
"integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=12.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"picomatch": "^3 || ^4"
|
||||
},
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "picpeak-frontend",
|
||||
"private": true,
|
||||
"version": "1.0.116",
|
||||
"version": "1.0.128",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
@@ -23,14 +23,14 @@
|
||||
"@types/dompurify": "^3.0.5",
|
||||
"@types/lodash": "^4.17.20",
|
||||
"@types/react-google-recaptcha": "^2.1.9",
|
||||
"axios": "^1.3.2",
|
||||
"axios": "^1.12.2",
|
||||
"clsx": "^2.0.0",
|
||||
"date-fns": "4.1.0",
|
||||
"dompurify": "^3.2.6",
|
||||
"i18next": "^25.3.1",
|
||||
"i18next-browser-languagedetector": "^8.2.0",
|
||||
"i18next-http-backend": "^3.0.2",
|
||||
"js-cookie": "^3.0.5",
|
||||
"linkifyjs": "^4.3.2",
|
||||
"lodash": "^4.17.21",
|
||||
"lowlight": "^2.9.0",
|
||||
"lucide-react": "0.525.0",
|
||||
@@ -47,7 +47,6 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.29.0",
|
||||
"@types/js-cookie": "^3.0.6",
|
||||
"@types/react": "^18.3.12",
|
||||
"@types/react-dom": "^18.3.1",
|
||||
"@vitejs/plugin-react": "^4.5.2",
|
||||
@@ -60,6 +59,6 @@
|
||||
"tailwindcss": "^3.3.0",
|
||||
"typescript": "~5.8.3",
|
||||
"typescript-eslint": "^8.34.1",
|
||||
"vite": "^7.0.0"
|
||||
"vite": "^7.1.6"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import React, { useEffect } from 'react';
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { useLocation } from 'react-router-dom';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { MaintenanceMode } from './MaintenanceMode';
|
||||
import { useMaintenanceMode } from '../contexts/MaintenanceContext';
|
||||
import { setMaintenanceModeCallback, api, getAuthToken } from '../config/api';
|
||||
import { setMaintenanceModeCallback, api } from '../config/api';
|
||||
|
||||
interface MaintenanceWrapperProps {
|
||||
children: React.ReactNode;
|
||||
@@ -12,10 +12,38 @@ interface MaintenanceWrapperProps {
|
||||
export const MaintenanceWrapper: React.FC<MaintenanceWrapperProps> = ({ children }) => {
|
||||
const location = useLocation();
|
||||
const { isMaintenanceMode, setMaintenanceMode } = useMaintenanceMode();
|
||||
const [hasAdminSession, setHasAdminSession] = useState(false);
|
||||
|
||||
// Check if current route is admin route
|
||||
const isAdminRoute = location.pathname.startsWith('/admin');
|
||||
const hasAdminAuth = !!getAuthToken(true);
|
||||
|
||||
useEffect(() => {
|
||||
let isMounted = true;
|
||||
|
||||
const checkAdminSession = async () => {
|
||||
if (!isAdminRoute) {
|
||||
setHasAdminSession(false);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await api.get<{ valid: boolean; type: string }>('/auth/session');
|
||||
if (isMounted) {
|
||||
setHasAdminSession(Boolean(response.data?.valid && response.data.type === 'admin'));
|
||||
}
|
||||
} catch (error) {
|
||||
if (isMounted) {
|
||||
setHasAdminSession(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
checkAdminSession();
|
||||
|
||||
return () => {
|
||||
isMounted = false;
|
||||
};
|
||||
}, [isAdminRoute]);
|
||||
|
||||
// Register the maintenance mode callback
|
||||
useEffect(() => {
|
||||
@@ -37,7 +65,7 @@ export const MaintenanceWrapper: React.FC<MaintenanceWrapperProps> = ({ children
|
||||
} catch (error: any) {
|
||||
if (error.response?.status === 503) {
|
||||
// Only set maintenance mode for non-admin routes or unauthenticated admin routes
|
||||
if (!isAdminRoute || !hasAdminAuth) {
|
||||
if (!isAdminRoute || !hasAdminSession) {
|
||||
setMaintenanceMode(true);
|
||||
return { maintenance: true };
|
||||
}
|
||||
@@ -47,13 +75,13 @@ export const MaintenanceWrapper: React.FC<MaintenanceWrapperProps> = ({ children
|
||||
},
|
||||
staleTime: 30000, // Check every 30 seconds
|
||||
retry: false, // Don't retry on failure
|
||||
enabled: (!isAdminRoute || !hasAdminAuth) && !isMaintenanceMode, // Don't check if already in maintenance
|
||||
enabled: (!isAdminRoute || !hasAdminSession) && !isMaintenanceMode, // Don't check if already in maintenance
|
||||
});
|
||||
|
||||
// Show maintenance page if in maintenance mode and not on admin route with auth
|
||||
if (isMaintenanceMode && (!isAdminRoute || !hasAdminAuth)) {
|
||||
if (isMaintenanceMode && (!isAdminRoute || !hasAdminSession)) {
|
||||
return <MaintenanceMode />;
|
||||
}
|
||||
|
||||
return <>{children}</>;
|
||||
};
|
||||
};
|
||||
|
||||
@@ -71,35 +71,29 @@ export const AdminHeader: React.FC<AdminHeaderProps> = ({ onMenuClick }) => {
|
||||
<header className="sticky top-0 z-30 bg-white border-b border-neutral-200">
|
||||
<div className="px-4 sm:px-6 lg:px-8">
|
||||
<div className="flex items-center justify-between h-16">
|
||||
{/* Left side - Menu button and Date */}
|
||||
<div className="flex items-center gap-3">
|
||||
{/* Left side - Menu button, Logo, and Date */}
|
||||
<div className="flex items-center gap-3 min-w-0">
|
||||
<button
|
||||
onClick={onMenuClick}
|
||||
className="lg:hidden text-neutral-500 hover:text-neutral-700"
|
||||
>
|
||||
<Menu className="w-6 h-6" />
|
||||
</button>
|
||||
|
||||
{/* Date display - hidden on small screens */}
|
||||
<div className="hidden xl:block">
|
||||
|
||||
{/* PicPeak logo - sticky to the left on all sizes */}
|
||||
<div className="flex items-center gap-2">
|
||||
<img src="/picpeak-kamera-transparent.png" alt="PicPeak" className="h-8 w-auto object-contain" />
|
||||
<span className="text-xl sm:text-2xl" style={{ fontFamily: 'Poppins, sans-serif', fontWeight: 600, color: '#145346' }}>PicPeak</span>
|
||||
</div>
|
||||
|
||||
{/* Date display - hidden on smaller screens */}
|
||||
<div className="hidden xl:block pl-3 border-l border-neutral-200 ml-1">
|
||||
<p className="text-base text-neutral-700">
|
||||
{format(new Date(), 'PPPP')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Center - Logo and PicPeak text - hidden on small screens to prevent overlap */}
|
||||
<div className="hidden lg:flex absolute left-1/2 transform -translate-x-1/2 items-center gap-3">
|
||||
<img src="/picpeak-kamera-transparent.png" alt="PicPeak" className="h-10 w-auto object-contain" />
|
||||
<span className="text-2xl" style={{ fontFamily: 'Poppins, sans-serif', fontWeight: 600, color: '#145346' }}>PicPeak</span>
|
||||
</div>
|
||||
|
||||
{/* Mobile Logo - shown only on small screens */}
|
||||
<div className="flex lg:hidden items-center gap-2 mx-auto">
|
||||
<img src="/picpeak-kamera-transparent.png" alt="PicPeak" className="h-8 w-auto object-contain" />
|
||||
<span className="text-xl" style={{ fontFamily: 'Poppins, sans-serif', fontWeight: 600, color: '#145346' }}>PicPeak</span>
|
||||
</div>
|
||||
|
||||
{/* Right side actions */}
|
||||
<div className="flex items-center gap-3">
|
||||
{/* Language Selector */}
|
||||
@@ -253,4 +247,4 @@ export const AdminHeader: React.FC<AdminHeaderProps> = ({ onMenuClick }) => {
|
||||
/>
|
||||
</header>
|
||||
);
|
||||
};
|
||||
};
|
||||
|
||||
@@ -29,7 +29,10 @@ export const AdminPhotoGrid: React.FC<AdminPhotoGridProps> = ({
|
||||
if (e) {
|
||||
e.stopPropagation();
|
||||
}
|
||||
|
||||
// Auto-enable selection mode when selecting via checkbox
|
||||
if (!isSelectionMode) {
|
||||
setIsSelectionMode(true);
|
||||
}
|
||||
const newSelected = new Set(selectedPhotos);
|
||||
if (newSelected.has(photoId)) {
|
||||
newSelected.delete(photoId);
|
||||
@@ -126,7 +129,7 @@ export const AdminPhotoGrid: React.FC<AdminPhotoGridProps> = ({
|
||||
{isSelectionMode ? 'Cancel Selection' : 'Select Photos'}
|
||||
</Button>
|
||||
|
||||
{isSelectionMode && (
|
||||
{(isSelectionMode || selectedPhotos.size > 0) && (
|
||||
<>
|
||||
<Button
|
||||
variant="ghost"
|
||||
@@ -167,25 +170,32 @@ export const AdminPhotoGrid: React.FC<AdminPhotoGridProps> = ({
|
||||
return (
|
||||
<div
|
||||
key={photo.id}
|
||||
data-testid={`admin-photo-tile-${photo.id}`}
|
||||
className={`relative group cursor-pointer rounded-lg overflow-hidden bg-neutral-100 transition-opacity ${
|
||||
isSelectionMode ? 'ring-2 ring-offset-2 ' + (selectedPhotos.has(photo.id) ? 'ring-primary-500' : 'ring-transparent') : ''
|
||||
} ${isDeleting ? 'opacity-50' : ''}`}
|
||||
onClick={() => !isDeleting && (isSelectionMode ? handlePhotoSelect(photo.id) : onPhotoClick(photo, index))}
|
||||
onClick={() => !isDeleting && onPhotoClick(photo, index)}
|
||||
>
|
||||
{/* Selection Checkbox */}
|
||||
{isSelectionMode && (
|
||||
<div className="absolute top-2 left-2 z-10">
|
||||
<div className={`w-6 h-6 rounded border-2 flex items-center justify-center ${
|
||||
selectedPhotos.has(photo.id)
|
||||
? 'bg-primary-500 border-primary-500'
|
||||
: 'bg-white/80 border-neutral-300'
|
||||
}`}>
|
||||
{selectedPhotos.has(photo.id) && (
|
||||
<Check className="w-4 h-4 text-white" />
|
||||
)}
|
||||
</div>
|
||||
{/* Selection Checkbox (top-right) */}
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`Select ${photo.filename}`}
|
||||
role="checkbox"
|
||||
aria-checked={selectedPhotos.has(photo.id)}
|
||||
data-testid={`admin-photo-checkbox-${photo.id}`}
|
||||
className={`absolute top-2 right-2 z-20 transition-opacity ${
|
||||
selectedPhotos.has(photo.id) ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'
|
||||
}`}
|
||||
onClick={(e) => handlePhotoSelect(photo.id, e)}
|
||||
>
|
||||
<div className={`w-6 h-6 rounded border-2 flex items-center justify-center ${
|
||||
selectedPhotos.has(photo.id)
|
||||
? 'bg-primary-600 border-primary-600'
|
||||
: 'bg-white/90 border-white'
|
||||
}`}>
|
||||
{selectedPhotos.has(photo.id) && <Check className="w-4 h-4 text-white" />}
|
||||
</div>
|
||||
)}
|
||||
</button>
|
||||
|
||||
{/* Thumbnail */}
|
||||
<div className="aspect-square">
|
||||
@@ -238,30 +248,30 @@ export const AdminPhotoGrid: React.FC<AdminPhotoGridProps> = ({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Category Badge */}
|
||||
{/* Category Badge - move to top-left and prevent overlap with select checkbox */}
|
||||
{photo.category_name && (
|
||||
<div className="absolute top-2 right-2">
|
||||
<span className="px-2 py-1 text-xs font-medium bg-white/90 text-neutral-700 rounded">
|
||||
<div className="absolute left-2 top-2 pointer-events-none">
|
||||
<span className="px-2 py-1 text-xs font-medium bg-white/90 text-neutral-700 rounded max-w-[70%] whitespace-nowrap overflow-hidden text-ellipsis">
|
||||
{photo.category_name}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Feedback Indicators */}
|
||||
{/* Feedback Indicators (moved to bottom-right to avoid covering category) */}
|
||||
{(photo.comment_count > 0 || photo.average_rating > 0 || photo.like_count > 0) && (
|
||||
<div className="absolute top-2 left-2 flex gap-1 z-10" style={{ left: isSelectionMode ? '40px' : '8px' }}>
|
||||
{photo.comment_count > 0 && (
|
||||
<div className="bg-white/90 backdrop-blur-sm rounded-full px-2 py-1 flex items-center gap-1" title={`${photo.comment_count} comments`}>
|
||||
<MessageSquare className="w-3.5 h-3.5 text-primary-600" fill="currentColor" />
|
||||
<span className="text-xs font-medium text-neutral-700">{photo.comment_count}</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="absolute bottom-2 right-2 flex items-center gap-1 z-10">
|
||||
{photo.average_rating > 0 && (
|
||||
<div className="bg-white/90 backdrop-blur-sm rounded-full px-2 py-1 flex items-center gap-1" title={`Rating: ${Number(photo.average_rating).toFixed(1)}`}>
|
||||
<Star className="w-3.5 h-3.5 text-yellow-500" fill="currentColor" />
|
||||
<span className="text-xs font-medium text-neutral-700">{Number(photo.average_rating).toFixed(1)}</span>
|
||||
</div>
|
||||
)}
|
||||
{photo.comment_count > 0 && (
|
||||
<div className="bg-white/90 backdrop-blur-sm rounded-full px-2 py-1 flex items-center gap-1" title={`${photo.comment_count} comments`}>
|
||||
<MessageSquare className="w-3.5 h-3.5 text-primary-600" fill="currentColor" />
|
||||
<span className="text-xs font-medium text-neutral-700">{photo.comment_count}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
@@ -276,4 +286,4 @@ export const AdminPhotoGrid: React.FC<AdminPhotoGridProps> = ({
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
};
|
||||
|
||||
@@ -132,7 +132,7 @@ export const FeedbackModerationPanel: React.FC<FeedbackModerationPanelProps> = (
|
||||
<div className="mt-2 flex items-center gap-2">
|
||||
<div className="w-16 h-16 overflow-hidden rounded">
|
||||
<AdminAuthenticatedImage
|
||||
src={`/api/admin/photos/${eventId}/thumbnail/${item.photo_id}`}
|
||||
src={`/admin/photos/${eventId}/thumbnail/${item.photo_id}`}
|
||||
alt={item.filename || 'Photo'}
|
||||
className="w-16 h-16 object-cover rounded"
|
||||
/>
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { getAuthToken } from '../../config/api';
|
||||
import { buildResourceUrl } from '../../utils/url';
|
||||
|
||||
interface AuthenticatedImageProps extends React.ImgHTMLAttributes<HTMLImageElement> {
|
||||
@@ -25,33 +24,12 @@ export const AuthenticatedImage: React.FC<AuthenticatedImageProps> = ({
|
||||
let objectUrl: string | null = null;
|
||||
|
||||
// Determine which token to use based on context
|
||||
let token: string | undefined;
|
||||
|
||||
if (isGallery) {
|
||||
// For gallery images, get the gallery-specific token
|
||||
const pathParts = window.location.pathname.split('/');
|
||||
if (pathParts[1] === 'gallery' && pathParts[2]) {
|
||||
const gallerySlug = pathParts[2];
|
||||
token = localStorage.getItem(`gallery_token_${gallerySlug}`) || undefined;
|
||||
}
|
||||
} else {
|
||||
// For admin images, use the admin token
|
||||
token = getAuthToken(true);
|
||||
}
|
||||
|
||||
if (!src) {
|
||||
setImageSrc(fallbackSrc || '');
|
||||
setIsLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!token) {
|
||||
// No auth token - use fallback
|
||||
setImageSrc(fallbackSrc || '');
|
||||
setIsLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
setError(false);
|
||||
|
||||
@@ -71,9 +49,7 @@ export const AuthenticatedImage: React.FC<AuthenticatedImageProps> = ({
|
||||
|
||||
// Fetch authenticated image
|
||||
const response = await fetch(fullImageUrl, {
|
||||
headers: {
|
||||
'Authorization': `Bearer ${token}`
|
||||
}
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
@@ -119,4 +95,4 @@ export const AuthenticatedImage: React.FC<AuthenticatedImageProps> = ({
|
||||
}
|
||||
|
||||
return <img src={imageSrc} alt={alt} {...props} />;
|
||||
};
|
||||
};
|
||||
|
||||
@@ -1,18 +1,19 @@
|
||||
import React from 'react';
|
||||
import { Heart, Star } from 'lucide-react';
|
||||
import { Heart, Star, MessageSquare } from 'lucide-react';
|
||||
import { Button } from '../common';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
export type FilterType = 'all' | 'liked' | 'favorited';
|
||||
export type FilterType = 'all' | 'liked' | 'rated' | 'commented';
|
||||
|
||||
interface GalleryFilterProps {
|
||||
currentFilter: FilterType;
|
||||
onFilterChange: (filter: FilterType) => void;
|
||||
feedbackEnabled: boolean;
|
||||
likeCount?: number;
|
||||
favoriteCount?: number;
|
||||
ratedCount?: number;
|
||||
className?: string;
|
||||
isMobile?: boolean;
|
||||
variant?: 'default' | 'compact';
|
||||
}
|
||||
|
||||
export const GalleryFilter: React.FC<GalleryFilterProps> = ({
|
||||
@@ -20,9 +21,10 @@ export const GalleryFilter: React.FC<GalleryFilterProps> = ({
|
||||
onFilterChange,
|
||||
feedbackEnabled,
|
||||
likeCount = 0,
|
||||
favoriteCount = 0,
|
||||
ratedCount = 0,
|
||||
className = '',
|
||||
isMobile = false
|
||||
isMobile = false,
|
||||
variant = 'default'
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
@@ -30,6 +32,57 @@ export const GalleryFilter: React.FC<GalleryFilterProps> = ({
|
||||
return null;
|
||||
}
|
||||
|
||||
// Compact icon-only vertical variant (used in sidebar and tight spaces)
|
||||
if (variant === 'compact') {
|
||||
return (
|
||||
<div className={`${className}`}>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm text-neutral-700 whitespace-nowrap">
|
||||
{t('gallery.feedbackFilter', 'Feedback Filter')}
|
||||
</span>
|
||||
<div className="flex items-center gap-1">
|
||||
<Button
|
||||
variant={currentFilter === 'all' ? 'primary' : 'outline'}
|
||||
size="sm"
|
||||
onClick={() => onFilterChange('all')}
|
||||
className="p-1 w-8 h-8 flex items-center justify-center"
|
||||
aria-label={t('gallery.all', 'All')}
|
||||
>
|
||||
<svg viewBox="0 0 24 24" className="w-3.5 h-3.5 text-current"><path d="M3 3h8v8H3V3zm10 0h8v8h-8V3zM3 13h8v8H3v-8zm10 8v-8h8v8h-8z"/></svg>
|
||||
</Button>
|
||||
<Button
|
||||
variant={currentFilter === 'liked' ? 'primary' : 'outline'}
|
||||
size="sm"
|
||||
onClick={() => onFilterChange('liked')}
|
||||
className="p-1 w-8 h-8 flex items-center justify-center"
|
||||
aria-label={t('feedback.likes', 'Likes')}
|
||||
>
|
||||
<Heart className="w-3.5 h-3.5" />
|
||||
</Button>
|
||||
<Button
|
||||
variant={currentFilter === 'rated' ? 'primary' : 'outline'}
|
||||
size="sm"
|
||||
onClick={() => onFilterChange('rated')}
|
||||
className="p-1 w-8 h-8 flex items-center justify-center"
|
||||
aria-label={t('gallery.rated', 'Rated')}
|
||||
>
|
||||
<Star className="w-3.5 h-3.5" />
|
||||
</Button>
|
||||
<Button
|
||||
variant={currentFilter === 'commented' ? 'primary' : 'outline'}
|
||||
size="sm"
|
||||
onClick={() => onFilterChange('commented')}
|
||||
className="p-1 w-8 h-8 flex items-center justify-center"
|
||||
aria-label={t('gallery.commented', 'Commented')}
|
||||
>
|
||||
<MessageSquare className="w-3.5 h-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={`${className}`}>
|
||||
{/* Mobile-optimized vertical layout */}
|
||||
@@ -59,13 +112,13 @@ export const GalleryFilter: React.FC<GalleryFilterProps> = ({
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant={currentFilter === 'favorited' ? 'primary' : 'outline'}
|
||||
variant={currentFilter === 'rated' ? 'primary' : 'outline'}
|
||||
size="sm"
|
||||
onClick={() => onFilterChange('favorited')}
|
||||
onClick={() => onFilterChange('rated')}
|
||||
className="text-xs flex-1 min-w-[80px] flex items-center justify-center gap-1"
|
||||
>
|
||||
<Star className="w-3 h-3" />
|
||||
<span>{favoriteCount > 0 ? favoriteCount : t('gallery.favorites', 'Favorites')}</span>
|
||||
<span>{ratedCount > 0 ? ratedCount : t('gallery.rated', 'Rated')}</span>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -101,22 +154,32 @@ export const GalleryFilter: React.FC<GalleryFilterProps> = ({
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant={currentFilter === 'favorited' ? 'primary' : 'outline'}
|
||||
variant={currentFilter === 'rated' ? 'primary' : 'outline'}
|
||||
size="sm"
|
||||
onClick={() => onFilterChange('favorited')}
|
||||
onClick={() => onFilterChange('rated')}
|
||||
className="text-xs sm:text-sm flex items-center gap-1"
|
||||
>
|
||||
<Star className="w-3 h-3 sm:w-4 sm:h-4" />
|
||||
<span className="hidden sm:inline">{t('gallery.favorited', 'Favorites')}</span>
|
||||
{favoriteCount > 0 && (
|
||||
<span className="hidden sm:inline">{t('gallery.rated', 'Rated')}</span>
|
||||
{ratedCount > 0 && (
|
||||
<span className="bg-primary-100 text-primary-700 px-1.5 rounded">
|
||||
{favoriteCount}
|
||||
{ratedCount}
|
||||
</span>
|
||||
)}
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant={currentFilter === 'commented' ? 'primary' : 'outline'}
|
||||
size="sm"
|
||||
onClick={() => onFilterChange('commented')}
|
||||
className="text-xs sm:text-sm flex items-center gap-1"
|
||||
>
|
||||
<MessageSquare className="w-3 h-3 sm:w-4 sm:h-4" />
|
||||
<span className="hidden sm:inline">{t('gallery.commented', 'Commented')}</span>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
};
|
||||
|
||||
@@ -33,7 +33,7 @@ interface GallerySidebarProps {
|
||||
filterType?: FilterType;
|
||||
onFilterChange?: (filter: FilterType) => void;
|
||||
likeCount?: number;
|
||||
favoriteCount?: number;
|
||||
ratedCount?: number;
|
||||
}
|
||||
|
||||
export const GallerySidebar: React.FC<GallerySidebarProps> = ({
|
||||
@@ -64,7 +64,7 @@ export const GallerySidebar: React.FC<GallerySidebarProps> = ({
|
||||
filterType = 'all',
|
||||
onFilterChange,
|
||||
likeCount = 0,
|
||||
favoriteCount = 0
|
||||
ratedCount = 0
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const sidebarRef = useRef<HTMLDivElement>(null);
|
||||
@@ -114,7 +114,7 @@ export const GallerySidebar: React.FC<GallerySidebarProps> = ({
|
||||
<div
|
||||
ref={sidebarRef}
|
||||
className={`
|
||||
fixed top-0 left-0 h-full bg-white shadow-xl z-50 transition-transform duration-300 ease-in-out
|
||||
fixed top-0 left-0 h-full bg-white shadow-xl z-50 transition-transform duration-300 ease-in-out flex flex-col
|
||||
${isMobile ? 'w-full max-w-sm' : 'w-80'}
|
||||
${isOpen ? 'translate-x-0' : '-translate-x-full'}
|
||||
`}
|
||||
@@ -223,8 +223,9 @@ export const GallerySidebar: React.FC<GallerySidebarProps> = ({
|
||||
}}
|
||||
feedbackEnabled={feedbackEnabled}
|
||||
likeCount={likeCount}
|
||||
favoriteCount={favoriteCount}
|
||||
ratedCount={ratedCount}
|
||||
className="w-full"
|
||||
variant="compact"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
@@ -328,4 +329,4 @@ export const GallerySidebar: React.FC<GallerySidebarProps> = ({
|
||||
|
||||
</>
|
||||
);
|
||||
};
|
||||
};
|
||||
|
||||
@@ -22,6 +22,7 @@ import { Upload, Menu } from 'lucide-react';
|
||||
import { galleryService } from '../../services/gallery.service';
|
||||
import { feedbackService } from '../../services/feedback.service';
|
||||
import { useWatermarkSettings } from '../../hooks/useWatermarkSettings';
|
||||
import type { Photo } from '../../types';
|
||||
|
||||
interface GalleryViewProps {
|
||||
slug: string;
|
||||
@@ -58,6 +59,7 @@ export const GalleryView: React.FC<GalleryViewProps> = ({ slug, event }) => {
|
||||
const [protectionLevel, setProtectionLevel] = useState<'basic' | 'standard' | 'enhanced' | 'maximum'>('standard');
|
||||
const [filterType, setFilterType] = useState<FilterType>('all');
|
||||
const [guestId, setGuestId] = useState<string>('');
|
||||
const [staticHeroPhoto, setStaticHeroPhoto] = useState<Photo | null>(null);
|
||||
|
||||
// Generate a unique guest ID for this session
|
||||
useEffect(() => {
|
||||
@@ -167,6 +169,23 @@ export const GalleryView: React.FC<GalleryViewProps> = ({ slug, event }) => {
|
||||
}
|
||||
}, [settingsData]);
|
||||
|
||||
// Determine a stable hero photo from the initial (unfiltered) load
|
||||
useEffect(() => {
|
||||
if (!staticHeroPhoto && data?.photos && filterType === 'all') {
|
||||
let hero: Photo | null = null;
|
||||
const heroId = data?.event?.hero_photo_id || null;
|
||||
if (heroId) {
|
||||
hero = data.photos.find(p => p.id === heroId) || null;
|
||||
}
|
||||
if (!hero && data.photos.length > 0) {
|
||||
hero = data.photos[0];
|
||||
}
|
||||
if (hero) {
|
||||
setStaticHeroPhoto(hero);
|
||||
}
|
||||
}
|
||||
}, [data?.photos, data?.event?.hero_photo_id, filterType, staticHeroPhoto]);
|
||||
|
||||
// Apply theme when settings are loaded
|
||||
useEffect(() => {
|
||||
if (settingsData && data?.event) {
|
||||
@@ -247,6 +266,21 @@ export const GalleryView: React.FC<GalleryViewProps> = ({ slug, event }) => {
|
||||
);
|
||||
}
|
||||
|
||||
// Apply feedback filter
|
||||
switch (filterType) {
|
||||
case 'liked':
|
||||
photos = photos.filter(photo => (photo.like_count || 0) > 0);
|
||||
break;
|
||||
case 'rated':
|
||||
photos = photos.filter(photo => (photo.average_rating || 0) > 0 || (photo.total_ratings || 0) > 0);
|
||||
break;
|
||||
case 'commented':
|
||||
photos = photos.filter(photo => (photo.comment_count || 0) > 0);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
// Apply sorting
|
||||
photos.sort((a, b) => {
|
||||
switch (sortBy) {
|
||||
@@ -279,7 +313,7 @@ export const GalleryView: React.FC<GalleryViewProps> = ({ slug, event }) => {
|
||||
}
|
||||
|
||||
return photos;
|
||||
}, [data?.photos, selectedCategoryId, searchTerm, sortBy, watermarkEnabled, slug]);
|
||||
}, [data?.photos, selectedCategoryId, searchTerm, sortBy, watermarkEnabled, slug, filterType]);
|
||||
|
||||
// Check if downloads are allowed (both event setting and not expired)
|
||||
const allowDownloads = !isExpired && (data?.event?.allow_downloads === true);
|
||||
@@ -440,7 +474,7 @@ export const GalleryView: React.FC<GalleryViewProps> = ({ slug, event }) => {
|
||||
filterType={filterType}
|
||||
onFilterChange={setFilterType}
|
||||
likeCount={data?.photos?.filter(p => p.like_count > 0).length || 0}
|
||||
favoriteCount={data?.photos?.filter(p => p.favorite_count > 0).length || 0}
|
||||
ratedCount={data?.photos?.filter(p => (p.total_ratings || 0) > 0).length || 0}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
@@ -531,8 +565,6 @@ export const GalleryView: React.FC<GalleryViewProps> = ({ slug, event }) => {
|
||||
feedbackEnabled={feedbackEnabled}
|
||||
currentFilter={filterType}
|
||||
onFilterChange={setFilterType}
|
||||
likeCount={data?.photos?.filter(p => p.like_count > 0).length || 0}
|
||||
favoriteCount={data?.photos?.filter(p => p.favorite_count > 0).length || 0}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
@@ -543,7 +575,16 @@ export const GalleryView: React.FC<GalleryViewProps> = ({ slug, event }) => {
|
||||
photos={filteredPhotos}
|
||||
slug={slug}
|
||||
categoryId={selectedCategoryId}
|
||||
onFeedbackChange={() => refetch()}
|
||||
heroPhotoOverride={staticHeroPhoto}
|
||||
feedbackEnabled={feedbackEnabled}
|
||||
feedbackOptions={{
|
||||
allowLikes: !!feedbackSettings?.allow_likes,
|
||||
allowFavorites: !!feedbackSettings?.allow_favorites,
|
||||
allowRatings: !!feedbackSettings?.allow_ratings,
|
||||
allowComments: !!feedbackSettings?.allow_comments,
|
||||
requireNameEmail: !!feedbackSettings?.require_name_email,
|
||||
}}
|
||||
isSelectionMode={isSelectionMode}
|
||||
selectedPhotos={selectedPhotos}
|
||||
onSelectionChange={setSelectedPhotos}
|
||||
@@ -575,4 +616,4 @@ export const GalleryView: React.FC<GalleryViewProps> = ({ slug, event }) => {
|
||||
</GalleryLayout>
|
||||
</>
|
||||
);
|
||||
};
|
||||
};
|
||||
|
||||
@@ -4,7 +4,6 @@ import { feedbackService } from '../../services/feedback.service';
|
||||
import { PhotoRating } from './PhotoRating';
|
||||
import { PhotoLikes } from './PhotoLikes';
|
||||
import { PhotoComments } from './PhotoComments';
|
||||
import { PhotoFavorites } from './PhotoFavorites';
|
||||
import { Skeleton } from '../common';
|
||||
import type { FeedbackSettings } from '../../services/feedback.service';
|
||||
|
||||
@@ -43,18 +42,14 @@ export const PhotoFeedback: React.FC<PhotoFeedbackProps> = ({
|
||||
// Local state for optimistic updates
|
||||
const [currentRating, setCurrentRating] = useState(0);
|
||||
const [isLiked, setIsLiked] = useState(false);
|
||||
const [isFavorited, setIsFavorited] = useState(false);
|
||||
const [likeCount, setLikeCount] = useState(0);
|
||||
const [favoriteCount, setFavoriteCount] = useState(0);
|
||||
|
||||
// Update local state when data loads
|
||||
useEffect(() => {
|
||||
if (feedbackData) {
|
||||
setCurrentRating(feedbackData.my_feedback.rating || 0);
|
||||
setIsLiked(feedbackData.my_feedback.liked);
|
||||
setIsFavorited(feedbackData.my_feedback.favorited);
|
||||
setLikeCount(feedbackData.summary.like_count);
|
||||
setFavoriteCount(feedbackData.summary.favorite_count);
|
||||
}
|
||||
}, [feedbackData]);
|
||||
|
||||
@@ -70,12 +65,6 @@ export const PhotoFeedback: React.FC<PhotoFeedbackProps> = ({
|
||||
if (onFeedbackUpdate) onFeedbackUpdate();
|
||||
};
|
||||
|
||||
const handleFavoriteChange = (favorited: boolean) => {
|
||||
setIsFavorited(favorited);
|
||||
setFavoriteCount(prev => favorited ? prev + 1 : Math.max(0, prev - 1));
|
||||
if (onFeedbackUpdate) onFeedbackUpdate();
|
||||
};
|
||||
|
||||
if (settingsLoading) {
|
||||
return (
|
||||
<div className={`space-y-3 ${className}`}>
|
||||
@@ -90,7 +79,7 @@ export const PhotoFeedback: React.FC<PhotoFeedbackProps> = ({
|
||||
}
|
||||
|
||||
const hasAnyFeedbackType = settings.allow_ratings || settings.allow_likes ||
|
||||
settings.allow_comments || settings.allow_favorites;
|
||||
settings.allow_comments;
|
||||
|
||||
if (!hasAnyFeedbackType) {
|
||||
return null;
|
||||
@@ -113,7 +102,7 @@ export const PhotoFeedback: React.FC<PhotoFeedbackProps> = ({
|
||||
)}
|
||||
|
||||
{/* Action Buttons */}
|
||||
{(settings.allow_likes || settings.allow_favorites) && (
|
||||
{settings.allow_likes && (
|
||||
<div className="flex items-center gap-2">
|
||||
{settings.allow_likes && (
|
||||
<PhotoLikes
|
||||
@@ -126,17 +115,6 @@ export const PhotoFeedback: React.FC<PhotoFeedbackProps> = ({
|
||||
onLikeChange={handleLikeChange}
|
||||
/>
|
||||
)}
|
||||
{settings.allow_favorites && (
|
||||
<PhotoFavorites
|
||||
photoId={photoId}
|
||||
gallerySlug={gallerySlug}
|
||||
isFavorited={isFavorited}
|
||||
favoriteCount={favoriteCount}
|
||||
isEnabled={true}
|
||||
requireNameEmail={settings.require_name_email || false}
|
||||
onFavoriteChange={handleFavoriteChange}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -158,4 +136,4 @@ export const PhotoFeedback: React.FC<PhotoFeedbackProps> = ({
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
};
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import React, { useState } from 'react';
|
||||
import { Search, SortAsc, Grid, Heart, Star } from 'lucide-react';
|
||||
import { Search, SortAsc, Grid, Heart, Star, MessageSquare } from 'lucide-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Button, Input } from '../common';
|
||||
import type { FilterType } from './GalleryFilter';
|
||||
@@ -32,8 +32,6 @@ interface PhotoFilterBarProps {
|
||||
feedbackEnabled?: boolean;
|
||||
currentFilter?: FilterType;
|
||||
onFilterChange?: (filter: FilterType) => void;
|
||||
likeCount?: number;
|
||||
favoriteCount?: number;
|
||||
}
|
||||
|
||||
export const PhotoFilterBar: React.FC<PhotoFilterBarProps> = ({
|
||||
@@ -49,8 +47,6 @@ export const PhotoFilterBar: React.FC<PhotoFilterBarProps> = ({
|
||||
feedbackEnabled = false,
|
||||
currentFilter = 'all',
|
||||
onFilterChange,
|
||||
likeCount = 0,
|
||||
favoriteCount = 0,
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const [showSortMenu, setShowSortMenu] = useState(false);
|
||||
@@ -143,6 +139,7 @@ export const PhotoFilterBar: React.FC<PhotoFilterBarProps> = ({
|
||||
{/* Categories Row */}
|
||||
{categories && categories.length > 0 && (
|
||||
<div className="flex items-start lg:items-center justify-between flex-col lg:flex-row gap-3">
|
||||
{/* Categories: keep in a horizontal scroll container */}
|
||||
<div className="w-full overflow-x-auto pb-2 lg:pb-0">
|
||||
<div className="flex items-center gap-2 min-w-max">
|
||||
<Button
|
||||
@@ -170,81 +167,104 @@ export const PhotoFilterBar: React.FC<PhotoFilterBarProps> = ({
|
||||
</Button>
|
||||
);
|
||||
})}
|
||||
|
||||
{/* Feedback Filter - Inline on desktop, below on mobile/tablet */}
|
||||
{feedbackEnabled && onFilterChange && (
|
||||
<>
|
||||
{/* Desktop: Divider and inline filter - only on larger screens */}
|
||||
<div className="hidden lg:flex items-center gap-2 ml-2 pl-2 border-l border-neutral-300">
|
||||
<span className="text-sm text-neutral-600 whitespace-nowrap">{t('gallery.feedbackFilter')}:</span>
|
||||
<Button
|
||||
variant={currentFilter === 'all' ? 'primary' : 'outline'}
|
||||
size="sm"
|
||||
onClick={() => onFilterChange('all')}
|
||||
className="text-xs sm:text-sm"
|
||||
>
|
||||
{t('gallery.all')}
|
||||
</Button>
|
||||
<Button
|
||||
variant={currentFilter === 'liked' ? 'primary' : 'outline'}
|
||||
size="sm"
|
||||
onClick={() => onFilterChange('liked')}
|
||||
className="text-xs sm:text-sm flex items-center gap-1"
|
||||
>
|
||||
<Heart className="w-3 h-3" />
|
||||
{likeCount > 0 && <span>{likeCount}</span>}
|
||||
</Button>
|
||||
<Button
|
||||
variant={currentFilter === 'favorited' ? 'primary' : 'outline'}
|
||||
size="sm"
|
||||
onClick={() => onFilterChange('favorited')}
|
||||
className="text-xs sm:text-sm flex items-center gap-1"
|
||||
>
|
||||
<Star className="w-3 h-3" />
|
||||
{favoriteCount > 0 && <span>{favoriteCount}</span>}
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Desktop: compact horizontal feedback filter with headline (icons only) */}
|
||||
{feedbackEnabled && onFilterChange && (
|
||||
<div className="hidden lg:flex items-center gap-2 mx-2 flex-shrink-0">
|
||||
<span className="text-sm text-neutral-600 whitespace-nowrap">
|
||||
{t('gallery.feedbackFilter', 'Feedback Filter')}
|
||||
</span>
|
||||
<div className="flex items-center gap-1">
|
||||
<Button
|
||||
variant={currentFilter === 'all' ? 'primary' : 'outline'}
|
||||
size="sm"
|
||||
onClick={() => onFilterChange('all')}
|
||||
className="p-1 w-8 h-8 flex items-center justify-center"
|
||||
aria-label={t('gallery.all', 'All')}
|
||||
>
|
||||
<Grid className="w-3.5 h-3.5" />
|
||||
</Button>
|
||||
<Button
|
||||
variant={currentFilter === 'liked' ? 'primary' : 'outline'}
|
||||
size="sm"
|
||||
onClick={() => onFilterChange('liked')}
|
||||
className="p-1 w-8 h-8 flex items-center justify-center"
|
||||
aria-label={t('feedback.likes', 'Likes')}
|
||||
>
|
||||
<Heart className="w-3.5 h-3.5" />
|
||||
</Button>
|
||||
<Button
|
||||
variant={currentFilter === 'rated' ? 'primary' : 'outline'}
|
||||
size="sm"
|
||||
onClick={() => onFilterChange('rated')}
|
||||
className="p-1 w-8 h-8 flex items-center justify-center"
|
||||
aria-label={t('gallery.rated', 'Rated')}
|
||||
>
|
||||
<Star className="w-3.5 h-3.5" />
|
||||
</Button>
|
||||
<Button
|
||||
variant={currentFilter === 'commented' ? 'primary' : 'outline'}
|
||||
size="sm"
|
||||
onClick={() => onFilterChange('commented')}
|
||||
className="p-1 w-8 h-8 flex items-center justify-center"
|
||||
aria-label={t('gallery.commented', 'Commented')}
|
||||
>
|
||||
<MessageSquare className="w-3.5 h-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<p className="text-xs md:text-sm text-neutral-600 flex-shrink-0 ml-auto">
|
||||
{photoCount} {photoCount === 1 ? t('common.photo') : t('common.photos')}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Mobile/Tablet: Feedback Filter below categories */}
|
||||
{/* Mobile/Tablet: compact horizontal icons with headline below categories */}
|
||||
{feedbackEnabled && onFilterChange && (
|
||||
<div className="flex lg:hidden items-center gap-2">
|
||||
<span className="text-xs text-neutral-600">{t('gallery.feedbackFilter')}:</span>
|
||||
<div className="flex gap-1 flex-1">
|
||||
<span className="text-xs text-neutral-600 whitespace-nowrap">
|
||||
{t('gallery.feedbackFilter', 'Feedback Filter')}
|
||||
</span>
|
||||
<div className="flex items-center gap-1">
|
||||
<Button
|
||||
variant={currentFilter === 'all' ? 'primary' : 'outline'}
|
||||
size="sm"
|
||||
onClick={() => onFilterChange('all')}
|
||||
className="text-xs flex-1"
|
||||
className="p-1 w-8 h-8 flex items-center justify-center"
|
||||
aria-label={t('gallery.all', 'All')}
|
||||
>
|
||||
{t('gallery.all')}
|
||||
<Grid className="w-3.5 h-3.5" />
|
||||
</Button>
|
||||
<Button
|
||||
variant={currentFilter === 'liked' ? 'primary' : 'outline'}
|
||||
size="sm"
|
||||
onClick={() => onFilterChange('liked')}
|
||||
className="text-xs flex-1 flex items-center justify-center gap-1"
|
||||
className="p-1 w-8 h-8 flex items-center justify-center"
|
||||
aria-label={t('feedback.likes', 'Likes')}
|
||||
>
|
||||
<Heart className="w-3 h-3" />
|
||||
{likeCount > 0 && <span>{likeCount}</span>}
|
||||
<Heart className="w-3.5 h-3.5" />
|
||||
</Button>
|
||||
<Button
|
||||
variant={currentFilter === 'favorited' ? 'primary' : 'outline'}
|
||||
variant={currentFilter === 'rated' ? 'primary' : 'outline'}
|
||||
size="sm"
|
||||
onClick={() => onFilterChange('favorited')}
|
||||
className="text-xs flex-1 flex items-center justify-center gap-1"
|
||||
onClick={() => onFilterChange('rated')}
|
||||
className="p-1 w-8 h-8 flex items-center justify-center"
|
||||
aria-label={t('gallery.rated', 'Rated')}
|
||||
>
|
||||
<Star className="w-3 h-3" />
|
||||
{favoriteCount > 0 && <span>{favoriteCount}</span>}
|
||||
<Star className="w-3.5 h-3.5" />
|
||||
</Button>
|
||||
<Button
|
||||
variant={currentFilter === 'commented' ? 'primary' : 'outline'}
|
||||
size="sm"
|
||||
onClick={() => onFilterChange('commented')}
|
||||
className="p-1 w-8 h-8 flex items-center justify-center"
|
||||
aria-label={t('gallery.commented', 'Commented')}
|
||||
>
|
||||
<MessageSquare className="w-3.5 h-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -254,4 +274,4 @@ export const PhotoFilterBar: React.FC<PhotoFilterBarProps> = ({
|
||||
);
|
||||
};
|
||||
|
||||
PhotoFilterBar.displayName = 'PhotoFilterBar';
|
||||
PhotoFilterBar.displayName = 'PhotoFilterBar';
|
||||
|
||||
@@ -95,35 +95,17 @@ export const PhotoGrid: React.FC<PhotoGridProps> = ({
|
||||
|
||||
const handleDownloadSelected = async () => {
|
||||
if (selectedPhotos.size === 0) return;
|
||||
|
||||
const selectedPhotosList = photos.filter(p => selectedPhotos.has(p.id));
|
||||
|
||||
toastify.info(t('gallery.downloading', { count: selectedPhotos.size }));
|
||||
|
||||
// Download each selected photo
|
||||
const downloadPromises = selectedPhotosList.map(photo =>
|
||||
galleryService.downloadPhoto(slug, photo.id, photo.filename)
|
||||
.catch(err => {
|
||||
// Download failed - error handled by UI
|
||||
return null;
|
||||
})
|
||||
);
|
||||
|
||||
const ids = Array.from(selectedPhotos);
|
||||
toastify.info(t('gallery.downloading', { count: ids.length }));
|
||||
|
||||
try {
|
||||
await Promise.all(downloadPromises);
|
||||
toastify.success(t('gallery.downloadedPhotos', { count: selectedPhotos.size }));
|
||||
|
||||
// Track bulk download
|
||||
analyticsService.trackGalleryEvent('bulk_download', {
|
||||
gallery: slug,
|
||||
photo_count: selectedPhotos.size
|
||||
});
|
||||
|
||||
// Clear selection after download
|
||||
setSelectedPhotos(new Set());
|
||||
setIsSelectionMode(false);
|
||||
await galleryService.downloadSelectedPhotos(slug, ids);
|
||||
analyticsService.trackGalleryEvent('bulk_download_selected', { gallery: slug, photo_count: ids.length });
|
||||
} catch (error) {
|
||||
toastify.error(t('gallery.downloadError'));
|
||||
} finally {
|
||||
setSelectedPhotos(new Set());
|
||||
setIsSelectionMode(false);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -316,7 +298,7 @@ const PhotoThumbnail: React.FC<PhotoThumbnailProps> = ({
|
||||
)}
|
||||
|
||||
{/* Overlay on hover/tap - Always visible on mobile for better UX */}
|
||||
<div className="absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 sm:opacity-0 sm:group-hover:opacity-100 transition-opacity duration-200 rounded-lg flex items-center justify-center gap-2">
|
||||
<div className="absolute inset-0 bg-black/40 opacity-100 md:opacity-0 md:group-hover:opacity-100 transition-opacity duration-200 rounded-lg flex items-center justify-center gap-2">
|
||||
{!isSelectionMode && (
|
||||
<>
|
||||
<button
|
||||
@@ -365,4 +347,4 @@ const PhotoThumbnail: React.FC<PhotoThumbnailProps> = ({
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
};
|
||||
|
||||
@@ -25,6 +25,9 @@ interface PhotoGridWithLayoutsProps {
|
||||
photos: Photo[];
|
||||
slug: string;
|
||||
categoryId?: number | null;
|
||||
// When provided, the hero layout will use this photo
|
||||
// instead of deriving from the filtered photo list.
|
||||
heroPhotoOverride?: Photo | null;
|
||||
isSelectionMode?: boolean;
|
||||
selectedPhotos?: Set<number>;
|
||||
onSelectionChange?: (photos: Set<number>) => void;
|
||||
@@ -38,15 +41,26 @@ interface PhotoGridWithLayoutsProps {
|
||||
allowDownloads?: boolean;
|
||||
protectionLevel?: 'basic' | 'standard' | 'enhanced' | 'maximum';
|
||||
useEnhancedProtection?: boolean;
|
||||
feedbackOptions?: {
|
||||
allowLikes?: boolean;
|
||||
allowFavorites?: boolean;
|
||||
allowRatings?: boolean;
|
||||
allowComments?: boolean;
|
||||
requireNameEmail?: boolean;
|
||||
};
|
||||
onFeedbackChange?: () => void;
|
||||
}
|
||||
|
||||
export const PhotoGridWithLayouts: React.FC<PhotoGridWithLayoutsProps> = ({
|
||||
photos,
|
||||
slug,
|
||||
categoryId,
|
||||
heroPhotoOverride,
|
||||
isSelectionMode: parentSelectionMode,
|
||||
selectedPhotos: parentSelectedPhotos,
|
||||
feedbackEnabled,
|
||||
feedbackOptions,
|
||||
onFeedbackChange,
|
||||
allowDownloads = true,
|
||||
protectionLevel = 'standard',
|
||||
useEnhancedProtection = false,
|
||||
@@ -61,6 +75,7 @@ export const PhotoGridWithLayouts: React.FC<PhotoGridWithLayoutsProps> = ({
|
||||
const { t } = useTranslation();
|
||||
const { theme } = useTheme();
|
||||
const [selectedPhotoIndex, setSelectedPhotoIndex] = useState<number | null>(null);
|
||||
const [openFeedbackInitially, setOpenFeedbackInitially] = useState<boolean>(false);
|
||||
const [localSelectedPhotos, setLocalSelectedPhotos] = useState<Set<number>>(new Set());
|
||||
const [localSelectionMode, setLocalSelectionMode] = useState(false);
|
||||
const downloadPhotoMutation = useDownloadPhoto();
|
||||
@@ -77,10 +92,24 @@ export const PhotoGridWithLayouts: React.FC<PhotoGridWithLayoutsProps> = ({
|
||||
}, [categoryId]);
|
||||
|
||||
const handlePhotoClick = (index: number) => {
|
||||
setOpenFeedbackInitially(false);
|
||||
setSelectedPhotoIndex(index);
|
||||
};
|
||||
|
||||
const handleOpenWithFeedback = (index: number) => {
|
||||
setOpenFeedbackInitially(true);
|
||||
setSelectedPhotoIndex(index);
|
||||
};
|
||||
|
||||
const handlePhotoSelect = (photoId: number) => {
|
||||
// Auto-enable selection mode when selecting via checkbox
|
||||
if (!isSelectionMode) {
|
||||
if (parentToggleSelectionMode) {
|
||||
parentToggleSelectionMode();
|
||||
} else {
|
||||
setLocalSelectionMode(true);
|
||||
}
|
||||
}
|
||||
const newSelected = new Set(selectedPhotos);
|
||||
if (newSelected.has(photoId)) {
|
||||
newSelected.delete(photoId);
|
||||
@@ -114,39 +143,21 @@ export const PhotoGridWithLayouts: React.FC<PhotoGridWithLayoutsProps> = ({
|
||||
|
||||
const handleDownloadSelected = async () => {
|
||||
if (selectedPhotos.size === 0) return;
|
||||
|
||||
const selectedPhotosList = photos.filter(p => selectedPhotos.has(p.id));
|
||||
|
||||
toastify.info(t('gallery.downloading', { count: selectedPhotos.size }));
|
||||
|
||||
// Download each selected photo
|
||||
const downloadPromises = selectedPhotosList.map(photo =>
|
||||
galleryService.downloadPhoto(slug, photo.id, photo.filename)
|
||||
.catch(err => {
|
||||
// Download failed - error handled by UI
|
||||
return null;
|
||||
})
|
||||
);
|
||||
|
||||
const ids = Array.from(selectedPhotos);
|
||||
toastify.info(t('gallery.downloading', { count: ids.length }));
|
||||
|
||||
try {
|
||||
await Promise.all(downloadPromises);
|
||||
toastify.success(t('gallery.downloadedPhotos', { count: selectedPhotos.size }));
|
||||
|
||||
// Track bulk download
|
||||
analyticsService.trackGalleryEvent('bulk_download', {
|
||||
gallery: slug,
|
||||
photo_count: selectedPhotos.size
|
||||
});
|
||||
|
||||
// Clear selection after download
|
||||
await galleryService.downloadSelectedPhotos(slug, ids);
|
||||
analyticsService.trackGalleryEvent('bulk_download_selected', { gallery: slug, photo_count: ids.length });
|
||||
} catch (error) {
|
||||
toastify.error(t('gallery.downloadError'));
|
||||
} finally {
|
||||
setSelectedPhotos(new Set());
|
||||
if (parentToggleSelectionMode) {
|
||||
parentToggleSelectionMode();
|
||||
} else {
|
||||
setLocalSelectionMode(false);
|
||||
}
|
||||
} catch (error) {
|
||||
toastify.error(t('gallery.downloadError'));
|
||||
}
|
||||
};
|
||||
|
||||
@@ -166,7 +177,10 @@ export const PhotoGridWithLayouts: React.FC<PhotoGridWithLayoutsProps> = ({
|
||||
photos,
|
||||
slug,
|
||||
onPhotoClick: handlePhotoClick,
|
||||
onOpenPhotoWithFeedback: handleOpenWithFeedback,
|
||||
onFeedbackChange: onFeedbackChange,
|
||||
onDownload: handleDownload,
|
||||
heroPhotoOverride,
|
||||
selectedPhotos,
|
||||
allowDownloads,
|
||||
protectionLevel,
|
||||
@@ -178,6 +192,7 @@ export const PhotoGridWithLayouts: React.FC<PhotoGridWithLayoutsProps> = ({
|
||||
eventDate,
|
||||
expiresAt,
|
||||
feedbackEnabled,
|
||||
feedbackOptions,
|
||||
};
|
||||
|
||||
let LayoutComponent;
|
||||
@@ -275,8 +290,9 @@ export const PhotoGridWithLayouts: React.FC<PhotoGridWithLayoutsProps> = ({
|
||||
allowDownloads={allowDownloads}
|
||||
protectionLevel={protectionLevel}
|
||||
useEnhancedProtection={useEnhancedProtection}
|
||||
initialShowFeedback={openFeedbackInitially}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
};
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { useDevToolsProtection } from '../../hooks/useDevToolsProtection';
|
||||
import { X, ChevronLeft, ChevronRight, Download, ZoomIn, ZoomOut, MessageSquare } from 'lucide-react';
|
||||
import { X, ChevronLeft, ChevronRight, Download, ZoomIn, ZoomOut, MessageSquare, Heart, Star } from 'lucide-react';
|
||||
import type { Photo } from '../../types';
|
||||
import { useDownloadPhoto } from '../../hooks/useGallery';
|
||||
import { AuthenticatedImage } from '../common';
|
||||
import { PhotoFeedback } from './PhotoFeedback';
|
||||
import { feedbackService } from '../../services/feedback.service';
|
||||
import { FeedbackIdentityModal } from './FeedbackIdentityModal';
|
||||
|
||||
interface PhotoLightboxProps {
|
||||
photos: Photo[];
|
||||
@@ -15,6 +17,7 @@ interface PhotoLightboxProps {
|
||||
allowDownloads?: boolean;
|
||||
protectionLevel?: 'basic' | 'standard' | 'enhanced' | 'maximum';
|
||||
useEnhancedProtection?: boolean;
|
||||
initialShowFeedback?: boolean;
|
||||
}
|
||||
|
||||
export const PhotoLightbox: React.FC<PhotoLightboxProps> = ({
|
||||
@@ -26,6 +29,7 @@ export const PhotoLightbox: React.FC<PhotoLightboxProps> = ({
|
||||
allowDownloads = true,
|
||||
protectionLevel = 'standard',
|
||||
useEnhancedProtection = false,
|
||||
initialShowFeedback = false,
|
||||
}) => {
|
||||
const [currentIndex, setCurrentIndex] = useState(initialIndex);
|
||||
const [zoom, setZoom] = useState(1);
|
||||
@@ -33,7 +37,28 @@ export const PhotoLightbox: React.FC<PhotoLightboxProps> = ({
|
||||
const [dragStart, setDragStart] = useState({ x: 0, y: 0 });
|
||||
const [dragOffset, setDragOffset] = useState({ x: 0, y: 0 });
|
||||
const [touchDistance, setTouchDistance] = useState<number | null>(null);
|
||||
const [showFeedback, setShowFeedback] = useState(false);
|
||||
const [showFeedback, setShowFeedback] = useState(initialShowFeedback);
|
||||
const [isSmallScreen, setIsSmallScreen] = useState<boolean>(typeof window !== 'undefined' ? window.innerWidth < 640 : false);
|
||||
const [feedbackSettings, setFeedbackSettings] = useState<{
|
||||
feedback_enabled?: boolean;
|
||||
allow_likes?: boolean;
|
||||
allow_ratings?: boolean;
|
||||
require_name_email?: boolean;
|
||||
} | null>(null);
|
||||
const [myLiked, setMyLiked] = useState<boolean>(false);
|
||||
const [myRating, setMyRating] = useState<number>(0);
|
||||
const [likeCount, setLikeCount] = useState<number>(0);
|
||||
const [avgRating, setAvgRating] = useState<number>(0);
|
||||
const [totalRatings, setTotalRatings] = useState<number>(0);
|
||||
const [savedIdentity, setSavedIdentity] = useState<{ name: string; email: string } | null>(null);
|
||||
const [showIdentityModal, setShowIdentityModal] = useState(false);
|
||||
const [pendingAction, setPendingAction] = useState<null | { type: 'like' | 'rating'; rating?: number }>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const onResize = () => setIsSmallScreen(window.innerWidth < 640);
|
||||
window.addEventListener('resize', onResize);
|
||||
return () => window.removeEventListener('resize', onResize);
|
||||
}, []);
|
||||
|
||||
const downloadPhotoMutation = useDownloadPhoto();
|
||||
const currentPhoto = photos[currentIndex];
|
||||
@@ -111,6 +136,81 @@ export const PhotoLightbox: React.FC<PhotoLightboxProps> = ({
|
||||
};
|
||||
}, [currentIndex]);
|
||||
|
||||
// Load feedback settings once
|
||||
useEffect(() => {
|
||||
let mounted = true;
|
||||
(async () => {
|
||||
try {
|
||||
const settings = await feedbackService.getGalleryFeedbackSettings(slug);
|
||||
if (mounted) setFeedbackSettings(settings as any);
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
})();
|
||||
return () => { mounted = false; };
|
||||
}, [slug]);
|
||||
|
||||
// Load my feedback for the current photo
|
||||
useEffect(() => {
|
||||
let mounted = true;
|
||||
(async () => {
|
||||
try {
|
||||
if (!feedbackSettings?.feedback_enabled) return;
|
||||
const data = await feedbackService.getPhotoFeedback(slug, String(currentPhoto.id));
|
||||
if (!mounted) return;
|
||||
setMyLiked(!!data.my_feedback.liked);
|
||||
setMyRating(data.my_feedback.rating || 0);
|
||||
setLikeCount(Number(data.summary?.like_count) || 0);
|
||||
setAvgRating(Number(data.summary?.average_rating) || 0);
|
||||
setTotalRatings(Number(data.summary?.total_ratings) || 0);
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
})();
|
||||
return () => { mounted = false; };
|
||||
}, [slug, currentPhoto.id, feedbackSettings?.feedback_enabled]);
|
||||
|
||||
const submitLike = async () => {
|
||||
const needIdentity = feedbackSettings?.require_name_email && !savedIdentity;
|
||||
if (needIdentity) {
|
||||
setPendingAction({ type: 'like' });
|
||||
setShowIdentityModal(true);
|
||||
return;
|
||||
}
|
||||
await feedbackService.submitFeedback(slug, String(currentPhoto.id), {
|
||||
feedback_type: 'like',
|
||||
guest_name: savedIdentity?.name,
|
||||
guest_email: savedIdentity?.email,
|
||||
});
|
||||
setMyLiked(prev => {
|
||||
const next = !prev;
|
||||
setLikeCount(c => Math.max(0, c + (next ? 1 : -1)));
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
const submitRating = async (value: number) => {
|
||||
const needIdentity = feedbackSettings?.require_name_email && !savedIdentity;
|
||||
if (needIdentity) {
|
||||
setPendingAction({ type: 'rating', rating: value });
|
||||
setShowIdentityModal(true);
|
||||
return;
|
||||
}
|
||||
await feedbackService.submitFeedback(slug, String(currentPhoto.id), {
|
||||
feedback_type: 'rating',
|
||||
rating: value,
|
||||
guest_name: savedIdentity?.name,
|
||||
guest_email: savedIdentity?.email,
|
||||
});
|
||||
setMyRating(value);
|
||||
// Refresh current summary to reflect average and totals
|
||||
try {
|
||||
const fresh = await feedbackService.getPhotoFeedback(slug, String(currentPhoto.id));
|
||||
setAvgRating(Number(fresh.summary?.average_rating) || 0);
|
||||
setTotalRatings(Number(fresh.summary?.total_ratings) || 0);
|
||||
} catch {}
|
||||
};
|
||||
|
||||
const goToPrevious = () => {
|
||||
setCurrentIndex((prev) => (prev > 0 ? prev - 1 : photos.length - 1));
|
||||
resetZoom();
|
||||
@@ -211,13 +311,17 @@ export const PhotoLightbox: React.FC<PhotoLightboxProps> = ({
|
||||
`fixed inset-0 bg-black z-50 flex items-center justify-center protected-image protection-${protectionLevel}` :
|
||||
'fixed inset-0 bg-black z-50 flex items-center justify-center';
|
||||
|
||||
const desktopFeedbackWidth = 416; // 26rem; keep in sync with panel width
|
||||
const isDesktopFeedback = showFeedback && !isSmallScreen;
|
||||
|
||||
return (
|
||||
<div className={lightboxClass}>
|
||||
{/* Close button */}
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="absolute top-4 right-4 p-2 bg-white/10 hover:bg-white/20 rounded-full transition-colors z-20"
|
||||
className="absolute top-4 p-2 bg-white/10 hover:bg-white/20 rounded-full transition-colors z-30"
|
||||
aria-label="Close"
|
||||
style={{ right: isDesktopFeedback ? `${desktopFeedbackWidth + 16}px` : '1rem' }}
|
||||
>
|
||||
<X className="w-6 h-6 text-white" />
|
||||
</button>
|
||||
@@ -231,16 +335,22 @@ export const PhotoLightbox: React.FC<PhotoLightboxProps> = ({
|
||||
<ChevronLeft className="w-6 h-6 text-white" />
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={goToNext}
|
||||
className="absolute right-4 top-1/2 -translate-y-1/2 p-2 bg-white/10 hover:bg-white/20 rounded-full transition-colors z-20"
|
||||
aria-label="Next photo"
|
||||
>
|
||||
<ChevronRight className="w-6 h-6 text-white" />
|
||||
</button>
|
||||
{!showFeedback || !isSmallScreen ? (
|
||||
<button
|
||||
onClick={goToNext}
|
||||
className="absolute top-1/2 -translate-y-1/2 p-2 bg-white/10 hover:bg-white/20 rounded-full transition-colors z-30"
|
||||
aria-label="Next photo"
|
||||
style={{ right: isDesktopFeedback ? `${desktopFeedbackWidth + 16}px` : '1rem' }}
|
||||
>
|
||||
<ChevronRight className="w-6 h-6 text-white" />
|
||||
</button>
|
||||
) : null}
|
||||
|
||||
{/* Bottom toolbar */}
|
||||
<div className="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/80 to-transparent p-4 z-20">
|
||||
<div
|
||||
className="absolute bottom-0 left-0 bg-gradient-to-t from-black/80 to-transparent p-4 z-20"
|
||||
style={{ right: isDesktopFeedback ? `${desktopFeedbackWidth}px` : 0 }}
|
||||
>
|
||||
<div className="max-w-4xl mx-auto flex items-center justify-between">
|
||||
<div className="text-white">
|
||||
<p className="text-sm opacity-75">
|
||||
@@ -280,6 +390,39 @@ export const PhotoLightbox: React.FC<PhotoLightboxProps> = ({
|
||||
<Download className="w-5 h-5 text-white" />
|
||||
</button>
|
||||
)}
|
||||
|
||||
{/* Inline Like */}
|
||||
{feedbackEnabled && feedbackSettings?.allow_likes && (
|
||||
<div className="flex items-center gap-1">
|
||||
<button
|
||||
onClick={submitLike}
|
||||
className={`p-2 rounded-full transition-colors ${myLiked ? 'bg-red-500/80 hover:bg-red-500' : 'bg-white/10 hover:bg-white/20'}`}
|
||||
aria-label={myLiked ? 'Unlike photo' : 'Like photo'}
|
||||
title={myLiked ? 'Unlike' : 'Like'}
|
||||
>
|
||||
<Heart className={`w-5 h-5 ${myLiked ? 'text-white' : 'text-white'}`} />
|
||||
</button>
|
||||
<span className="text-white text-xs min-w-[1.5rem] text-center select-none">{likeCount}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Inline Rating */}
|
||||
{feedbackEnabled && feedbackSettings?.allow_ratings && (
|
||||
<div className="flex items-center gap-1 ml-1" aria-label="Rate photo">
|
||||
{[1,2,3,4,5].map((i) => (
|
||||
<button
|
||||
key={i}
|
||||
onClick={() => submitRating(i)}
|
||||
className="p-1"
|
||||
aria-label={`Rate ${i} star${i>1?'s':''}`}
|
||||
title={`Rate ${i}`}
|
||||
>
|
||||
<Star className={`w-5 h-5 ${myRating >= i ? 'text-yellow-400 fill-yellow-400' : 'text-white/70'}`} />
|
||||
</button>
|
||||
))}
|
||||
<span className="text-white/90 text-xs ml-2 select-none">{avgRating.toFixed(1)} ({totalRatings})</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Feedback button with indicator */}
|
||||
{feedbackEnabled && (
|
||||
@@ -305,7 +448,7 @@ export const PhotoLightbox: React.FC<PhotoLightboxProps> = ({
|
||||
|
||||
{/* Image container */}
|
||||
<div
|
||||
className="absolute inset-0 flex items-center justify-center z-0"
|
||||
className="absolute top-0 left-0 bottom-0 flex items-center justify-center z-0"
|
||||
onClick={handleImageClick}
|
||||
onMouseDown={handleMouseDown}
|
||||
onMouseMove={handleMouseMove}
|
||||
@@ -314,11 +457,15 @@ export const PhotoLightbox: React.FC<PhotoLightboxProps> = ({
|
||||
onTouchStart={handleTouchStart}
|
||||
onTouchMove={handleTouchMove}
|
||||
onTouchEnd={handleTouchEnd}
|
||||
style={{ cursor: zoom > 1 ? (isDragging ? 'grabbing' : 'grab') : 'default' }}
|
||||
style={{
|
||||
cursor: zoom > 1 ? (isDragging ? 'grabbing' : 'grab') : 'default',
|
||||
right: isDesktopFeedback ? `${desktopFeedbackWidth}px` : 0,
|
||||
}}
|
||||
>
|
||||
<AuthenticatedImage
|
||||
src={currentPhoto.url}
|
||||
alt={currentPhoto.filename}
|
||||
fallbackSrc={currentPhoto.thumbnail_url || undefined}
|
||||
className="max-w-full max-h-full object-contain select-none"
|
||||
style={{
|
||||
transform: `scale(${zoom}) translate(${dragOffset.x / zoom}px, ${dragOffset.y / zoom}px)`,
|
||||
@@ -369,7 +516,7 @@ export const PhotoLightbox: React.FC<PhotoLightboxProps> = ({
|
||||
|
||||
{/* Feedback Panel */}
|
||||
{showFeedback && (
|
||||
<div className="absolute right-0 top-0 bottom-0 w-full sm:w-96 lg:w-[28rem] bg-white shadow-xl z-20 overflow-y-auto">
|
||||
<div className="absolute right-0 top-0 bottom-0 w-full sm:w-[26rem] bg-white shadow-xl z-20 overflow-y-auto flex flex-col border-l border-neutral-200">
|
||||
<div className="sticky top-0 bg-white border-b px-4 py-3 flex items-center justify-between">
|
||||
<h3 className="font-semibold text-neutral-900">Photo Feedback</h3>
|
||||
<button
|
||||
@@ -380,7 +527,7 @@ export const PhotoLightbox: React.FC<PhotoLightboxProps> = ({
|
||||
<X className="w-5 h-5" />
|
||||
</button>
|
||||
</div>
|
||||
<div className="p-4">
|
||||
<div className="p-4 flex-1 overflow-y-auto">
|
||||
<PhotoFeedback
|
||||
photoId={currentPhoto.id}
|
||||
gallerySlug={slug}
|
||||
@@ -390,6 +537,34 @@ export const PhotoLightbox: React.FC<PhotoLightboxProps> = ({
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Identity Modal for required name/email */}
|
||||
<FeedbackIdentityModal
|
||||
isOpen={showIdentityModal}
|
||||
onClose={() => { setShowIdentityModal(false); setPendingAction(null); }}
|
||||
onSubmit={async (name, email) => {
|
||||
setSavedIdentity({ name, email });
|
||||
setShowIdentityModal(false);
|
||||
if (pendingAction?.type === 'like') {
|
||||
await feedbackService.submitFeedback(slug, String(currentPhoto.id), {
|
||||
feedback_type: 'like',
|
||||
guest_name: name,
|
||||
guest_email: email,
|
||||
});
|
||||
setMyLiked(true);
|
||||
} else if (pendingAction?.type === 'rating' && pendingAction.rating) {
|
||||
await feedbackService.submitFeedback(slug, String(currentPhoto.id), {
|
||||
feedback_type: 'rating',
|
||||
rating: pendingAction.rating,
|
||||
guest_name: name,
|
||||
guest_email: email,
|
||||
});
|
||||
setMyRating(pendingAction.rating);
|
||||
}
|
||||
setPendingAction(null);
|
||||
}}
|
||||
feedbackType={pendingAction?.type === 'rating' ? 'rating' : 'like'}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
};
|
||||
|
||||
@@ -10,4 +10,3 @@ export { PhotoFeedback } from './PhotoFeedback';
|
||||
export { PhotoRating } from './PhotoRating';
|
||||
export { PhotoLikes } from './PhotoLikes';
|
||||
export { PhotoComments } from './PhotoComments';
|
||||
export { PhotoFavorites } from './PhotoFavorites';
|
||||
@@ -5,6 +5,10 @@ export interface BaseGalleryLayoutProps {
|
||||
photos: Photo[];
|
||||
slug: string;
|
||||
onPhotoClick: (index: number) => void;
|
||||
// Optional: open the lightbox with feedback panel visible
|
||||
onOpenPhotoWithFeedback?: (index: number) => void;
|
||||
// Notify parent that feedback (like/favorite/rating/comment) changed
|
||||
onFeedbackChange?: () => void;
|
||||
onDownload: (photo: Photo, e: React.MouseEvent) => void;
|
||||
selectedPhotos?: Set<number>;
|
||||
isSelectionMode?: boolean;
|
||||
@@ -17,8 +21,15 @@ export interface BaseGalleryLayoutProps {
|
||||
protectionLevel?: 'basic' | 'standard' | 'enhanced' | 'maximum';
|
||||
useEnhancedProtection?: boolean;
|
||||
feedbackEnabled?: boolean;
|
||||
feedbackOptions?: {
|
||||
allowLikes?: boolean;
|
||||
allowFavorites?: boolean;
|
||||
allowRatings?: boolean;
|
||||
allowComments?: boolean;
|
||||
requireNameEmail?: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
export abstract class BaseGalleryLayout<T extends BaseGalleryLayoutProps = BaseGalleryLayoutProps> extends React.Component<T> {
|
||||
abstract render(): React.ReactNode;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,16 +1,20 @@
|
||||
import React, { useState, useEffect, useRef } from 'react';
|
||||
import { ChevronLeft, ChevronRight, Download, Maximize2, Play, Pause } from 'lucide-react';
|
||||
import { ChevronLeft, ChevronRight, Download, Maximize2, Play, Pause, Heart, MessageSquare } from 'lucide-react';
|
||||
import { useTheme } from '../../../contexts/ThemeContext';
|
||||
import { AuthenticatedImage, Button } from '../../common';
|
||||
import type { BaseGalleryLayoutProps } from './BaseGalleryLayout';
|
||||
import { FeedbackIdentityModal } from '../../gallery/FeedbackIdentityModal';
|
||||
import { feedbackService } from '../../../services/feedback.service';
|
||||
|
||||
export const CarouselGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
||||
photos,
|
||||
slug,
|
||||
onPhotoClick,
|
||||
onOpenPhotoWithFeedback,
|
||||
onDownload,
|
||||
allowDownloads = true,
|
||||
// selectedPhotos = new Set(),
|
||||
// isSelectionMode = false
|
||||
feedbackEnabled = false,
|
||||
feedbackOptions
|
||||
}) => {
|
||||
const { theme } = useTheme();
|
||||
const [currentIndex, setCurrentIndex] = useState(0);
|
||||
@@ -59,6 +63,11 @@ export const CarouselGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
||||
if (photos.length === 0) return null;
|
||||
|
||||
const currentPhoto = photos[currentIndex];
|
||||
const [showIdentityModal, setShowIdentityModal] = useState(false);
|
||||
const [pendingAction, setPendingAction] = useState<null | { type: 'like'; photoId: number }>(null);
|
||||
const [savedIdentity, setSavedIdentity] = useState<{ name: string; email: string } | null>(null);
|
||||
const [likedIds, setLikedIds] = useState<Set<number>>(new Set());
|
||||
const canQuickComment = Boolean(feedbackEnabled && feedbackOptions?.allowComments && onOpenPhotoWithFeedback);
|
||||
|
||||
return (
|
||||
<div className="relative">
|
||||
@@ -136,6 +145,44 @@ export const CarouselGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
||||
<Download className="w-5 h-5" />
|
||||
</Button>
|
||||
)}
|
||||
{feedbackOptions?.allowLikes && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={async () => {
|
||||
if (feedbackOptions?.requireNameEmail && !savedIdentity) {
|
||||
setPendingAction({ type: 'like', photoId: currentPhoto.id });
|
||||
setShowIdentityModal(true);
|
||||
return;
|
||||
}
|
||||
setLikedIds(prev => new Set(prev).add(currentPhoto.id));
|
||||
try {
|
||||
await feedbackService.submitFeedback(slug!, String(currentPhoto.id), {
|
||||
feedback_type: 'like',
|
||||
guest_name: savedIdentity?.name,
|
||||
guest_email: savedIdentity?.email,
|
||||
});
|
||||
} catch (_) {}
|
||||
}}
|
||||
className={`hover:bg-white/20 ${likedIds.has(currentPhoto.id) ? 'text-red-400' : 'text-white'}`}
|
||||
title="Like photo"
|
||||
aria-pressed={likedIds.has(currentPhoto.id)}
|
||||
>
|
||||
<Heart className="w-5 h-5" />
|
||||
</Button>
|
||||
)}
|
||||
{canQuickComment && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => { onOpenPhotoWithFeedback?.(currentIndex); }}
|
||||
className="text-white hover:bg-white/20"
|
||||
title="Comment"
|
||||
aria-label="Comment on photo"
|
||||
>
|
||||
<MessageSquare className="w-5 h-5" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -181,6 +228,24 @@ export const CarouselGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
||||
</div>
|
||||
)}
|
||||
|
||||
<FeedbackIdentityModal
|
||||
isOpen={showIdentityModal}
|
||||
onClose={() => { setShowIdentityModal(false); setPendingAction(null); }}
|
||||
onSubmit={async (name, email) => {
|
||||
setSavedIdentity({ name, email });
|
||||
setShowIdentityModal(false);
|
||||
if (pendingAction) {
|
||||
await feedbackService.submitFeedback(slug!, String(pendingAction.photoId), {
|
||||
feedback_type: pendingAction.type,
|
||||
guest_name: name,
|
||||
guest_email: email,
|
||||
});
|
||||
setPendingAction(null);
|
||||
}
|
||||
}}
|
||||
feedbackType="like"
|
||||
/>
|
||||
|
||||
<style>{`
|
||||
@keyframes progress {
|
||||
from { width: 0%; }
|
||||
@@ -189,4 +254,4 @@ export const CarouselGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
||||
`}</style>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
};
|
||||
|
||||
@@ -3,6 +3,8 @@ import { Download, Maximize2, Check, MessageSquare, Star, Heart } from 'lucide-r
|
||||
import { useInView } from 'react-intersection-observer';
|
||||
import { useTheme } from '../../../contexts/ThemeContext';
|
||||
import { AuthenticatedImage } from '../../common';
|
||||
import { FeedbackIdentityModal } from '../../gallery/FeedbackIdentityModal';
|
||||
import { feedbackService } from '../../../services/feedback.service';
|
||||
import type { BaseGalleryLayoutProps } from './BaseGalleryLayout';
|
||||
import type { Photo } from '../../../types';
|
||||
|
||||
@@ -12,12 +14,26 @@ interface GridPhotoProps {
|
||||
isSelectionMode: boolean;
|
||||
onClick: (e: React.MouseEvent) => void;
|
||||
onDownload: (e: React.MouseEvent) => void;
|
||||
onToggleSelect: () => void;
|
||||
animationType?: string;
|
||||
allowDownloads?: boolean;
|
||||
slug?: string;
|
||||
protectionLevel?: 'basic' | 'standard' | 'enhanced' | 'maximum';
|
||||
useEnhancedProtection?: boolean;
|
||||
feedbackEnabled?: boolean;
|
||||
feedbackOptions?: {
|
||||
allowLikes?: boolean;
|
||||
allowRatings?: boolean;
|
||||
allowComments?: boolean;
|
||||
requireNameEmail?: boolean;
|
||||
};
|
||||
savedIdentity?: { name: string; email: string } | null;
|
||||
onRequireIdentity?: (action: 'like', photoId: number) => void;
|
||||
onQuickComment?: () => void;
|
||||
onFeedbackChange?: () => void;
|
||||
// Immediate UI like state and callback
|
||||
liked?: boolean;
|
||||
onLikeSuccess?: () => void;
|
||||
}
|
||||
|
||||
const GridPhoto: React.FC<GridPhotoProps> = ({
|
||||
@@ -26,13 +42,22 @@ const GridPhoto: React.FC<GridPhotoProps> = ({
|
||||
isSelectionMode,
|
||||
onClick,
|
||||
onDownload,
|
||||
onToggleSelect,
|
||||
animationType = 'fade',
|
||||
allowDownloads = true,
|
||||
slug,
|
||||
protectionLevel = 'standard',
|
||||
useEnhancedProtection = false,
|
||||
feedbackEnabled = false
|
||||
feedbackEnabled = false,
|
||||
feedbackOptions,
|
||||
savedIdentity,
|
||||
onRequireIdentity,
|
||||
onQuickComment,
|
||||
onFeedbackChange,
|
||||
liked = false,
|
||||
onLikeSuccess
|
||||
}) => {
|
||||
// handled by parent layout; kept here for type completeness but not used
|
||||
const { ref, inView } = useInView({
|
||||
triggerOnce: true,
|
||||
threshold: 0.1,
|
||||
@@ -79,7 +104,7 @@ const GridPhoto: React.FC<GridPhotoProps> = ({
|
||||
}}
|
||||
/>
|
||||
|
||||
<div className="absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity duration-200 rounded-lg flex items-center justify-center gap-2">
|
||||
<div className="absolute inset-0 bg-black/40 opacity-100 md:opacity-0 md:group-hover:opacity-100 transition-opacity duration-200 rounded-lg flex items-center justify-center gap-2">
|
||||
{!isSelectionMode && (
|
||||
<>
|
||||
<button
|
||||
@@ -101,44 +126,91 @@ const GridPhoto: React.FC<GridPhotoProps> = ({
|
||||
<Download className="w-5 h-5 text-neutral-800" />
|
||||
</button>
|
||||
)}
|
||||
{onQuickComment && (
|
||||
<button
|
||||
className="p-2 bg-white/90 rounded-full hover:bg-white transition-colors"
|
||||
onClick={(e) => { e.stopPropagation(); onQuickComment(); }}
|
||||
aria-label="Comment on photo"
|
||||
title="Comment"
|
||||
>
|
||||
<MessageSquare className="w-5 h-5 text-neutral-800" />
|
||||
</button>
|
||||
)}
|
||||
{/* Quick feedback actions */}
|
||||
{feedbackOptions?.allowLikes && (
|
||||
<button
|
||||
className={`p-2 rounded-full transition-colors ${liked ? 'bg-red-500/90 hover:bg-red-500' : 'bg-white/90 hover:bg-white'}`}
|
||||
onClick={async (e) => {
|
||||
e.stopPropagation();
|
||||
if (feedbackOptions?.requireNameEmail && !savedIdentity && onRequireIdentity) {
|
||||
onRequireIdentity('like', photo.id);
|
||||
return;
|
||||
}
|
||||
// Optimistic UI: mark as liked immediately
|
||||
if (onLikeSuccess) onLikeSuccess();
|
||||
try {
|
||||
await feedbackService.submitFeedback(slug!, String(photo.id), {
|
||||
feedback_type: 'like',
|
||||
guest_name: savedIdentity?.name,
|
||||
guest_email: savedIdentity?.email,
|
||||
});
|
||||
} catch (err) {
|
||||
// Keep optimistic state; a refresh will reconcile
|
||||
console.warn('Like submit failed, keeping optimistic UI', err);
|
||||
}
|
||||
if (onFeedbackChange) onFeedbackChange();
|
||||
}}
|
||||
aria-label="Like photo"
|
||||
aria-pressed={liked}
|
||||
title="Like"
|
||||
>
|
||||
<Heart className={`w-5 h-5 ${liked ? 'text-white fill-white' : 'text-neutral-800'}`} />
|
||||
</button>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{isSelectionMode && (
|
||||
<div className={`absolute top-2 right-2 ${isSelected ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'} transition-opacity`}>
|
||||
<div className={`w-6 h-6 rounded-full border-2 ${isSelected ? 'bg-primary-600 border-primary-600' : 'bg-white/80 border-white'} flex items-center justify-center transition-colors`}>
|
||||
{isSelected && <Check className="w-4 h-4 text-white" />}
|
||||
</div>
|
||||
{/* Selection Checkbox (visible on hover or when selected) */}
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`Select ${photo.filename}`}
|
||||
role="checkbox"
|
||||
aria-checked={isSelected}
|
||||
data-testid={`gallery-photo-checkbox-${photo.id}`}
|
||||
className={`absolute top-2 right-2 z-20 transition-opacity ${
|
||||
isSelected ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'
|
||||
}`}
|
||||
onClick={(e) => { e.stopPropagation(); onToggleSelect(); }}
|
||||
>
|
||||
<div className={`w-6 h-6 rounded-full border-2 ${isSelected ? 'bg-primary-600 border-primary-600' : 'bg-white/90 border-white'} flex items-center justify-center transition-colors`}>
|
||||
{isSelected && <Check className="w-4 h-4 text-white" />}
|
||||
</div>
|
||||
)}
|
||||
</button>
|
||||
|
||||
{/* Feedback Indicators */}
|
||||
{feedbackEnabled && (photo.comment_count > 0 || photo.average_rating > 0 || photo.like_count > 0) && (
|
||||
<div className="absolute top-2 left-2 flex gap-1 z-10">
|
||||
{photo.comment_count > 0 && (
|
||||
<div className="bg-white/90 backdrop-blur-sm rounded-full px-2 py-1 flex items-center gap-1" title={`${photo.comment_count} comments`}>
|
||||
<MessageSquare className="w-3.5 h-3.5 text-primary-600" fill="currentColor" />
|
||||
<span className="text-xs font-medium text-neutral-700">{photo.comment_count}</span>
|
||||
</div>
|
||||
{/* Feedback Indicators (always visible, bottom-left). Show like immediately when user liked */}
|
||||
{(photo.comment_count > 0 || photo.average_rating > 0 || photo.like_count > 0 || liked) && (
|
||||
<div className={`absolute ${photo.type === 'collage' ? 'bottom-8' : 'bottom-2'} left-2 flex items-center gap-1 z-10`}>
|
||||
{(photo.like_count > 0 || liked) && (
|
||||
<span className="inline-flex items-center justify-center w-6 h-6 rounded-full bg-white/90 backdrop-blur-sm" title="Liked">
|
||||
<Heart className="w-3.5 h-3.5 text-red-500" fill="currentColor" />
|
||||
</span>
|
||||
)}
|
||||
{photo.average_rating > 0 && (
|
||||
<div className="bg-white/90 backdrop-blur-sm rounded-full px-2 py-1 flex items-center gap-1" title={`Rating: ${Number(photo.average_rating).toFixed(1)}`}>
|
||||
<span className="inline-flex items-center justify-center w-6 h-6 rounded-full bg-white/90 backdrop-blur-sm" title="Rated">
|
||||
<Star className="w-3.5 h-3.5 text-yellow-500" fill="currentColor" />
|
||||
<span className="text-xs font-medium text-neutral-700">{Number(photo.average_rating).toFixed(1)}</span>
|
||||
</div>
|
||||
</span>
|
||||
)}
|
||||
{photo.like_count > 0 && (
|
||||
<div className="bg-white/90 backdrop-blur-sm rounded-full px-2 py-1 flex items-center gap-1" title={`${photo.like_count} likes`}>
|
||||
<Heart className="w-3.5 h-3.5 text-red-500" fill="currentColor" />
|
||||
<span className="text-xs font-medium text-neutral-700">{photo.like_count}</span>
|
||||
</div>
|
||||
{photo.comment_count > 0 && (
|
||||
<span className="inline-flex items-center justify-center w-6 h-6 rounded-full bg-white/90 backdrop-blur-sm" title="Commented">
|
||||
<MessageSquare className="w-3.5 h-3.5 text-primary-600" fill="currentColor" />
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{photo.type === 'collage' && (
|
||||
<div className="absolute bottom-2 left-2">
|
||||
<div className="absolute bottom-2 right-2">
|
||||
<span className="px-2 py-1 bg-black/60 text-white text-xs rounded">
|
||||
Collage
|
||||
</span>
|
||||
@@ -156,6 +228,8 @@ export const GridGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
||||
photos,
|
||||
slug,
|
||||
onPhotoClick,
|
||||
onOpenPhotoWithFeedback,
|
||||
onFeedbackChange,
|
||||
onDownload,
|
||||
selectedPhotos = new Set(),
|
||||
isSelectionMode = false,
|
||||
@@ -163,7 +237,8 @@ export const GridGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
||||
allowDownloads = true,
|
||||
protectionLevel = 'standard',
|
||||
useEnhancedProtection = false,
|
||||
feedbackEnabled = false
|
||||
feedbackEnabled = false,
|
||||
feedbackOptions
|
||||
}) => {
|
||||
const { theme } = useTheme();
|
||||
const gallerySettings = theme.gallerySettings || {};
|
||||
@@ -171,6 +246,11 @@ export const GridGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
||||
const spacing = gallerySettings.spacing || 'normal';
|
||||
const animation = gallerySettings.photoAnimation || 'fade';
|
||||
|
||||
const [showIdentityModal, setShowIdentityModal] = React.useState(false);
|
||||
const [pendingAction, setPendingAction] = React.useState<null | { type: 'like'; photoId: number }>(null);
|
||||
const [likedPhotoIds, setLikedPhotoIds] = React.useState<Set<number>>(new Set());
|
||||
const [savedIdentity, setSavedIdentity] = React.useState<{ name: string; email: string } | null>(null);
|
||||
|
||||
const spacingClass = spacing === 'tight' ? 'gap-2' : spacing === 'relaxed' ? 'gap-6' : 'gap-4';
|
||||
|
||||
const gridClass = `grid ${spacingClass}
|
||||
@@ -187,13 +267,8 @@ export const GridGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
||||
photo={photo}
|
||||
isSelected={selectedPhotos.has(photo.id)}
|
||||
isSelectionMode={isSelectionMode}
|
||||
onClick={() => {
|
||||
if (isSelectionMode && onPhotoSelect) {
|
||||
onPhotoSelect(photo.id);
|
||||
} else {
|
||||
onPhotoClick(index);
|
||||
}
|
||||
}}
|
||||
onClick={() => onPhotoClick(index)}
|
||||
onToggleSelect={() => onPhotoSelect && onPhotoSelect(photo.id)}
|
||||
onDownload={(e) => onDownload(photo, e)}
|
||||
animationType={animation}
|
||||
allowDownloads={allowDownloads}
|
||||
@@ -201,8 +276,49 @@ export const GridGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
||||
protectionLevel={protectionLevel}
|
||||
useEnhancedProtection={useEnhancedProtection}
|
||||
feedbackEnabled={feedbackEnabled}
|
||||
feedbackOptions={feedbackOptions}
|
||||
savedIdentity={savedIdentity}
|
||||
onRequireIdentity={(action, photoId) => {
|
||||
setPendingAction({ type: action, photoId });
|
||||
setShowIdentityModal(true);
|
||||
}}
|
||||
onQuickComment={() => onOpenPhotoWithFeedback && onOpenPhotoWithFeedback(index)}
|
||||
onFeedbackChange={onFeedbackChange}
|
||||
liked={likedPhotoIds.has(photo.id)}
|
||||
onLikeSuccess={() => {
|
||||
setLikedPhotoIds((prev) => {
|
||||
const next = new Set(prev);
|
||||
next.add(photo.id);
|
||||
return next;
|
||||
});
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
<FeedbackIdentityModal
|
||||
isOpen={showIdentityModal}
|
||||
onClose={() => { setShowIdentityModal(false); setPendingAction(null); }}
|
||||
onSubmit={async (name, email) => {
|
||||
setSavedIdentity({ name, email });
|
||||
setShowIdentityModal(false);
|
||||
if (pendingAction) {
|
||||
await feedbackService.submitFeedback(slug, String(pendingAction.photoId), {
|
||||
feedback_type: pendingAction.type,
|
||||
guest_name: name,
|
||||
guest_email: email,
|
||||
});
|
||||
// Immediately reflect like UI
|
||||
if (pendingAction.type === 'like') {
|
||||
setLikedPhotoIds((prev) => {
|
||||
const next = new Set(prev);
|
||||
next.add(pendingAction.photoId);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
setPendingAction(null);
|
||||
}
|
||||
}}
|
||||
feedbackType="like"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
};
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { Download, Maximize2, Check, ChevronDown, Calendar, Clock } from 'lucide-react';
|
||||
import { Download, Maximize2, Check, ChevronDown, Calendar, Clock, Heart, MessageSquare } from 'lucide-react';
|
||||
import { parseISO } from 'date-fns';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useLocalizedDate } from '../../../hooks/useLocalizedDate';
|
||||
@@ -8,17 +8,23 @@ import { AuthenticatedImage } from '../../common';
|
||||
import type { BaseGalleryLayoutProps } from './BaseGalleryLayout';
|
||||
import type { Photo } from '../../../types';
|
||||
import { buildResourceUrl } from '../../../utils/url';
|
||||
import { FeedbackIdentityModal } from '../../gallery/FeedbackIdentityModal';
|
||||
import { feedbackService } from '../../../services/feedback.service';
|
||||
|
||||
interface HeroGalleryLayoutProps extends BaseGalleryLayoutProps {
|
||||
eventName?: string;
|
||||
eventLogo?: string | null;
|
||||
eventDate?: string;
|
||||
expiresAt?: string;
|
||||
// Use a static hero photo independent of current filter
|
||||
heroPhotoOverride?: Photo | null;
|
||||
}
|
||||
|
||||
export const HeroGalleryLayout: React.FC<HeroGalleryLayoutProps> = ({
|
||||
photos,
|
||||
slug,
|
||||
onPhotoClick,
|
||||
onOpenPhotoWithFeedback,
|
||||
onDownload,
|
||||
selectedPhotos = new Set(),
|
||||
isSelectionMode = false,
|
||||
@@ -27,15 +33,31 @@ export const HeroGalleryLayout: React.FC<HeroGalleryLayoutProps> = ({
|
||||
eventLogo,
|
||||
eventDate,
|
||||
expiresAt,
|
||||
allowDownloads = true
|
||||
heroPhotoOverride,
|
||||
allowDownloads = true,
|
||||
feedbackEnabled = false,
|
||||
feedbackOptions
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const { format } = useLocalizedDate();
|
||||
const { theme } = useTheme();
|
||||
const [heroPhoto, setHeroPhoto] = useState<Photo | null>(null);
|
||||
const [hasInitialized, setHasInitialized] = useState(false);
|
||||
const [showIdentityModal, setShowIdentityModal] = useState(false);
|
||||
const [pendingAction, setPendingAction] = useState<null | { type: 'like'; photoId: number }>(null);
|
||||
const [savedIdentity, setSavedIdentity] = useState<{ name: string; email: string } | null>(null);
|
||||
const gallerySettings = theme.gallerySettings || {};
|
||||
const overlayOpacity = gallerySettings.heroOverlayOpacity || 0.3;
|
||||
const [likedIds, setLikedIds] = useState<Set<number>>(new Set());
|
||||
const canQuickComment = Boolean(feedbackEnabled && feedbackOptions?.allowComments && onOpenPhotoWithFeedback);
|
||||
|
||||
// If an override is provided, always use it and skip initialization logic
|
||||
useEffect(() => {
|
||||
if (heroPhotoOverride) {
|
||||
setHeroPhoto(heroPhotoOverride);
|
||||
setHasInitialized(true);
|
||||
}
|
||||
}, [heroPhotoOverride]);
|
||||
|
||||
// Reset initialization when heroImageId changes
|
||||
useEffect(() => {
|
||||
@@ -46,29 +68,28 @@ export const HeroGalleryLayout: React.FC<HeroGalleryLayoutProps> = ({
|
||||
|
||||
// Select hero photo (admin-selected or first photo only if gallery was empty)
|
||||
useEffect(() => {
|
||||
// When an override is provided, the effect above has already set the hero.
|
||||
if (heroPhotoOverride) return;
|
||||
|
||||
if (photos.length > 0) {
|
||||
const heroId = gallerySettings.heroImageId;
|
||||
// Process hero layout with provided photos
|
||||
|
||||
// If admin has selected a specific hero image, always use it
|
||||
// If admin has selected a specific hero image, always use it when available
|
||||
if (heroId) {
|
||||
const adminSelectedHero = photos.find(p => p.id === heroId);
|
||||
// Hero photo selected by admin
|
||||
if (adminSelectedHero) {
|
||||
setHeroPhoto(adminSelectedHero);
|
||||
setHasInitialized(true);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Only auto-select first photo on initial load when gallery was empty
|
||||
// This prevents changing the hero when new photos are uploaded
|
||||
|
||||
// Only auto-select first photo on initial load
|
||||
if (!hasInitialized) {
|
||||
setHeroPhoto(photos[0]);
|
||||
setHasInitialized(true);
|
||||
}
|
||||
}
|
||||
}, [photos, gallerySettings.heroImageId, hasInitialized]);
|
||||
}, [photos, gallerySettings.heroImageId, hasInitialized, heroPhotoOverride]);
|
||||
|
||||
if (!heroPhoto) return null;
|
||||
|
||||
@@ -76,11 +97,13 @@ export const HeroGalleryLayout: React.FC<HeroGalleryLayoutProps> = ({
|
||||
const remainingPhotos = photos;
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="relative -mt-6">
|
||||
{/* Hero Section */}
|
||||
<div className="relative h-[60vh] sm:h-[70vh] lg:h-[80vh] -mx-4 sm:-mx-6 lg:-mx-8 mb-8">
|
||||
<AuthenticatedImage
|
||||
src={heroPhoto.url}
|
||||
fallbackSrc={heroPhoto.thumbnail_url || undefined}
|
||||
alt={heroPhoto.filename}
|
||||
className="w-full h-full object-cover"
|
||||
isGallery={true}
|
||||
@@ -152,13 +175,7 @@ export const HeroGalleryLayout: React.FC<HeroGalleryLayoutProps> = ({
|
||||
<div
|
||||
key={photo.id}
|
||||
className="relative group cursor-pointer aspect-square"
|
||||
onClick={() => {
|
||||
if (isSelectionMode && onPhotoSelect) {
|
||||
onPhotoSelect(photo.id);
|
||||
} else {
|
||||
onPhotoClick(actualIndex);
|
||||
}
|
||||
}}
|
||||
onClick={() => onPhotoClick(actualIndex)}
|
||||
>
|
||||
<AuthenticatedImage
|
||||
src={photo.thumbnail_url || photo.url}
|
||||
@@ -194,15 +211,81 @@ export const HeroGalleryLayout: React.FC<HeroGalleryLayoutProps> = ({
|
||||
<Download className="w-5 h-5 text-neutral-800" />
|
||||
</button>
|
||||
)}
|
||||
{feedbackOptions?.allowLikes && (
|
||||
<button
|
||||
className={`p-2 rounded-full transition-colors ${likedIds.has(photo.id) ? 'bg-red-500/90 hover:bg-red-500' : 'bg-white/90 hover:bg-white'}`}
|
||||
onClick={async (e) => {
|
||||
e.stopPropagation();
|
||||
if (feedbackOptions?.requireNameEmail && !savedIdentity) {
|
||||
setPendingAction({ type: 'like', photoId: photo.id });
|
||||
setShowIdentityModal(true);
|
||||
return;
|
||||
}
|
||||
setLikedIds(prev => new Set(prev).add(photo.id));
|
||||
try {
|
||||
await feedbackService.submitFeedback(slug!, String(photo.id), {
|
||||
feedback_type: 'like',
|
||||
guest_name: savedIdentity?.name,
|
||||
guest_email: savedIdentity?.email,
|
||||
});
|
||||
} catch (_) {}
|
||||
}}
|
||||
aria-label="Like photo"
|
||||
aria-pressed={likedIds.has(photo.id)}
|
||||
title="Like"
|
||||
>
|
||||
<Heart className={`w-5 h-5 ${likedIds.has(photo.id) ? 'text-white fill-white' : 'text-neutral-800'}`} />
|
||||
</button>
|
||||
)}
|
||||
{canQuickComment && (
|
||||
<button
|
||||
className="p-2 bg-white/90 rounded-full hover:bg-white transition-colors"
|
||||
onClick={(e) => { e.stopPropagation(); onOpenPhotoWithFeedback?.(actualIndex); }}
|
||||
aria-label="Comment on photo"
|
||||
title="Comment"
|
||||
>
|
||||
<MessageSquare className="w-5 h-5 text-neutral-800" />
|
||||
</button>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{isSelectionMode && (
|
||||
<div className={`absolute top-2 right-2 ${selectedPhotos.has(photo.id) ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'} transition-opacity`}>
|
||||
<div className={`w-6 h-6 rounded-full border-2 ${selectedPhotos.has(photo.id) ? 'bg-primary-600 border-primary-600' : 'bg-white/80 border-white'} flex items-center justify-center transition-colors`}>
|
||||
{selectedPhotos.has(photo.id) && <Check className="w-4 h-4 text-white" />}
|
||||
</div>
|
||||
{/* Selection Checkbox (visible on hover or when selected) */}
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`Select ${photo.filename}`}
|
||||
role="checkbox"
|
||||
aria-checked={selectedPhotos.has(photo.id)}
|
||||
data-testid={`gallery-photo-checkbox-${photo.id}`}
|
||||
className={`absolute top-2 right-2 z-20 transition-opacity ${
|
||||
selectedPhotos.has(photo.id) ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'
|
||||
}`}
|
||||
onClick={(e) => { e.stopPropagation(); onPhotoSelect && onPhotoSelect(photo.id); }}
|
||||
>
|
||||
<div className={`w-6 h-6 rounded-full border-2 ${selectedPhotos.has(photo.id) ? 'bg-primary-600 border-primary-600' : 'bg-white/90 border-white'} flex items-center justify-center transition-colors`}>
|
||||
{selectedPhotos.has(photo.id) && <Check className="w-4 h-4 text-white" />}
|
||||
</div>
|
||||
</button>
|
||||
|
||||
{/* Feedback indicators (always visible, bottom-left). Show like immediately when liked */}
|
||||
{(photo.like_count > 0 || likedIds.has(photo.id) || (photo.average_rating || 0) > 0 || (photo.comment_count || 0) > 0) && (
|
||||
<div className={`absolute ${photo.type === 'collage' ? 'bottom-8' : 'bottom-2'} left-2 flex items-center gap-1 z-20`}>
|
||||
{(photo.like_count > 0 || likedIds.has(photo.id)) && (
|
||||
<span className="inline-flex items-center justify-center w-6 h-6 rounded-full bg-white/90 backdrop-blur-sm" title="Liked">
|
||||
<Heart className="w-3.5 h-3.5 text-red-500" fill="currentColor" />
|
||||
</span>
|
||||
)}
|
||||
{(photo.average_rating || 0) > 0 && (
|
||||
<span className="inline-flex items-center justify-center w-6 h-6 rounded-full bg-white/90 backdrop-blur-sm" title="Rated">
|
||||
<svg viewBox="0 0 24 24" className="w-3.5 h-3.5 text-yellow-500 fill-current"><path d="M12 .587l3.668 7.431 8.2 1.193-5.934 5.787 1.402 8.168L12 18.897l-7.336 3.869 1.402-8.168L.132 9.211l8.2-1.193z"/></svg>
|
||||
</span>
|
||||
)}
|
||||
{(photo.comment_count || 0) > 0 && (
|
||||
<span className="inline-flex items-center justify-center w-6 h-6 rounded-full bg-white/90 backdrop-blur-sm" title="Commented">
|
||||
<svg viewBox="0 0 24 24" className="w-3.5 h-3.5 text-blue-600 fill-current"><path d="M20 2H4a2 2 0 00-2 2v18l4-4h14a2 2 0 002-2V4a2 2 0 00-2-2z"/></svg>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
@@ -210,5 +293,23 @@ export const HeroGalleryLayout: React.FC<HeroGalleryLayoutProps> = ({
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
<FeedbackIdentityModal
|
||||
isOpen={showIdentityModal}
|
||||
onClose={() => { setShowIdentityModal(false); setPendingAction(null); }}
|
||||
onSubmit={async (name, email) => {
|
||||
setSavedIdentity({ name, email });
|
||||
setShowIdentityModal(false);
|
||||
if (pendingAction) {
|
||||
await feedbackService.submitFeedback(slug!, String(pendingAction.photoId), {
|
||||
feedback_type: pendingAction.type,
|
||||
guest_name: name,
|
||||
guest_email: email,
|
||||
});
|
||||
setPendingAction(null);
|
||||
}
|
||||
}}
|
||||
feedbackType="like"
|
||||
/>
|
||||
</>
|
||||
);
|
||||
};
|
||||
};
|
||||
|
||||
@@ -2,6 +2,8 @@ import React, { useEffect, useRef, useState } from 'react';
|
||||
import { Download, Maximize2, Check, MessageSquare, Star, Heart } from 'lucide-react';
|
||||
import { useTheme } from '../../../contexts/ThemeContext';
|
||||
import { AuthenticatedImage } from '../../common';
|
||||
import { FeedbackIdentityModal } from '../../gallery/FeedbackIdentityModal';
|
||||
import { feedbackService } from '../../../services/feedback.service';
|
||||
import type { BaseGalleryLayoutProps } from './BaseGalleryLayout';
|
||||
import type { Photo } from '../../../types';
|
||||
|
||||
@@ -11,9 +13,17 @@ interface MasonryPhotoProps {
|
||||
isSelectionMode: boolean;
|
||||
onClick: (e: React.MouseEvent) => void;
|
||||
onDownload: (e: React.MouseEvent) => void;
|
||||
onToggleSelect: () => void;
|
||||
style?: React.CSSProperties;
|
||||
allowDownloads?: boolean;
|
||||
feedbackEnabled?: boolean;
|
||||
slug?: string;
|
||||
feedbackOptions?: {
|
||||
allowLikes?: boolean;
|
||||
allowComments?: boolean;
|
||||
requireNameEmail?: boolean;
|
||||
};
|
||||
onQuickComment?: () => void;
|
||||
}
|
||||
|
||||
const MasonryPhoto: React.FC<MasonryPhotoProps> = ({
|
||||
@@ -22,11 +32,18 @@ const MasonryPhoto: React.FC<MasonryPhotoProps> = ({
|
||||
isSelectionMode,
|
||||
onClick,
|
||||
onDownload,
|
||||
onToggleSelect,
|
||||
style,
|
||||
allowDownloads = true,
|
||||
feedbackEnabled = false
|
||||
feedbackEnabled = false,
|
||||
slug,
|
||||
feedbackOptions,
|
||||
onQuickComment
|
||||
}) => {
|
||||
const [imageHeight, setImageHeight] = useState<number>(200);
|
||||
const [showIdentityModal, setShowIdentityModal] = useState(false);
|
||||
const [pendingAction, setPendingAction] = useState<null | { type: 'like'; photoId: number }>(null);
|
||||
const [savedIdentity, setSavedIdentity] = useState<{ name: string; email: string } | null>(null);
|
||||
|
||||
// Generate random heights for masonry effect
|
||||
useEffect(() => {
|
||||
@@ -100,17 +117,77 @@ const MasonryPhoto: React.FC<MasonryPhotoProps> = ({
|
||||
<Download className="w-5 h-5 text-neutral-800" />
|
||||
</button>
|
||||
)}
|
||||
{onQuickComment && (
|
||||
<button
|
||||
className="p-2 bg-white/90 rounded-full hover:bg-white transition-colors"
|
||||
onClick={(e) => { e.stopPropagation(); onQuickComment(); }}
|
||||
aria-label="Comment on photo"
|
||||
title="Comment"
|
||||
>
|
||||
<MessageSquare className="w-5 h-5 text-neutral-800" />
|
||||
</button>
|
||||
)}
|
||||
{feedbackOptions?.allowLikes && (
|
||||
<button
|
||||
className="p-2 bg-white/90 rounded-full hover:bg-white transition-colors"
|
||||
onClick={async (e) => {
|
||||
e.stopPropagation();
|
||||
if (feedbackOptions?.requireNameEmail && !savedIdentity) {
|
||||
setPendingAction({ type: 'like', photoId: photo.id });
|
||||
setShowIdentityModal(true);
|
||||
return;
|
||||
}
|
||||
await feedbackService.submitFeedback(slug!, String(photo.id), {
|
||||
feedback_type: 'like',
|
||||
guest_name: savedIdentity?.name,
|
||||
guest_email: savedIdentity?.email,
|
||||
});
|
||||
}}
|
||||
aria-label="Like photo"
|
||||
title="Like"
|
||||
>
|
||||
<Heart className="w-5 h-5 text-neutral-800" />
|
||||
</button>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{isSelectionMode && (
|
||||
<div className={`absolute top-2 right-2 ${isSelected ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'} transition-opacity`}>
|
||||
<div className={`w-6 h-6 rounded-full border-2 ${isSelected ? 'bg-primary-600 border-primary-600' : 'bg-white/80 border-white'} flex items-center justify-center transition-colors`}>
|
||||
{isSelected && <Check className="w-4 h-4 text-white" />}
|
||||
</div>
|
||||
{/* Identity Modal */}
|
||||
<FeedbackIdentityModal
|
||||
isOpen={showIdentityModal}
|
||||
onClose={() => { setShowIdentityModal(false); setPendingAction(null); }}
|
||||
onSubmit={async (name, email) => {
|
||||
setSavedIdentity({ name, email });
|
||||
setShowIdentityModal(false);
|
||||
if (pendingAction) {
|
||||
await feedbackService.submitFeedback(slug!, String(pendingAction.photoId), {
|
||||
feedback_type: pendingAction.type,
|
||||
guest_name: name,
|
||||
guest_email: email,
|
||||
});
|
||||
setPendingAction(null);
|
||||
}
|
||||
}}
|
||||
feedbackType="like"
|
||||
/>
|
||||
|
||||
{/* Selection Checkbox (visible on hover or when selected) */}
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`Select ${photo.filename}`}
|
||||
role="checkbox"
|
||||
aria-checked={isSelected}
|
||||
data-testid={`gallery-photo-checkbox-${photo.id}`}
|
||||
className={`absolute top-2 right-2 z-20 transition-opacity ${
|
||||
isSelected ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'
|
||||
}`}
|
||||
onClick={(e) => { e.stopPropagation(); onToggleSelect(); }}
|
||||
>
|
||||
<div className={`w-6 h-6 rounded-full border-2 ${isSelected ? 'bg-primary-600 border-primary-600' : 'bg-white/90 border-white'} flex items-center justify-center transition-colors`}>
|
||||
{isSelected && <Check className="w-4 h-4 text-white" />}
|
||||
</div>
|
||||
)}
|
||||
</button>
|
||||
|
||||
{photo.type === 'collage' && (
|
||||
<div className="absolute bottom-2 left-2">
|
||||
@@ -125,13 +202,16 @@ const MasonryPhoto: React.FC<MasonryPhotoProps> = ({
|
||||
|
||||
export const MasonryGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
||||
photos,
|
||||
slug,
|
||||
onPhotoClick,
|
||||
onOpenPhotoWithFeedback,
|
||||
onDownload,
|
||||
selectedPhotos = new Set(),
|
||||
isSelectionMode = false,
|
||||
onPhotoSelect,
|
||||
allowDownloads = true,
|
||||
feedbackEnabled = false
|
||||
feedbackEnabled = false,
|
||||
feedbackOptions
|
||||
}) => {
|
||||
const { theme } = useTheme();
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
@@ -182,16 +262,14 @@ export const MasonryGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
||||
photo={photo}
|
||||
isSelected={selectedPhotos.has(photo.id)}
|
||||
isSelectionMode={isSelectionMode}
|
||||
onClick={() => {
|
||||
if (isSelectionMode && onPhotoSelect) {
|
||||
onPhotoSelect(photo.id);
|
||||
} else {
|
||||
onPhotoClick(originalIndex);
|
||||
}
|
||||
}}
|
||||
onClick={() => onPhotoClick(originalIndex)}
|
||||
onDownload={(e) => onDownload(photo, e)}
|
||||
onToggleSelect={() => onPhotoSelect && onPhotoSelect(photo.id)}
|
||||
allowDownloads={allowDownloads}
|
||||
feedbackEnabled={feedbackEnabled}
|
||||
slug={slug}
|
||||
feedbackOptions={feedbackOptions}
|
||||
onQuickComment={() => onOpenPhotoWithFeedback && onOpenPhotoWithFeedback(originalIndex)}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
@@ -199,4 +277,4 @@ export const MasonryGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
};
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import React from 'react';
|
||||
import { Download, Maximize2, Check } from 'lucide-react';
|
||||
import { Download, Maximize2, Check, Heart, MessageSquare } from 'lucide-react';
|
||||
// import { useTheme } from '../../../contexts/ThemeContext';
|
||||
import { AuthenticatedImage } from '../../common';
|
||||
import { FeedbackIdentityModal } from '../../gallery/FeedbackIdentityModal';
|
||||
import { feedbackService } from '../../../services/feedback.service';
|
||||
import type { BaseGalleryLayoutProps } from './BaseGalleryLayout';
|
||||
import type { Photo } from '../../../types';
|
||||
|
||||
@@ -11,8 +13,17 @@ interface MosaicPhotoProps {
|
||||
isSelectionMode: boolean;
|
||||
onClick: (e: React.MouseEvent) => void;
|
||||
onDownload: (e: React.MouseEvent) => void;
|
||||
onToggleSelect: () => void;
|
||||
className?: string;
|
||||
allowDownloads?: boolean;
|
||||
slug?: string;
|
||||
feedbackEnabled?: boolean;
|
||||
feedbackOptions?: {
|
||||
allowLikes?: boolean;
|
||||
allowComments?: boolean;
|
||||
requireNameEmail?: boolean;
|
||||
};
|
||||
onQuickComment?: () => void;
|
||||
}
|
||||
|
||||
const MosaicPhoto: React.FC<MosaicPhotoProps> = ({
|
||||
@@ -21,10 +32,22 @@ const MosaicPhoto: React.FC<MosaicPhotoProps> = ({
|
||||
isSelectionMode,
|
||||
onClick,
|
||||
onDownload,
|
||||
onToggleSelect,
|
||||
className = '',
|
||||
allowDownloads = true
|
||||
allowDownloads = true,
|
||||
slug,
|
||||
feedbackEnabled = false,
|
||||
feedbackOptions,
|
||||
onQuickComment
|
||||
}) => {
|
||||
const [showIdentityModal, setShowIdentityModal] = React.useState(false);
|
||||
const [pendingAction, setPendingAction] = React.useState<null | { type: 'like'; photoId: number }>(null);
|
||||
const [savedIdentity, setSavedIdentity] = React.useState<{ name: string; email: string } | null>(null);
|
||||
const [likedLocal, setLikedLocal] = React.useState(false);
|
||||
const canComment = Boolean(feedbackEnabled && feedbackOptions?.allowComments && onQuickComment);
|
||||
|
||||
return (
|
||||
<>
|
||||
<div
|
||||
className={`relative group cursor-pointer overflow-hidden rounded-lg bg-neutral-100 ${className}`}
|
||||
onClick={(e) => {
|
||||
@@ -65,18 +88,72 @@ const MosaicPhoto: React.FC<MosaicPhotoProps> = ({
|
||||
<Download className="w-5 h-5 text-neutral-800" />
|
||||
</button>
|
||||
)}
|
||||
{feedbackOptions?.allowLikes && (
|
||||
<button
|
||||
className={`p-2 rounded-full transition-colors ${likedLocal ? 'bg-red-500/90 hover:bg-red-500' : 'bg-white/90 hover:bg-white'}`}
|
||||
onClick={async (e) => {
|
||||
e.stopPropagation();
|
||||
if (feedbackOptions?.requireNameEmail && !savedIdentity) {
|
||||
setPendingAction({ type: 'like', photoId: photo.id });
|
||||
setShowIdentityModal(true);
|
||||
return;
|
||||
}
|
||||
setLikedLocal(true);
|
||||
try {
|
||||
await feedbackService.submitFeedback(slug!, String(photo.id), {
|
||||
feedback_type: 'like',
|
||||
guest_name: savedIdentity?.name,
|
||||
guest_email: savedIdentity?.email,
|
||||
});
|
||||
} catch (_) {}
|
||||
}}
|
||||
aria-label="Like photo"
|
||||
aria-pressed={likedLocal}
|
||||
title="Like"
|
||||
>
|
||||
<Heart className={`w-5 h-5 ${likedLocal ? 'text-white fill-white' : 'text-neutral-800'}`} />
|
||||
</button>
|
||||
)}
|
||||
{canComment && (
|
||||
<button
|
||||
className="p-2 bg-white/90 rounded-full hover:bg-white transition-colors"
|
||||
onClick={(e) => { e.stopPropagation(); onQuickComment?.(); }}
|
||||
aria-label="Comment on photo"
|
||||
title="Comment"
|
||||
>
|
||||
<MessageSquare className="w-5 h-5 text-neutral-800" />
|
||||
</button>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{isSelectionMode && (
|
||||
<div className={`absolute top-2 right-2 ${isSelected ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'} transition-opacity`}>
|
||||
<div className={`w-6 h-6 rounded-full border-2 ${isSelected ? 'bg-primary-600 border-primary-600' : 'bg-white/80 border-white'} flex items-center justify-center transition-colors`}>
|
||||
{isSelected && <Check className="w-4 h-4 text-white" />}
|
||||
</div>
|
||||
{/* Feedback Indicators (bottom-left) */}
|
||||
{(photo.like_count > 0 || likedLocal) && (
|
||||
<div className={`absolute ${photo.type === 'collage' ? 'bottom-8' : 'bottom-2'} left-2 z-10`}>
|
||||
<span className="inline-flex items-center justify-center w-6 h-6 rounded-full bg-white/90 backdrop-blur-sm" title="Liked">
|
||||
<Heart className="w-3.5 h-3.5 text-red-500" fill="currentColor" />
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Selection Checkbox (visible on hover or when selected) */}
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`Select ${photo.filename}`}
|
||||
role="checkbox"
|
||||
aria-checked={isSelected}
|
||||
data-testid={`gallery-photo-checkbox-${photo.id}`}
|
||||
className={`absolute top-2 right-2 z-20 transition-opacity ${
|
||||
isSelected ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'
|
||||
}`}
|
||||
onClick={(e) => { e.stopPropagation(); onToggleSelect(); }}
|
||||
>
|
||||
<div className={`w-6 h-6 rounded-full border-2 ${isSelected ? 'bg-primary-600 border-primary-600' : 'bg-white/90 border-white'} flex items-center justify-center transition-colors`}>
|
||||
{isSelected && <Check className="w-4 h-4 text-white" />}
|
||||
</div>
|
||||
</button>
|
||||
|
||||
{photo.type === 'collage' && (
|
||||
<div className="absolute bottom-2 left-2">
|
||||
<span className="px-2 py-1 bg-black/60 text-white text-xs rounded">
|
||||
@@ -85,17 +162,39 @@ const MosaicPhoto: React.FC<MosaicPhotoProps> = ({
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<FeedbackIdentityModal
|
||||
isOpen={showIdentityModal}
|
||||
onClose={() => { setShowIdentityModal(false); setPendingAction(null); }}
|
||||
onSubmit={async (name, email) => {
|
||||
setSavedIdentity({ name, email });
|
||||
setShowIdentityModal(false);
|
||||
if (pendingAction) {
|
||||
await feedbackService.submitFeedback(slug!, String(pendingAction.photoId), {
|
||||
feedback_type: pendingAction.type,
|
||||
guest_name: name,
|
||||
guest_email: email,
|
||||
});
|
||||
setPendingAction(null);
|
||||
}
|
||||
}}
|
||||
feedbackType="like"
|
||||
/>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export const MosaicGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
||||
photos,
|
||||
slug,
|
||||
onPhotoClick,
|
||||
onOpenPhotoWithFeedback,
|
||||
onDownload,
|
||||
selectedPhotos = new Set(),
|
||||
isSelectionMode = false,
|
||||
onPhotoSelect,
|
||||
allowDownloads = true
|
||||
allowDownloads = true,
|
||||
feedbackEnabled = false,
|
||||
feedbackOptions
|
||||
}) => {
|
||||
// const { theme } = useTheme();
|
||||
// const gallerySettings = theme.gallerySettings || {};
|
||||
@@ -136,10 +235,15 @@ export const MosaicGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
||||
photo={photo0}
|
||||
isSelected={selectedPhotos.has(photo0.id)}
|
||||
isSelectionMode={isSelectionMode}
|
||||
onClick={() => handlePhotoClick(idx0, photo0.id)}
|
||||
onClick={() => onPhotoClick(idx0)}
|
||||
onDownload={(e) => onDownload(photo0, e)}
|
||||
onToggleSelect={() => onPhotoSelect && onPhotoSelect(photo0.id)}
|
||||
className="col-span-1"
|
||||
allowDownloads={allowDownloads}
|
||||
slug={slug}
|
||||
feedbackEnabled={feedbackEnabled}
|
||||
feedbackOptions={feedbackOptions}
|
||||
onQuickComment={() => { if (typeof onOpenPhotoWithFeedback !== 'undefined' && onOpenPhotoWithFeedback) onOpenPhotoWithFeedback(idx0); }}
|
||||
/>
|
||||
)}
|
||||
<div className="grid grid-rows-2 gap-2">
|
||||
@@ -148,22 +252,32 @@ export const MosaicGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
||||
photo={photo1}
|
||||
isSelected={selectedPhotos.has(photo1.id)}
|
||||
isSelectionMode={isSelectionMode}
|
||||
onClick={() => handlePhotoClick(idx1, photo1.id)}
|
||||
onClick={() => onPhotoClick(idx1)}
|
||||
onDownload={(e) => onDownload(photo1, e)}
|
||||
onToggleSelect={() => onPhotoSelect && onPhotoSelect(photo1.id)}
|
||||
className=""
|
||||
allowDownloads={allowDownloads}
|
||||
/>
|
||||
slug={slug}
|
||||
feedbackEnabled={feedbackEnabled}
|
||||
feedbackOptions={feedbackOptions}
|
||||
onQuickComment={() => { if (typeof onOpenPhotoWithFeedback !== 'undefined' && onOpenPhotoWithFeedback) onOpenPhotoWithFeedback(idx1); }}
|
||||
/>
|
||||
)}
|
||||
{photo2 && (
|
||||
<MosaicPhoto
|
||||
photo={photo2}
|
||||
isSelected={selectedPhotos.has(photo2.id)}
|
||||
isSelectionMode={isSelectionMode}
|
||||
onClick={() => handlePhotoClick(idx2, photo2.id)}
|
||||
onClick={() => onPhotoClick(idx2)}
|
||||
onDownload={(e) => onDownload(photo2, e)}
|
||||
onToggleSelect={() => onPhotoSelect && onPhotoSelect(photo2.id)}
|
||||
className=""
|
||||
allowDownloads={allowDownloads}
|
||||
/>
|
||||
slug={slug}
|
||||
feedbackEnabled={feedbackEnabled}
|
||||
feedbackOptions={feedbackOptions}
|
||||
onQuickComment={() => { if (typeof onOpenPhotoWithFeedback !== 'undefined' && onOpenPhotoWithFeedback) onOpenPhotoWithFeedback(idx2); }}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
@@ -186,6 +300,10 @@ export const MosaicGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
||||
onDownload={(e) => onDownload(photo, e)}
|
||||
className=""
|
||||
allowDownloads={allowDownloads}
|
||||
slug={slug}
|
||||
feedbackEnabled={feedbackEnabled}
|
||||
feedbackOptions={feedbackOptions}
|
||||
onQuickComment={() => { if (typeof onOpenPhotoWithFeedback !== 'undefined' && onOpenPhotoWithFeedback) onOpenPhotoWithFeedback(currentIndex); }}
|
||||
/>
|
||||
) : null;
|
||||
})}
|
||||
@@ -209,10 +327,15 @@ export const MosaicGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
||||
photo={photo0}
|
||||
isSelected={selectedPhotos.has(photo0.id)}
|
||||
isSelectionMode={isSelectionMode}
|
||||
onClick={() => handlePhotoClick(idx0, photo0.id)}
|
||||
onClick={() => onPhotoClick(idx0)}
|
||||
onDownload={(e) => onDownload(photo0, e)}
|
||||
onToggleSelect={() => onPhotoSelect && onPhotoSelect(photo0.id)}
|
||||
className="col-span-2"
|
||||
allowDownloads={allowDownloads}
|
||||
slug={slug}
|
||||
feedbackEnabled={feedbackEnabled}
|
||||
feedbackOptions={feedbackOptions}
|
||||
onQuickComment={() => { if (typeof onOpenPhotoWithFeedback !== 'undefined' && onOpenPhotoWithFeedback) onOpenPhotoWithFeedback(idx0); }}
|
||||
/>
|
||||
)}
|
||||
<div className="grid grid-rows-2 gap-2">
|
||||
@@ -221,22 +344,32 @@ export const MosaicGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
||||
photo={photo1}
|
||||
isSelected={selectedPhotos.has(photo1.id)}
|
||||
isSelectionMode={isSelectionMode}
|
||||
onClick={() => handlePhotoClick(idx1, photo1.id)}
|
||||
onClick={() => onPhotoClick(idx1)}
|
||||
onDownload={(e) => onDownload(photo1, e)}
|
||||
onToggleSelect={() => onPhotoSelect && onPhotoSelect(photo1.id)}
|
||||
className=""
|
||||
allowDownloads={allowDownloads}
|
||||
/>
|
||||
slug={slug}
|
||||
feedbackEnabled={feedbackEnabled}
|
||||
feedbackOptions={feedbackOptions}
|
||||
onQuickComment={() => { if (typeof onOpenPhotoWithFeedback !== 'undefined' && onOpenPhotoWithFeedback) onOpenPhotoWithFeedback(idx1); }}
|
||||
/>
|
||||
)}
|
||||
{photo2 && (
|
||||
<MosaicPhoto
|
||||
photo={photo2}
|
||||
isSelected={selectedPhotos.has(photo2.id)}
|
||||
isSelectionMode={isSelectionMode}
|
||||
onClick={() => handlePhotoClick(idx2, photo2.id)}
|
||||
onClick={() => onPhotoClick(idx2)}
|
||||
onDownload={(e) => onDownload(photo2, e)}
|
||||
onToggleSelect={() => onPhotoSelect && onPhotoSelect(photo2.id)}
|
||||
className=""
|
||||
allowDownloads={allowDownloads}
|
||||
/>
|
||||
slug={slug}
|
||||
feedbackEnabled={feedbackEnabled}
|
||||
feedbackOptions={feedbackOptions}
|
||||
onQuickComment={() => { if (typeof onOpenPhotoWithFeedback !== 'undefined' && onOpenPhotoWithFeedback) onOpenPhotoWithFeedback(idx2); }}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
@@ -263,10 +396,15 @@ export const MosaicGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
||||
photo={photo}
|
||||
isSelected={selectedPhotos.has(photo.id)}
|
||||
isSelectionMode={isSelectionMode}
|
||||
onClick={() => handlePhotoClick(index, photo.id)}
|
||||
onClick={() => onPhotoClick(index)}
|
||||
onDownload={(e) => onDownload(photo, e)}
|
||||
onToggleSelect={() => onPhotoSelect && onPhotoSelect(photo.id)}
|
||||
className="aspect-square"
|
||||
allowDownloads={allowDownloads}
|
||||
slug={slug}
|
||||
feedbackEnabled={feedbackEnabled}
|
||||
feedbackOptions={feedbackOptions}
|
||||
onQuickComment={() => { if (typeof onOpenPhotoWithFeedback !== 'undefined' && onOpenPhotoWithFeedback) onOpenPhotoWithFeedback(index); }}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
@@ -282,4 +420,4 @@ export const MosaicGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
||||
{renderMosaicLayout()}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
};
|
||||
|
||||
@@ -1,24 +1,35 @@
|
||||
import React, { useMemo } from 'react';
|
||||
import { Download, Maximize2, Check, Calendar } from 'lucide-react';
|
||||
import React, { useMemo, useState } from 'react';
|
||||
import { Download, Maximize2, Check, Calendar, Heart, MessageSquare } from 'lucide-react';
|
||||
import { format, parseISO, startOfDay, startOfWeek, startOfMonth } from 'date-fns';
|
||||
import { useTheme } from '../../../contexts/ThemeContext';
|
||||
import { AuthenticatedImage } from '../../common';
|
||||
import type { BaseGalleryLayoutProps } from './BaseGalleryLayout';
|
||||
import type { Photo } from '../../../types';
|
||||
import { FeedbackIdentityModal } from '../../gallery/FeedbackIdentityModal';
|
||||
import { feedbackService } from '../../../services/feedback.service';
|
||||
|
||||
export const TimelineGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
||||
photos,
|
||||
slug,
|
||||
onPhotoClick,
|
||||
onOpenPhotoWithFeedback,
|
||||
onDownload,
|
||||
selectedPhotos = new Set(),
|
||||
isSelectionMode = false,
|
||||
onPhotoSelect,
|
||||
allowDownloads = true
|
||||
allowDownloads = true,
|
||||
feedbackEnabled = false,
|
||||
feedbackOptions
|
||||
}) => {
|
||||
const { theme } = useTheme();
|
||||
const [likedIds, setLikedIds] = useState<Set<number>>(new Set());
|
||||
const [showIdentityModal, setShowIdentityModal] = useState(false);
|
||||
const [pendingAction, setPendingAction] = useState<null | { type: 'like'; photoId: number }>(null);
|
||||
const [savedIdentity, setSavedIdentity] = useState<{ name: string; email: string } | null>(null);
|
||||
const gallerySettings = theme.gallerySettings || {};
|
||||
const grouping = gallerySettings.timelineGrouping || 'day';
|
||||
const showDates = gallerySettings.timelineShowDates !== false;
|
||||
const canQuickComment = Boolean(feedbackEnabled && feedbackOptions?.allowComments && onOpenPhotoWithFeedback);
|
||||
|
||||
// Group photos by date
|
||||
const groupedPhotos = useMemo(() => {
|
||||
@@ -90,13 +101,7 @@ export const TimelineGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
||||
<div
|
||||
key={photo.id}
|
||||
className="relative group cursor-pointer aspect-square"
|
||||
onClick={() => {
|
||||
if (isSelectionMode && onPhotoSelect) {
|
||||
onPhotoSelect(photo.id);
|
||||
} else {
|
||||
onPhotoClick(actualIndex);
|
||||
}
|
||||
}}
|
||||
onClick={() => onPhotoClick(actualIndex)}
|
||||
>
|
||||
<AuthenticatedImage
|
||||
src={photo.thumbnail_url || photo.url}
|
||||
@@ -137,17 +142,70 @@ export const TimelineGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
||||
<Download className="w-5 h-5 text-neutral-800" />
|
||||
</button>
|
||||
)}
|
||||
{feedbackOptions?.allowLikes && (
|
||||
<button
|
||||
className={`p-2 rounded-full transition-colors ${likedIds.has(photo.id) ? 'bg-red-500/90 hover:bg-red-500' : 'bg-white/90 hover:bg-white'}`}
|
||||
onClick={async (e) => {
|
||||
e.stopPropagation();
|
||||
if (feedbackOptions?.requireNameEmail && !savedIdentity) {
|
||||
setPendingAction({ type: 'like', photoId: photo.id });
|
||||
setShowIdentityModal(true);
|
||||
return;
|
||||
}
|
||||
setLikedIds(prev => new Set(prev).add(photo.id));
|
||||
try {
|
||||
await feedbackService.submitFeedback(slug!, String(photo.id), {
|
||||
feedback_type: 'like',
|
||||
guest_name: savedIdentity?.name,
|
||||
guest_email: savedIdentity?.email,
|
||||
});
|
||||
} catch (_) {}
|
||||
}}
|
||||
aria-label="Like photo"
|
||||
aria-pressed={likedIds.has(photo.id)}
|
||||
title="Like"
|
||||
>
|
||||
<Heart className={`w-5 h-5 ${likedIds.has(photo.id) ? 'text-white fill-white' : 'text-neutral-800'}`} />
|
||||
</button>
|
||||
)}
|
||||
{canQuickComment && (
|
||||
<button
|
||||
className="p-2 bg-white/90 rounded-full hover:bg-white transition-colors"
|
||||
onClick={(e) => { e.stopPropagation(); onOpenPhotoWithFeedback?.(actualIndex); }}
|
||||
aria-label="Comment on photo"
|
||||
title="Comment"
|
||||
>
|
||||
<MessageSquare className="w-5 h-5 text-neutral-800" />
|
||||
</button>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{isSelectionMode && (
|
||||
<div className={`absolute top-2 right-2 ${selectedPhotos.has(photo.id) ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'} transition-opacity`}>
|
||||
<div className={`w-6 h-6 rounded-full border-2 ${selectedPhotos.has(photo.id) ? 'bg-primary-600 border-primary-600' : 'bg-white/80 border-white'} flex items-center justify-center transition-colors`}>
|
||||
{selectedPhotos.has(photo.id) && <Check className="w-4 h-4 text-white" />}
|
||||
</div>
|
||||
{(photo.like_count > 0 || likedIds.has(photo.id)) && (
|
||||
<div className={`absolute ${photo.type === 'collage' ? 'bottom-8' : 'bottom-2'} left-2 z-10`}>
|
||||
<span className="inline-flex items-center justify-center w-6 h-6 rounded-full bg-white/90 backdrop-blur-sm" title="Liked">
|
||||
<Heart className="w-3.5 h-3.5 text-red-500" fill="currentColor" />
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Selection Checkbox (visible on hover or when selected) */}
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`Select ${photo.filename}`}
|
||||
role="checkbox"
|
||||
aria-checked={selectedPhotos.has(photo.id)}
|
||||
data-testid={`gallery-photo-checkbox-${photo.id}`}
|
||||
className={`absolute top-2 right-2 z-20 transition-opacity ${
|
||||
selectedPhotos.has(photo.id) ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'
|
||||
}`}
|
||||
onClick={(e) => { e.stopPropagation(); onPhotoSelect && onPhotoSelect(photo.id); }}
|
||||
>
|
||||
<div className={`w-6 h-6 rounded-full border-2 ${selectedPhotos.has(photo.id) ? 'bg-primary-600 border-primary-600' : 'bg-white/90 border-white'} flex items-center justify-center transition-colors`}>
|
||||
{selectedPhotos.has(photo.id) && <Check className="w-4 h-4 text-white" />}
|
||||
</div>
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
@@ -155,6 +213,23 @@ export const TimelineGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<FeedbackIdentityModal
|
||||
isOpen={showIdentityModal}
|
||||
onClose={() => { setShowIdentityModal(false); setPendingAction(null); }}
|
||||
onSubmit={async (name, email) => {
|
||||
setSavedIdentity({ name, email });
|
||||
setShowIdentityModal(false);
|
||||
if (pendingAction) {
|
||||
await feedbackService.submitFeedback(slug!, String(pendingAction.photoId), {
|
||||
feedback_type: pendingAction.type,
|
||||
guest_name: name,
|
||||
guest_email: email,
|
||||
});
|
||||
setPendingAction(null);
|
||||
}
|
||||
}}
|
||||
feedbackType="like"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
};
|
||||
|
||||
+5
-100
@@ -1,9 +1,4 @@
|
||||
import axios, { AxiosHeaders } from 'axios';
|
||||
import Cookies from 'js-cookie';
|
||||
|
||||
// Cookie keys
|
||||
export const ADMIN_TOKEN_KEY = 'admin_token';
|
||||
export const GALLERY_TOKEN_KEY = 'gallery_token';
|
||||
import axios from 'axios';
|
||||
|
||||
// Maintenance mode callback
|
||||
let maintenanceModeCallback: ((enabled: boolean) => void) | null = null;
|
||||
@@ -18,80 +13,12 @@ export const api = axios.create({
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
withCredentials: false, // Ensure we're not relying on cookies
|
||||
withCredentials: true,
|
||||
});
|
||||
|
||||
// Request interceptor to add auth token
|
||||
// Request interceptor: drop Content-Type for FormData payloads so the browser can set boundaries
|
||||
api.interceptors.request.use(
|
||||
(config) => {
|
||||
// Don't process if headers are already set by the component
|
||||
const existingAuth = config.headers?.['Authorization'] || config.headers?.get?.('Authorization');
|
||||
|
||||
// If authorization is already set by the component, don't override it
|
||||
if (existingAuth) {
|
||||
return config;
|
||||
}
|
||||
|
||||
// Check if it's an admin route or gallery route
|
||||
const isAdminRoute = config.url?.includes('/admin');
|
||||
|
||||
if (isAdminRoute) {
|
||||
const token = Cookies.get(ADMIN_TOKEN_KEY);
|
||||
if (token) {
|
||||
if (!config.headers) {
|
||||
config.headers = {};
|
||||
}
|
||||
config.headers['Authorization'] = `Bearer ${token}`;
|
||||
}
|
||||
} else {
|
||||
// For gallery routes, try to extract slug from the request URL first
|
||||
const galleryMatch = config.url?.match(/gallery\/([^\/]+)/);
|
||||
|
||||
if (galleryMatch && galleryMatch[1]) {
|
||||
const galleryIdOrSlug = galleryMatch[1];
|
||||
// Remove any query parameters from the slug
|
||||
const cleanIdOrSlug = galleryIdOrSlug.split('?')[0];
|
||||
|
||||
// Check if it's a numeric ID (for upload endpoints)
|
||||
let token = null;
|
||||
if (/^\d+$/.test(cleanIdOrSlug)) {
|
||||
// It's an event ID - try to find the token from current page slug
|
||||
const pathParts = window.location.pathname.split('/');
|
||||
if (pathParts[1] === 'gallery' && pathParts[2]) {
|
||||
const gallerySlug = pathParts[2];
|
||||
const cleanSlug = gallerySlug.split('?')[0];
|
||||
token = localStorage.getItem(`gallery_token_${cleanSlug}`);
|
||||
}
|
||||
} else {
|
||||
// It's a slug - use it directly
|
||||
token = localStorage.getItem(`gallery_token_${cleanIdOrSlug}`);
|
||||
}
|
||||
|
||||
if (token) {
|
||||
if (!config.headers) {
|
||||
config.headers = {};
|
||||
}
|
||||
config.headers['Authorization'] = `Bearer ${token}`;
|
||||
}
|
||||
} else {
|
||||
// Fallback to getting slug from the current page URL
|
||||
const pathParts = window.location.pathname.split('/');
|
||||
if (pathParts[1] === 'gallery' && pathParts[2]) {
|
||||
const gallerySlug = pathParts[2];
|
||||
// Remove any query parameters from the slug
|
||||
const cleanSlug = gallerySlug.split('?')[0];
|
||||
const token = localStorage.getItem(`gallery_token_${cleanSlug}`);
|
||||
if (token) {
|
||||
if (!config.headers) {
|
||||
config.headers = {};
|
||||
}
|
||||
config.headers['Authorization'] = `Bearer ${token}`;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Don't set Content-Type for FormData - let browser set it with boundary
|
||||
if (config.data instanceof FormData) {
|
||||
delete config.headers?.['Content-Type'];
|
||||
}
|
||||
@@ -110,10 +37,9 @@ api.interceptors.response.use(
|
||||
// Handle maintenance mode (503)
|
||||
if (error.response?.status === 503) {
|
||||
const isAdminRoute = error.config?.url?.includes('/admin');
|
||||
const hasAdminAuth = error.config?.headers?.Authorization?.startsWith('Bearer ');
|
||||
|
||||
// Only trigger maintenance mode for non-admin routes or unauthenticated admin routes
|
||||
if (!isAdminRoute || !hasAdminAuth) {
|
||||
if (!isAdminRoute) {
|
||||
if (maintenanceModeCallback) {
|
||||
maintenanceModeCallback(true);
|
||||
}
|
||||
@@ -126,8 +52,6 @@ api.interceptors.response.use(
|
||||
const currentPath = window.location.pathname;
|
||||
|
||||
if (isAdminRoute) {
|
||||
// Clear admin token on unauthorized
|
||||
Cookies.remove(ADMIN_TOKEN_KEY);
|
||||
// Only redirect if we're not already on the admin login page
|
||||
if (!currentPath.includes('/admin/login')) {
|
||||
window.location.href = '/admin/login';
|
||||
@@ -144,8 +68,7 @@ api.interceptors.response.use(
|
||||
// Don't clear tokens for image requests - they might just need a retry
|
||||
if (!isImageRequest && galleryMatch && galleryMatch[1]) {
|
||||
const gallerySlug = galleryMatch[1];
|
||||
localStorage.removeItem(`gallery_token_${gallerySlug}`);
|
||||
localStorage.removeItem(`gallery_event_${gallerySlug}`);
|
||||
sessionStorage.removeItem(`gallery_event_${gallerySlug}`);
|
||||
}
|
||||
// Don't redirect - let the component handle the auth state
|
||||
} else if (galleryMatch) {
|
||||
@@ -159,21 +82,3 @@ api.interceptors.response.use(
|
||||
return Promise.reject(error);
|
||||
}
|
||||
);
|
||||
|
||||
// Helper to set auth tokens
|
||||
export const setAuthToken = (token: string, isAdmin: boolean = false) => {
|
||||
const key = isAdmin ? ADMIN_TOKEN_KEY : GALLERY_TOKEN_KEY;
|
||||
Cookies.set(key, token, { expires: 1 }); // 1 day expiry
|
||||
};
|
||||
|
||||
// Helper to clear auth tokens
|
||||
export const clearAuthToken = (isAdmin: boolean = false) => {
|
||||
const key = isAdmin ? ADMIN_TOKEN_KEY : GALLERY_TOKEN_KEY;
|
||||
Cookies.remove(key);
|
||||
};
|
||||
|
||||
// Helper to get auth tokens
|
||||
export const getAuthToken = (isAdmin: boolean = false) => {
|
||||
const key = isAdmin ? ADMIN_TOKEN_KEY : GALLERY_TOKEN_KEY;
|
||||
return Cookies.get(key);
|
||||
};
|
||||
@@ -1,6 +1,6 @@
|
||||
import React, { createContext, useContext, useState, useEffect } from 'react';
|
||||
import type { ReactNode } from 'react';
|
||||
import { getAuthToken } from '../config/api';
|
||||
import { api } from '../config/api';
|
||||
import { authService } from '../services';
|
||||
import type { AdminUser } from '../types';
|
||||
|
||||
@@ -40,15 +40,31 @@ export const AdminAuthProvider: React.FC<AdminAuthProviderProps> = ({ children }
|
||||
// Check if user has a valid token on mount
|
||||
const checkAuth = async () => {
|
||||
try {
|
||||
const token = getAuthToken(true);
|
||||
if (token) {
|
||||
// For now, just assume the token is valid
|
||||
// TODO: Validate token with backend and get user info
|
||||
const storedUser = sessionStorage.getItem('admin_user');
|
||||
if (storedUser) {
|
||||
try {
|
||||
setUser(JSON.parse(storedUser));
|
||||
} catch (err) {
|
||||
sessionStorage.removeItem('admin_user');
|
||||
}
|
||||
}
|
||||
|
||||
const response = await api.get<{ valid: boolean; type: string; adminUsername?: string; user?: string }>(
|
||||
'/auth/session'
|
||||
);
|
||||
|
||||
if (response.data?.valid && response.data.type === 'admin') {
|
||||
setIsAuthenticated(true);
|
||||
} else {
|
||||
sessionStorage.removeItem('admin_user');
|
||||
setIsAuthenticated(false);
|
||||
setUser(null);
|
||||
}
|
||||
} catch (error) {
|
||||
// Auth check failed - user needs to login
|
||||
setError('Failed to check authentication');
|
||||
sessionStorage.removeItem('admin_user');
|
||||
setIsAuthenticated(false);
|
||||
setUser(null);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
@@ -63,9 +79,11 @@ export const AdminAuthProvider: React.FC<AdminAuthProviderProps> = ({ children }
|
||||
setError(null);
|
||||
setIsAuthenticated(true);
|
||||
setMustChangePassword(user.mustChangePassword || false);
|
||||
sessionStorage.setItem('admin_user', JSON.stringify(user));
|
||||
};
|
||||
|
||||
const logout = () => {
|
||||
sessionStorage.removeItem('admin_user');
|
||||
authService.adminLogout();
|
||||
setIsAuthenticated(false);
|
||||
setUser(null);
|
||||
@@ -79,6 +97,10 @@ export const AdminAuthProvider: React.FC<AdminAuthProviderProps> = ({ children }
|
||||
...user,
|
||||
mustChangePassword: false
|
||||
});
|
||||
sessionStorage.setItem('admin_user', JSON.stringify({
|
||||
...user,
|
||||
mustChangePassword: false
|
||||
}));
|
||||
}
|
||||
};
|
||||
|
||||
@@ -98,4 +120,4 @@ export const AdminAuthProvider: React.FC<AdminAuthProviderProps> = ({ children }
|
||||
{children}
|
||||
</AdminAuthContext.Provider>
|
||||
);
|
||||
};
|
||||
};
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import React, { createContext, useContext, useState, useEffect } from 'react';
|
||||
import type { ReactNode } from 'react';
|
||||
import { authService } from '../services';
|
||||
import { api } from '../config/api';
|
||||
import { authService, galleryService } from '../services';
|
||||
import { cleanupOldGalleryAuth } from '../utils/cleanupGalleryAuth';
|
||||
|
||||
interface GalleryEvent {
|
||||
@@ -52,36 +53,81 @@ export const GalleryAuthProvider: React.FC<GalleryAuthProviderProps> = ({ childr
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
// Clean up old authentication data on mount
|
||||
cleanupOldGalleryAuth();
|
||||
|
||||
// Check if user has a valid token on mount
|
||||
const currentSlug = getCurrentGallerySlug();
|
||||
if (currentSlug) {
|
||||
// Try to restore event data from localStorage with slug-specific key
|
||||
const storedEvent = localStorage.getItem(`gallery_event_${currentSlug}`);
|
||||
const storedToken = localStorage.getItem(`gallery_token_${currentSlug}`);
|
||||
|
||||
if (storedEvent && storedToken) {
|
||||
|
||||
const initialise = async () => {
|
||||
const currentSlug = getCurrentGallerySlug();
|
||||
|
||||
if (!currentSlug) {
|
||||
setIsLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const storedEvent = sessionStorage.getItem(`gallery_event_${currentSlug}`);
|
||||
if (storedEvent) {
|
||||
try {
|
||||
const eventData = JSON.parse(storedEvent);
|
||||
// Verify the stored event matches the current gallery slug
|
||||
if (eventData && eventData.id) {
|
||||
setEvent(eventData);
|
||||
setIsAuthenticated(true);
|
||||
} else {
|
||||
// Clear invalid data
|
||||
localStorage.removeItem(`gallery_event_${currentSlug}`);
|
||||
localStorage.removeItem(`gallery_token_${currentSlug}`);
|
||||
const parsed = JSON.parse(storedEvent);
|
||||
if (parsed && parsed.id) {
|
||||
setEvent(parsed);
|
||||
}
|
||||
} catch (error) {
|
||||
// Invalid stored data - clear it
|
||||
localStorage.removeItem(`gallery_event_${currentSlug}`);
|
||||
localStorage.removeItem(`gallery_token_${currentSlug}`);
|
||||
} catch (err) {
|
||||
sessionStorage.removeItem(`gallery_event_${currentSlug}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
setIsLoading(false);
|
||||
|
||||
try {
|
||||
setIsLoading(true);
|
||||
const sessionResponse = await api.get<{ valid: boolean; type: string; eventSlug?: string }>(
|
||||
'/auth/session',
|
||||
{ params: { slug: currentSlug } }
|
||||
);
|
||||
|
||||
if (sessionResponse.data?.valid && sessionResponse.data.type === 'gallery' && sessionResponse.data.eventSlug === currentSlug) {
|
||||
setIsAuthenticated(true);
|
||||
|
||||
if (!storedEvent) {
|
||||
// Fetch gallery details to hydrate context
|
||||
const galleryData = await galleryService.getGalleryPhotos(currentSlug);
|
||||
if (galleryData?.event) {
|
||||
setEvent(galleryData.event);
|
||||
sessionStorage.setItem(`gallery_event_${currentSlug}`, JSON.stringify(galleryData.event));
|
||||
}
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// If no active session, check for share token in URL
|
||||
const parts = window.location.pathname.split('/');
|
||||
const urlToken = parts.length >= 5 ? parts[4] : (parts.length >= 4 ? parts[3] : undefined);
|
||||
|
||||
if (urlToken) {
|
||||
const verify = await galleryService.verifyToken(currentSlug, urlToken);
|
||||
if (verify?.valid) {
|
||||
const response = await authService.shareLinkLogin(currentSlug, urlToken);
|
||||
if (response?.event) {
|
||||
setEvent(response.event);
|
||||
setIsAuthenticated(true);
|
||||
sessionStorage.setItem(`gallery_event_${currentSlug}`, JSON.stringify(response.event));
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// No valid session found
|
||||
setIsAuthenticated(false);
|
||||
sessionStorage.removeItem(`gallery_event_${currentSlug}`);
|
||||
setEvent(null);
|
||||
} catch (error) {
|
||||
setIsAuthenticated(false);
|
||||
sessionStorage.removeItem(`gallery_event_${currentSlug}`);
|
||||
setEvent(null);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
initialise();
|
||||
}, []);
|
||||
|
||||
const login = async (slug: string, password: string, recaptchaToken?: string | null) => {
|
||||
@@ -92,9 +138,8 @@ export const GalleryAuthProvider: React.FC<GalleryAuthProviderProps> = ({ childr
|
||||
setEvent(response.event);
|
||||
setIsAuthenticated(true);
|
||||
|
||||
// Store event data and token in localStorage with slug-specific key
|
||||
localStorage.setItem(`gallery_event_${slug}`, JSON.stringify(response.event));
|
||||
localStorage.setItem(`gallery_token_${slug}`, response.token);
|
||||
// Store event data for quick reloads (non-sensitive)
|
||||
sessionStorage.setItem(`gallery_event_${slug}`, JSON.stringify(response.event));
|
||||
} catch (err: any) {
|
||||
setError(err.response?.data?.error || 'Invalid password');
|
||||
throw err;
|
||||
@@ -106,13 +151,13 @@ export const GalleryAuthProvider: React.FC<GalleryAuthProviderProps> = ({ childr
|
||||
const logout = () => {
|
||||
const currentSlug = getCurrentGallerySlug();
|
||||
if (currentSlug) {
|
||||
localStorage.removeItem(`gallery_event_${currentSlug}`);
|
||||
localStorage.removeItem(`gallery_token_${currentSlug}`);
|
||||
sessionStorage.removeItem(`gallery_event_${currentSlug}`);
|
||||
}
|
||||
authService.galleryLogout();
|
||||
authService.galleryLogout(currentSlug || undefined);
|
||||
setIsAuthenticated(false);
|
||||
setEvent(null);
|
||||
};
|
||||
}
|
||||
;
|
||||
|
||||
return (
|
||||
<GalleryAuthContext.Provider
|
||||
@@ -128,4 +173,4 @@ export const GalleryAuthProvider: React.FC<GalleryAuthProviderProps> = ({ childr
|
||||
{children}
|
||||
</GalleryAuthContext.Provider>
|
||||
);
|
||||
};
|
||||
};
|
||||
|
||||
@@ -11,9 +11,15 @@ export const useGalleryInfo = (slug: string, token?: string) => {
|
||||
});
|
||||
};
|
||||
|
||||
export const useGalleryPhotos = (slug: string, filter?: 'liked' | 'favorited' | 'all', guestId?: string, enabled: boolean = true) => {
|
||||
export const useGalleryPhotos = (
|
||||
slug: string,
|
||||
filter?: 'liked' | 'commented' | 'rated' | 'all',
|
||||
guestId?: string,
|
||||
enabled: boolean = true
|
||||
) => {
|
||||
return useQuery({
|
||||
queryKey: ['gallery-photos', slug, filter, guestId],
|
||||
// Pass guestId so backend can filter per-guest views when needed
|
||||
queryFn: () => galleryService.getGalleryPhotos(slug, filter, guestId),
|
||||
enabled,
|
||||
retry: 1,
|
||||
@@ -63,4 +69,4 @@ export const useDownloadAllPhotos = () => {
|
||||
toast.error('Failed to download photos');
|
||||
},
|
||||
});
|
||||
};
|
||||
};
|
||||
|
||||
@@ -1079,6 +1079,24 @@
|
||||
"bulk_download": "{{count}} Fotos heruntergeladen von {{eventName}}",
|
||||
"gallery_password_entry": "Passwort eingegeben für {{eventName}}",
|
||||
"expiration_warning_viewed": "Ablaufwarnung angesehen für {{eventName}}",
|
||||
"feedback_settings_updated": "Feedback-Einstellungen aktualisiert",
|
||||
"feedback_moderated": "Feedback moderiert",
|
||||
"feedback_deleted": "Feedback gelöscht",
|
||||
"photo_like": "Foto mit Gefällt mir markiert in {{eventName}}",
|
||||
"photo_favorite": "Foto favorisiert in {{eventName}}",
|
||||
"photo_rating": "Foto bewertet in {{eventName}}",
|
||||
"photo_comment": "Foto kommentiert in {{eventName}}",
|
||||
"guest_feedback_like": "Gast hat ein Foto mit Gefällt mir markiert in {{eventName}}",
|
||||
"guest_feedback_favorite": "Gast hat ein Foto favorisiert in {{eventName}}",
|
||||
"guest_feedback_rating": "Gast hat ein Foto bewertet in {{eventName}}",
|
||||
"guest_feedback_comment": "Gast hat ein Foto kommentiert in {{eventName}}",
|
||||
"word_filter_added": "Wortfilter hinzugefügt",
|
||||
"external_import_completed": "Externer Medienimport abgeschlossen ({{imported}} importiert, {{skipped}} übersprungen)",
|
||||
"bulk_archive_completed": "Sammelarchivierung abgeschlossen",
|
||||
"event_activated": "Veranstaltung aktiviert: {{eventName}}",
|
||||
"event_deactivated": "Veranstaltung deaktiviert: {{eventName}}",
|
||||
"photo_deleted": "Foto gelöscht aus {{eventName}}",
|
||||
"photos_bulk_deleted": "{{count}} Fotos gelöscht aus {{eventName}}",
|
||||
"settings_updated": "Einstellungen aktualisiert",
|
||||
"event_updated": "Veranstaltung aktualisiert: {{eventName}}",
|
||||
"event_deleted": "Veranstaltung gelöscht: {{eventName}}",
|
||||
|
||||
@@ -821,6 +821,24 @@
|
||||
"bulk_download": "{{count}} photos downloaded from {{eventName}}",
|
||||
"gallery_password_entry": "Password entered for {{eventName}}",
|
||||
"expiration_warning_viewed": "Expiration warning viewed for {{eventName}}",
|
||||
"feedback_settings_updated": "Feedback settings updated",
|
||||
"feedback_moderated": "Feedback moderated",
|
||||
"feedback_deleted": "Feedback deleted",
|
||||
"photo_like": "Photo liked in {{eventName}}",
|
||||
"photo_favorite": "Photo favorited in {{eventName}}",
|
||||
"photo_rating": "Photo rated in {{eventName}}",
|
||||
"photo_comment": "Photo commented in {{eventName}}",
|
||||
"guest_feedback_like": "Guest liked a photo in {{eventName}}",
|
||||
"guest_feedback_favorite": "Guest favorited a photo in {{eventName}}",
|
||||
"guest_feedback_rating": "Guest rated a photo in {{eventName}}",
|
||||
"guest_feedback_comment": "Guest commented on a photo in {{eventName}}",
|
||||
"word_filter_added": "Word filter added",
|
||||
"external_import_completed": "External media import completed ({{imported}} imported, {{skipped}} skipped)",
|
||||
"bulk_archive_completed": "Bulk archive completed",
|
||||
"event_activated": "Event activated: {{eventName}}",
|
||||
"event_deactivated": "Event deactivated: {{eventName}}",
|
||||
"photo_deleted": "Photo deleted from {{eventName}}",
|
||||
"photos_bulk_deleted": "{{count}} photos deleted from {{eventName}}",
|
||||
"settings_updated": "Settings updated",
|
||||
"event_updated": "Event updated: {{eventName}}",
|
||||
"event_deleted": "Event deleted: {{eventName}}",
|
||||
|
||||
@@ -268,13 +268,13 @@ export const AdminDashboard: React.FC = () => {
|
||||
categoryName: activity.metadata?.category_name || ''
|
||||
};
|
||||
|
||||
// Check if translation exists
|
||||
const translated = t(translationKey, params);
|
||||
if (typeof translated === 'string') {
|
||||
return translated;
|
||||
// Translate; if key missing i18n returns the key string itself
|
||||
const translated = t(translationKey, params) as string;
|
||||
if (!translated || translated === translationKey) {
|
||||
// Fallback: format a readable English message
|
||||
return adminService.formatActivityMessage(activity);
|
||||
}
|
||||
// Fallback to unknown activity if translation not found
|
||||
return t('admin.activities.unknown') as string;
|
||||
return translated;
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -302,4 +302,4 @@ export const AdminDashboard: React.FC = () => {
|
||||
);
|
||||
};
|
||||
|
||||
AdminDashboard.displayName = 'AdminDashboard';
|
||||
AdminDashboard.displayName = 'AdminDashboard';
|
||||
|
||||
@@ -8,7 +8,7 @@ import { useTranslation } from 'react-i18next';
|
||||
import { Button, Input, Card, ReCaptcha } from '../../components/common';
|
||||
import { useAdminAuth } from '../../contexts';
|
||||
import { authService } from '../../services/auth.service';
|
||||
import { getAuthToken, api } from '../../config/api';
|
||||
import { api } from '../../config/api';
|
||||
|
||||
export const AdminLoginPage: React.FC = () => {
|
||||
const { t } = useTranslation();
|
||||
@@ -84,17 +84,20 @@ export const AdminLoginPage: React.FC = () => {
|
||||
login(response.token, response.user);
|
||||
toast.success(t('adminLogin.loginSuccess'));
|
||||
setLoginSuccess(true);
|
||||
} catch (error: any) {
|
||||
// Login error handled by UI notification
|
||||
|
||||
// Handle network errors gracefully
|
||||
if (error.code === 'ERR_NETWORK' || error.code === 'ERR_CONNECTION_RESET') {
|
||||
} catch (error: any) {
|
||||
// Login error handled by UI notification
|
||||
|
||||
// Handle network errors gracefully
|
||||
if (error.code === 'ERR_NETWORK' || error.code === 'ERR_CONNECTION_RESET') {
|
||||
// Check if we actually got logged in despite the error
|
||||
const token = getAuthToken(true);
|
||||
if (token) {
|
||||
// Login was successful, just had a connection issue
|
||||
setLoginSuccess(true);
|
||||
return;
|
||||
try {
|
||||
const sessionResponse = await api.get<{ valid: boolean; type: string }>('/auth/session');
|
||||
if (sessionResponse.data?.valid && sessionResponse.data.type === 'admin') {
|
||||
setLoginSuccess(true);
|
||||
return;
|
||||
}
|
||||
} catch (sessionError) {
|
||||
// Ignore secondary failure, we'll surface the original network error
|
||||
}
|
||||
toast.error(t('adminLogin.networkError'));
|
||||
} else if (error.response?.status === 429) {
|
||||
@@ -259,4 +262,4 @@ export const AdminLoginPage: React.FC = () => {
|
||||
);
|
||||
};
|
||||
|
||||
AdminLoginPage.displayName = 'AdminLoginPage';
|
||||
AdminLoginPage.displayName = 'AdminLoginPage';
|
||||
|
||||
@@ -17,7 +17,7 @@ import {
|
||||
Trash2
|
||||
} from 'lucide-react';
|
||||
import { toast } from 'react-toastify';
|
||||
import { format } from 'date-fns';
|
||||
import { format, parseISO } from 'date-fns';
|
||||
|
||||
import { Button, Card, Loading } from '../../components/common';
|
||||
import { AdminAuthenticatedImage } from '../../components/admin/AdminAuthenticatedImage';
|
||||
@@ -254,7 +254,7 @@ export const EventFeedbackPage: React.FC = () => {
|
||||
{item.photo_id && (
|
||||
<div className="w-16 h-16 overflow-hidden rounded">
|
||||
<AdminAuthenticatedImage
|
||||
src={`/api/admin/photos/${eventId}/thumbnail/${item.photo_id}`}
|
||||
src={`/admin/photos/${id}/thumbnail/${item.photo_id}`}
|
||||
alt={item.filename || 'Photo'}
|
||||
className="w-16 h-16 object-cover rounded"
|
||||
/>
|
||||
@@ -290,7 +290,12 @@ export const EventFeedbackPage: React.FC = () => {
|
||||
<p className="text-sm text-neutral-700">{item.comment_text}</p>
|
||||
)}
|
||||
<p className="text-xs text-neutral-500 mt-1">
|
||||
{format(new Date(item.created_at), 'PPpp')}
|
||||
{(() => {
|
||||
const d = typeof item.created_at === 'string'
|
||||
? parseISO(item.created_at)
|
||||
: new Date(item.created_at);
|
||||
return isNaN(d.getTime()) ? t('common.unknownDate', 'Unknown date') : format(d, 'PPpp');
|
||||
})()}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
@@ -492,7 +497,12 @@ export const EventFeedbackPage: React.FC = () => {
|
||||
<p className="text-sm text-neutral-700">{comment.comment_text}</p>
|
||||
<p className="text-xs text-neutral-500 mt-1">
|
||||
{comment.guest_name} • {comment.filename} •
|
||||
{format(new Date(comment.created_at), 'PP')}
|
||||
{(() => {
|
||||
const d = typeof comment.created_at === 'string'
|
||||
? parseISO(comment.created_at)
|
||||
: new Date(comment.created_at);
|
||||
return isNaN(d.getTime()) ? t('common.unknownDate', 'Unknown date') : format(d, 'PP');
|
||||
})()}
|
||||
</p>
|
||||
</div>
|
||||
))}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { api, setAuthToken, clearAuthToken } from '../config/api';
|
||||
import { api } from '../config/api';
|
||||
import type { LoginResponse, GalleryAuthResponse } from '../types';
|
||||
|
||||
export const authService = {
|
||||
@@ -10,14 +10,17 @@ export const authService = {
|
||||
password: credentials.password,
|
||||
recaptchaToken: credentials.recaptchaToken
|
||||
});
|
||||
|
||||
setAuthToken(response.data.token, true);
|
||||
return response.data;
|
||||
},
|
||||
|
||||
adminLogout() {
|
||||
clearAuthToken(true);
|
||||
window.location.href = '/admin/login';
|
||||
async adminLogout() {
|
||||
try {
|
||||
await api.post('/auth/logout');
|
||||
} catch (err) {
|
||||
// Ignore logout errors; fallback to redirect
|
||||
} finally {
|
||||
window.location.href = '/admin/login';
|
||||
}
|
||||
},
|
||||
|
||||
// Gallery authentication
|
||||
@@ -32,7 +35,19 @@ export const authService = {
|
||||
return response.data;
|
||||
},
|
||||
|
||||
galleryLogout() {
|
||||
// Logout is now handled by GalleryAuthContext
|
||||
async shareLinkLogin(slug: string, token: string): Promise<GalleryAuthResponse> {
|
||||
const response = await api.post<GalleryAuthResponse>('/auth/gallery/share-login', {
|
||||
slug,
|
||||
token,
|
||||
});
|
||||
return response.data;
|
||||
},
|
||||
};
|
||||
|
||||
async galleryLogout(slug?: string | null) {
|
||||
try {
|
||||
await api.post('/auth/gallery/logout', { slug });
|
||||
} catch (err) {
|
||||
// Ignore; cookie will naturally expire if removal fails
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
@@ -16,7 +16,11 @@ export const galleryService = {
|
||||
},
|
||||
|
||||
// Get gallery photos (requires auth)
|
||||
async getGalleryPhotos(slug: string, filter?: 'liked' | 'favorited' | 'all', guestId?: string): Promise<GalleryData> {
|
||||
async getGalleryPhotos(
|
||||
slug: string,
|
||||
filter?: 'liked' | 'commented' | 'rated' | 'all',
|
||||
guestId?: string
|
||||
): Promise<GalleryData> {
|
||||
const params: any = {};
|
||||
if (filter && filter !== 'all' && guestId) {
|
||||
params.filter = filter;
|
||||
@@ -28,19 +32,36 @@ export const galleryService = {
|
||||
|
||||
// Download single photo
|
||||
async downloadPhoto(slug: string, photoId: number, filename: string): Promise<void> {
|
||||
const response = await api.get(`/gallery/${slug}/download/${photoId}`, {
|
||||
responseType: 'blob',
|
||||
});
|
||||
|
||||
// Create download link
|
||||
const url = window.URL.createObjectURL(new Blob([response.data]));
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.setAttribute('download', filename);
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
link.remove();
|
||||
window.URL.revokeObjectURL(url);
|
||||
try {
|
||||
const response = await api.get(`/gallery/${slug}/download/${photoId}`, {
|
||||
responseType: 'blob',
|
||||
});
|
||||
const url = window.URL.createObjectURL(new Blob([response.data]));
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.setAttribute('download', filename);
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
link.remove();
|
||||
window.URL.revokeObjectURL(url);
|
||||
} catch (err) {
|
||||
// Fallback: use the view endpoint if direct download fails (e.g., missing original)
|
||||
try {
|
||||
const response = await api.get(`/gallery/${slug}/photo/${photoId}`, {
|
||||
responseType: 'blob',
|
||||
});
|
||||
const url = window.URL.createObjectURL(new Blob([response.data]));
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.setAttribute('download', filename);
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
link.remove();
|
||||
window.URL.revokeObjectURL(url);
|
||||
} catch (fallbackErr) {
|
||||
throw fallbackErr;
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
// Download all photos as ZIP
|
||||
@@ -60,9 +81,25 @@ export const galleryService = {
|
||||
window.URL.revokeObjectURL(url);
|
||||
},
|
||||
|
||||
// Download selected photos as ZIP
|
||||
async downloadSelectedPhotos(slug: string, photoIds: number[]): Promise<void> {
|
||||
const response = await api.post(`/gallery/${slug}/download-selected`, { photo_ids: photoIds }, {
|
||||
responseType: 'blob',
|
||||
});
|
||||
|
||||
const url = window.URL.createObjectURL(new Blob([response.data]));
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.setAttribute('download', `${slug}-selected.zip`);
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
link.remove();
|
||||
window.URL.revokeObjectURL(url);
|
||||
},
|
||||
|
||||
// Get gallery statistics
|
||||
async getGalleryStats(slug: string): Promise<GalleryStats> {
|
||||
const response = await api.get<GalleryStats>(`/gallery/${slug}/stats`);
|
||||
return response.data;
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
@@ -49,21 +49,10 @@ class SecureTokenService {
|
||||
}
|
||||
|
||||
try {
|
||||
// Get the gallery token from localStorage
|
||||
const galleryToken = localStorage.getItem(`gallery_token_${slug}`);
|
||||
if (!galleryToken) {
|
||||
throw new Error('No gallery authentication token found');
|
||||
}
|
||||
|
||||
// Generate new token from backend with explicit auth header
|
||||
// Generate new token from backend – authentication handled via cookies
|
||||
const response = await api.post<SecureToken>(
|
||||
`/secure-images/${slug}/generate-token`,
|
||||
{ photoId, accessType },
|
||||
{
|
||||
headers: {
|
||||
'Authorization': `Bearer ${galleryToken}`
|
||||
}
|
||||
}
|
||||
{ photoId, accessType }
|
||||
);
|
||||
|
||||
const tokenData: SecureToken = {
|
||||
@@ -190,4 +179,4 @@ if (typeof window !== 'undefined') {
|
||||
setInterval(() => {
|
||||
secureTokenService.clearExpiredTokens();
|
||||
}, 5 * 60 * 1000);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,18 +9,12 @@ export const cleanupOldGalleryAuth = () => {
|
||||
for (let i = 0; i < localStorage.length; i++) {
|
||||
const key = localStorage.key(i);
|
||||
if (key && (key.startsWith('gallery_token') || key.startsWith('gallery_event'))) {
|
||||
// Check if it's an old format token that might be corrupted
|
||||
const value = localStorage.getItem(key);
|
||||
if (value && (value.length < 100 || !value.includes('.'))) {
|
||||
// Token is too short or doesn't contain dots (not a valid JWT)
|
||||
keysToRemove.push(key);
|
||||
}
|
||||
keysToRemove.push(key);
|
||||
}
|
||||
}
|
||||
|
||||
keysToRemove.forEach(key => {
|
||||
localStorage.removeItem(key);
|
||||
// Silently remove corrupted tokens
|
||||
});
|
||||
|
||||
// Remove old gallery token from cookies if it exists
|
||||
@@ -29,4 +23,4 @@ export const cleanupOldGalleryAuth = () => {
|
||||
// Also clear session storage
|
||||
sessionStorage.removeItem('gallery_event');
|
||||
sessionStorage.removeItem('gallery_token');
|
||||
};
|
||||
};
|
||||
|
||||
Generated
+64
@@ -10,6 +10,7 @@
|
||||
"node-fetch": "^2.7.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@playwright/test": "^1.48.2",
|
||||
"puppeteer": "^24.17.0"
|
||||
}
|
||||
},
|
||||
@@ -38,6 +39,22 @@
|
||||
"node": ">=6.9.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@playwright/test": {
|
||||
"version": "1.55.0",
|
||||
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.55.0.tgz",
|
||||
"integrity": "sha512-04IXzPwHrW69XusN/SIdDdKZBzMfOT9UNT/YiJit/xpy2VuAoB8NHc8Aplb96zsWDddLnbkPL3TsmrS04ZU2xQ==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"playwright": "1.55.0"
|
||||
},
|
||||
"bin": {
|
||||
"playwright": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@puppeteer/browsers": {
|
||||
"version": "2.10.7",
|
||||
"resolved": "https://registry.npmjs.org/@puppeteer/browsers/-/browsers-2.10.7.tgz",
|
||||
@@ -704,6 +721,21 @@
|
||||
"integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/fsevents": {
|
||||
"version": "2.3.2",
|
||||
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",
|
||||
"integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",
|
||||
"dev": true,
|
||||
"hasInstallScript": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"engines": {
|
||||
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/get-caller-file": {
|
||||
"version": "2.0.5",
|
||||
"resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz",
|
||||
@@ -1083,6 +1115,38 @@
|
||||
"dev": true,
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/playwright": {
|
||||
"version": "1.55.0",
|
||||
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.55.0.tgz",
|
||||
"integrity": "sha512-sdCWStblvV1YU909Xqx0DhOjPZE4/5lJsIS84IfN9dAZfcl/CIZ5O8l3o0j7hPMjDvqoTF8ZUcc+i/GL5erstA==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"playwright-core": "1.55.0"
|
||||
},
|
||||
"bin": {
|
||||
"playwright": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"fsevents": "2.3.2"
|
||||
}
|
||||
},
|
||||
"node_modules/playwright-core": {
|
||||
"version": "1.55.0",
|
||||
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.55.0.tgz",
|
||||
"integrity": "sha512-GvZs4vU3U5ro2nZpeiwyb0zuFaqb9sUiAJuyrWpcGouD8y9/HLgGbNRjIph7zU9D3hnPaisMl9zG9CgFi/biIg==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"bin": {
|
||||
"playwright-core": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/prebuild-install": {
|
||||
"version": "7.1.3",
|
||||
"resolved": "https://registry.npmjs.org/prebuild-install/-/prebuild-install-7.1.3.tgz",
|
||||
|
||||
+5
-1
@@ -1,10 +1,14 @@
|
||||
{
|
||||
"scripts": {
|
||||
"test:e2e": "playwright test"
|
||||
},
|
||||
"dependencies": {
|
||||
"better-sqlite3": "^12.2.0",
|
||||
"canvas": "^3.2.0",
|
||||
"node-fetch": "^2.7.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"puppeteer": "^24.17.0"
|
||||
"puppeteer": "^24.17.0",
|
||||
"@playwright/test": "^1.48.2"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import { defineConfig, devices } from '@playwright/test';
|
||||
|
||||
export default defineConfig({
|
||||
testDir: 'tests/e2e',
|
||||
timeout: 60_000,
|
||||
retries: 0,
|
||||
use: {
|
||||
baseURL: 'http://localhost:3000',
|
||||
headless: true,
|
||||
viewport: { width: 1280, height: 800 },
|
||||
ignoreHTTPSErrors: true,
|
||||
},
|
||||
projects: [
|
||||
{ name: 'chromium', use: { ...devices['Desktop Chrome'] } },
|
||||
{ name: 'mobile-chrome', use: { ...devices['Pixel 5'] } },
|
||||
],
|
||||
});
|
||||
|
||||
+119
-29
@@ -44,7 +44,6 @@ INSTALL_METHOD="" # docker or native
|
||||
OS_TYPE=""
|
||||
OS_VERSION=""
|
||||
PACKAGE_MANAGER=""
|
||||
ADMIN_PASSWORD=""
|
||||
ADMIN_EMAIL="admin@example.com"
|
||||
DOMAIN_NAME=""
|
||||
SMTP_HOST=""
|
||||
@@ -78,6 +77,21 @@ run_as_user() {
|
||||
fi
|
||||
}
|
||||
|
||||
# Prompt for admin email interactively (unless provided or unattended)
|
||||
prompt_admin_email() {
|
||||
if [[ -n "$ADMIN_EMAIL" ]]; then
|
||||
return
|
||||
fi
|
||||
if [[ "$UNATTENDED" == "true" ]]; then
|
||||
ADMIN_EMAIL="admin@example.com"
|
||||
return
|
||||
fi
|
||||
echo
|
||||
echo "Please enter the admin email address (used for the initial admin account):"
|
||||
read -p "Admin email [admin@example.com]: " ADMIN_EMAIL
|
||||
ADMIN_EMAIL=${ADMIN_EMAIL:-admin@example.com}
|
||||
}
|
||||
|
||||
print_banner() {
|
||||
echo -e "${PURPLE}"
|
||||
echo "╔════════════════════════════════════════════════════════════════════════╗"
|
||||
@@ -338,7 +352,7 @@ setup_docker_installation() {
|
||||
fi
|
||||
|
||||
log_step "Creating application directory at $app_dir"
|
||||
mkdir -p "$app_dir"/{storage/events/{active,archived},logs,backup,config}
|
||||
mkdir -p "$app_dir"/{storage/events/{active,archived},logs,backup,config,data,events}
|
||||
|
||||
# Clone repository
|
||||
log_step "Downloading PicPeak..."
|
||||
@@ -349,11 +363,20 @@ setup_docker_installation() {
|
||||
git clone "$REPO_URL" "$app_dir"
|
||||
fi
|
||||
|
||||
# Determine host user for container mapping (PUID/PGID)
|
||||
local host_uid host_gid
|
||||
if [[ -n "${SUDO_USER:-}" ]]; then
|
||||
host_uid=$(id -u "$SUDO_USER" 2>/dev/null || echo 1000)
|
||||
host_gid=$(id -g "$SUDO_USER" 2>/dev/null || echo 1000)
|
||||
else
|
||||
host_uid=$(id -u 2>/dev/null || echo 1000)
|
||||
host_gid=$(id -g 2>/dev/null || echo 1000)
|
||||
fi
|
||||
|
||||
# Generate secrets
|
||||
local jwt_secret=$(generate_jwt_secret)
|
||||
local db_password=$(generate_password)
|
||||
local redis_password=$(generate_password)
|
||||
[[ -z "$ADMIN_PASSWORD" ]] && ADMIN_PASSWORD=$(generate_password)
|
||||
|
||||
# Create .env file
|
||||
log_step "Creating configuration..."
|
||||
@@ -368,7 +391,10 @@ JWT_SECRET=$jwt_secret
|
||||
|
||||
# Admin
|
||||
ADMIN_EMAIL=$ADMIN_EMAIL
|
||||
ADMIN_PASSWORD=$ADMIN_PASSWORD
|
||||
|
||||
# Runtime user mapping for Docker bind mounts
|
||||
PUID=$host_uid
|
||||
PGID=$host_gid
|
||||
|
||||
# Database
|
||||
DB_HOST=postgres
|
||||
@@ -395,7 +421,7 @@ SMTP_FROM=${SMTP_USER:-noreply@localhost}
|
||||
|
||||
# URLs
|
||||
FRONTEND_URL=${DOMAIN_NAME:+https://$DOMAIN_NAME}
|
||||
ADMIN_URL=${DOMAIN_NAME:+https://$DOMAIN_NAME/admin}
|
||||
ADMIN_URL=${DOMAIN_NAME:+https://$DOMAIN_NAME}
|
||||
|
||||
# Features
|
||||
ENABLE_FILE_WATCHER=true
|
||||
@@ -403,6 +429,9 @@ ENABLE_EXPIRATION_CHECKER=true
|
||||
ENABLE_EMAIL_SERVICE=true
|
||||
DEFAULT_EXPIRY_DAYS=30
|
||||
EOF
|
||||
|
||||
# Ensure bind mounts are writable by mapped user
|
||||
chown -R "$host_uid":"$host_gid" "$app_dir"/storage "$app_dir"/logs "$app_dir"/backup "$app_dir"/data "$app_dir"/events 2>/dev/null || true
|
||||
|
||||
# Create docker-compose.yml if it doesn't exist
|
||||
if [[ ! -f "$app_dir/docker-compose.yml" ]]; then
|
||||
@@ -618,7 +647,6 @@ setup_native_installation() {
|
||||
|
||||
# Generate secrets
|
||||
local jwt_secret=$(generate_jwt_secret)
|
||||
[[ -z "$ADMIN_PASSWORD" ]] && ADMIN_PASSWORD=$(generate_password)
|
||||
|
||||
# Create .env file
|
||||
log_step "Creating configuration..."
|
||||
@@ -633,7 +661,6 @@ JWT_SECRET=$jwt_secret
|
||||
|
||||
# Admin
|
||||
ADMIN_USERNAME=admin
|
||||
ADMIN_PASSWORD=$ADMIN_PASSWORD
|
||||
ADMIN_EMAIL=$ADMIN_EMAIL
|
||||
|
||||
# Database (native uses SQLite by default)
|
||||
@@ -653,7 +680,7 @@ SMTP_FROM=${SMTP_USER:-noreply@localhost}
|
||||
|
||||
# URLs
|
||||
FRONTEND_URL=${DOMAIN_NAME:+https://$DOMAIN_NAME}
|
||||
ADMIN_URL=${DOMAIN_NAME:+https://$DOMAIN_NAME/admin}
|
||||
ADMIN_URL=${DOMAIN_NAME:+https://$DOMAIN_NAME}
|
||||
|
||||
# Features
|
||||
ENABLE_FILE_WATCHER=true
|
||||
@@ -690,8 +717,15 @@ EOF
|
||||
# Start services
|
||||
log_step "Starting services..."
|
||||
systemctl daemon-reload
|
||||
systemctl enable picpeak-backend picpeak-workers
|
||||
systemctl start picpeak-backend picpeak-workers
|
||||
systemctl enable picpeak-backend
|
||||
# Stop/remove legacy workers service if present
|
||||
if systemctl list-unit-files | grep -q '^picpeak-workers.service'; then
|
||||
systemctl disable picpeak-workers || true
|
||||
systemctl stop picpeak-workers || true
|
||||
rm -f /etc/systemd/system/picpeak-workers.service
|
||||
systemctl daemon-reload
|
||||
fi
|
||||
systemctl start picpeak-backend
|
||||
|
||||
log_success "Native installation completed!"
|
||||
}
|
||||
@@ -899,8 +933,32 @@ print_success_message() {
|
||||
echo
|
||||
echo "🔐 Admin Credentials:"
|
||||
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
|
||||
echo -e "Email: ${CYAN}$ADMIN_EMAIL${NC}"
|
||||
echo -e "Password: ${CYAN}$ADMIN_PASSWORD${NC}"
|
||||
# Read from ADMIN_CREDENTIALS.txt when available
|
||||
local cred_file email_line pass_line admin_email_val admin_pass_val
|
||||
if [[ "$INSTALL_METHOD" == "docker" ]]; then
|
||||
cred_file="$app_dir/data/ADMIN_CREDENTIALS.txt"
|
||||
else
|
||||
cred_file="$NATIVE_APP_DIR/app/backend/data/ADMIN_CREDENTIALS.txt"
|
||||
fi
|
||||
if [[ -f "$cred_file" ]]; then
|
||||
email_line=$(grep -m1 '^Email:' "$cred_file" || true)
|
||||
pass_line=$(grep -m1 '^Password:' "$cred_file" || true)
|
||||
admin_email_val=${email_line#Email: }
|
||||
admin_pass_val=${pass_line#Password: }
|
||||
if [[ -n "$admin_email_val" ]]; then
|
||||
echo -e "Email: ${CYAN}$admin_email_val${NC}"
|
||||
else
|
||||
echo -e "Email: ${CYAN}$ADMIN_EMAIL${NC}"
|
||||
fi
|
||||
if [[ -n "$admin_pass_val" ]]; then
|
||||
echo -e "Password: ${CYAN}$admin_pass_val${NC}"
|
||||
else
|
||||
echo -e "Password: ${YELLOW}(see $cred_file)${NC}"
|
||||
fi
|
||||
else
|
||||
echo -e "Email: ${CYAN}$ADMIN_EMAIL${NC}"
|
||||
echo -e "Password: ${YELLOW}(credentials file not found)${NC}"
|
||||
fi
|
||||
echo
|
||||
echo -e "${YELLOW}⚠️ IMPORTANT: Change the admin password on first login!${NC}"
|
||||
|
||||
@@ -924,8 +982,8 @@ print_success_message() {
|
||||
echo "🔧 Service Commands:"
|
||||
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
|
||||
echo "View logs: sudo journalctl -u picpeak-backend -f"
|
||||
echo "Stop: sudo systemctl stop picpeak-backend picpeak-workers"
|
||||
echo "Start: sudo systemctl start picpeak-backend picpeak-workers"
|
||||
echo "Stop: sudo systemctl stop picpeak-backend"
|
||||
echo "Start: sudo systemctl start picpeak-backend"
|
||||
echo "Status: sudo systemctl status picpeak-backend"
|
||||
fi
|
||||
|
||||
@@ -944,16 +1002,31 @@ print_success_message() {
|
||||
|
||||
update_installation() {
|
||||
print_header "Updating PicPeak"
|
||||
|
||||
# Detect existing installation
|
||||
if [[ -d "$DOCKER_APP_DIR" ]] || [[ -d "/home/${SUDO_USER:-}/picpeak" ]]; then
|
||||
INSTALL_METHOD="docker"
|
||||
update_docker_installation
|
||||
elif [[ -d "$NATIVE_APP_DIR" ]]; then
|
||||
|
||||
# Prefer explicit native install detection first
|
||||
native_detected=false
|
||||
docker_detected=false
|
||||
|
||||
# Native detection: app/backend exists OR systemd unit present
|
||||
if [[ -d "$NATIVE_APP_DIR/app/backend" ]]; then
|
||||
native_detected=true
|
||||
elif command -v systemctl >/dev/null 2>&1 && systemctl list-unit-files | grep -q '^picpeak-backend.service'; then
|
||||
native_detected=true
|
||||
fi
|
||||
|
||||
# Docker detection: docker app dir or user home picpeak dir exists
|
||||
if [[ -d "$DOCKER_APP_DIR" ]] || [[ -n "${SUDO_USER:-}" && -d "/home/${SUDO_USER}/picpeak" ]]; then
|
||||
docker_detected=true
|
||||
fi
|
||||
|
||||
if [[ "$native_detected" == true ]]; then
|
||||
INSTALL_METHOD="native"
|
||||
update_native_installation
|
||||
elif [[ "$docker_detected" == true ]]; then
|
||||
INSTALL_METHOD="docker"
|
||||
update_docker_installation
|
||||
else
|
||||
die "No existing PicPeak installation found"
|
||||
die "No existing PicPeak installation found (native dir $NATIVE_APP_DIR/app/backend or docker dir $DOCKER_APP_DIR not present)"
|
||||
fi
|
||||
}
|
||||
|
||||
@@ -986,7 +1059,10 @@ update_native_installation() {
|
||||
log_step "Updating native installation..."
|
||||
|
||||
# Stop services
|
||||
systemctl stop picpeak-backend picpeak-workers
|
||||
systemctl stop picpeak-backend || true
|
||||
if systemctl list-unit-files | grep -q '^picpeak-workers.service'; then
|
||||
systemctl stop picpeak-workers || true
|
||||
fi
|
||||
|
||||
# Backup current configuration
|
||||
if [[ -f "$NATIVE_APP_DIR/app/backend/.env" ]]; then
|
||||
@@ -1009,9 +1085,25 @@ update_native_installation() {
|
||||
|
||||
# Run migrations
|
||||
run_as_user "npm run migrate"
|
||||
|
||||
# Rebuild frontend (ensure admin UI for native installs)
|
||||
if [[ -d "$NATIVE_APP_DIR/app/frontend" ]]; then
|
||||
log_step "Rebuilding frontend..."
|
||||
cd "$NATIVE_APP_DIR/app/frontend"
|
||||
run_as_user "npm ci --include=dev" || run_as_user "npm install"
|
||||
run_as_user "npm run build"
|
||||
fi
|
||||
|
||||
# Ensure env has frontend serving flags
|
||||
if ! grep -q '^SERVE_FRONTEND=' "$NATIVE_APP_DIR/app/backend/.env"; then
|
||||
echo "SERVE_FRONTEND=true" >> "$NATIVE_APP_DIR/app/backend/.env"
|
||||
fi
|
||||
if ! grep -q '^FRONTEND_DIR=' "$NATIVE_APP_DIR/app/backend/.env"; then
|
||||
echo "FRONTEND_DIR=$NATIVE_APP_DIR/app/frontend/dist" >> "$NATIVE_APP_DIR/app/backend/.env"
|
||||
fi
|
||||
|
||||
# Restart services
|
||||
systemctl start picpeak-backend picpeak-workers
|
||||
systemctl restart picpeak-backend
|
||||
|
||||
log_success "Native installation updated successfully!"
|
||||
}
|
||||
@@ -1105,10 +1197,6 @@ parse_arguments() {
|
||||
ADMIN_EMAIL="$2"
|
||||
shift 2
|
||||
;;
|
||||
--admin-password)
|
||||
ADMIN_PASSWORD="$2"
|
||||
shift 2
|
||||
;;
|
||||
--smtp-host)
|
||||
SMTP_HOST="$2"
|
||||
shift 2
|
||||
@@ -1166,7 +1254,6 @@ Options:
|
||||
--unattended Run without prompts
|
||||
--domain DOMAIN Set domain name for HTTPS
|
||||
--email EMAIL Admin email address
|
||||
--admin-password Admin password (auto-generated if not set)
|
||||
--smtp-host HOST SMTP server hostname
|
||||
--smtp-port PORT SMTP server port
|
||||
--smtp-user USER SMTP username
|
||||
@@ -1189,7 +1276,7 @@ Examples:
|
||||
|
||||
# Fully automated Docker setup
|
||||
sudo $0 --docker --unattended --domain photos.example.com \\
|
||||
--email admin@example.com --admin-password SecurePass123 \\
|
||||
--email admin@example.com \\
|
||||
--smtp-host smtp.gmail.com --smtp-port 587 \\
|
||||
--smtp-user user@gmail.com --smtp-pass app-password \\
|
||||
--enable-ssl
|
||||
@@ -1229,6 +1316,9 @@ main() {
|
||||
# Check system requirements
|
||||
check_system_requirements
|
||||
|
||||
# Prompt for admin email (design choice: always ask unless provided)
|
||||
prompt_admin_email
|
||||
|
||||
# Configure email (optional)
|
||||
configure_email
|
||||
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 212 B |
Binary file not shown.
|
After Width: | Height: | Size: 212 B |
@@ -0,0 +1,43 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
|
||||
const ADMIN_EMAIL = process.env.ADMIN_EMAIL || 'admin@example.com';
|
||||
const ADMIN_PASSWORD = process.env.ADMIN_PASSWORD || 'Admin!234';
|
||||
|
||||
function randomSuffix() {
|
||||
return Math.random().toString(36).slice(2, 8);
|
||||
}
|
||||
|
||||
test('admin can create event via UI', async ({ page }) => {
|
||||
const eventName = `UI Playwright ${randomSuffix()}`;
|
||||
const hostEmail = `host+${randomSuffix()}@example.com`;
|
||||
|
||||
// Login
|
||||
await page.goto('/admin/login');
|
||||
await page.getByLabel(/Email/i).fill(ADMIN_EMAIL);
|
||||
await page.getByLabel(/Password/i).fill(ADMIN_PASSWORD);
|
||||
await page.getByRole('button', { name: /Sign In|Log in/i }).click();
|
||||
await expect(page.getByRole('heading', { name: /Dashboard/i })).toBeVisible({ timeout: 20000 });
|
||||
|
||||
// Navigate to create event page
|
||||
const createButton = page.getByRole('button', { name: /Create Event/i });
|
||||
if (await createButton.count()) {
|
||||
await createButton.first().click();
|
||||
} else {
|
||||
await page.goto('/admin/events/new');
|
||||
}
|
||||
|
||||
await expect(page.getByRole('heading', { name: /^Create$/i })).toBeVisible({ timeout: 10000 });
|
||||
|
||||
await page.getByLabel(/Event Name/i).fill(eventName);
|
||||
await page.getByLabel(/Host Name/i).fill('Host User');
|
||||
await page.getByLabel(/Event Date/i).fill('2025-12-31');
|
||||
await page.getByLabel(/Host Email/i).fill(hostEmail);
|
||||
await page.getByLabel(/Admin Email/i).fill(ADMIN_EMAIL);
|
||||
await page.getByLabel(/Gallery Password/i).fill('UiPlay123!');
|
||||
await page.getByLabel(/Confirm Password/i).fill('UiPlay123!');
|
||||
|
||||
await page.getByRole('button', { name: /Create Event/i }).click();
|
||||
|
||||
await expect(page).toHaveURL(/\/admin\/events\//, { timeout: 20000 });
|
||||
await expect(page.getByRole('heading', { name: eventName })).toBeVisible();
|
||||
});
|
||||
@@ -0,0 +1,100 @@
|
||||
import { test, expect, Page } from '@playwright/test';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
const ADMIN_EMAIL = process.env.ADMIN_EMAIL || 'admin@example.com';
|
||||
const ADMIN_PASSWORD = process.env.ADMIN_PASSWORD || 'Admin!234';
|
||||
const GALLERY_PASSWORD = process.env.GALLERY_PASSWORD || 'PlaywrightGallery123!';
|
||||
|
||||
async function createEventWithPhotos(page: Page) {
|
||||
const api = page.request;
|
||||
const loginResponse = await api.post('/api/auth/admin/login', {
|
||||
data: {
|
||||
username: ADMIN_EMAIL,
|
||||
password: ADMIN_PASSWORD,
|
||||
},
|
||||
});
|
||||
expect(loginResponse.ok()).toBeTruthy();
|
||||
const { token } = await loginResponse.json();
|
||||
expect(token).toBeTruthy();
|
||||
|
||||
const eventName = `Playwright Smoke ${Date.now()}`;
|
||||
const eventDate = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)
|
||||
.toISOString()
|
||||
.slice(0, 10);
|
||||
|
||||
const eventResponse = await api.post('/api/admin/events', {
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
data: {
|
||||
event_type: 'wedding',
|
||||
event_name: eventName,
|
||||
event_date: eventDate,
|
||||
host_name: 'Playwright Host',
|
||||
host_email: 'host@example.com',
|
||||
admin_email: ADMIN_EMAIL,
|
||||
password: GALLERY_PASSWORD,
|
||||
expiration_days: 30,
|
||||
allow_user_uploads: false,
|
||||
allow_downloads: true,
|
||||
disable_right_click: false,
|
||||
watermark_downloads: false,
|
||||
},
|
||||
});
|
||||
expect(eventResponse.ok()).toBeTruthy();
|
||||
const event = await eventResponse.json();
|
||||
|
||||
const imagePath = path.join(process.cwd(), 'test-assets', 'img1.png');
|
||||
const buffer = fs.readFileSync(imagePath);
|
||||
const uploadResponse = await api.post(`/api/admin/events/${event.id}/upload`, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
multipart: {
|
||||
photos: {
|
||||
name: path.basename(imagePath),
|
||||
mimeType: 'image/png',
|
||||
buffer,
|
||||
},
|
||||
category_id: 'individual',
|
||||
},
|
||||
});
|
||||
expect(uploadResponse.ok()).toBeTruthy();
|
||||
|
||||
return {
|
||||
event,
|
||||
shareLink: event.share_link,
|
||||
slug: event.slug,
|
||||
};
|
||||
}
|
||||
|
||||
test('admin login and gallery viewing smoke test', async ({ page }) => {
|
||||
const { shareLink } = await createEventWithPhotos(page);
|
||||
|
||||
// Admin UI login
|
||||
await page.goto('/admin/login');
|
||||
const emailField = page.getByLabel(/Email/i);
|
||||
if (await emailField.count()) {
|
||||
await emailField.fill(ADMIN_EMAIL);
|
||||
await page.getByLabel(/Password/i).fill(ADMIN_PASSWORD);
|
||||
await page.getByRole('button', { name: /Sign In|Log in/i }).click();
|
||||
}
|
||||
await expect(page.getByRole('heading', { name: /Dashboard/i })).toBeVisible({ timeout: 20000 });
|
||||
|
||||
// Visit gallery share link and authenticate
|
||||
await page.goto(shareLink);
|
||||
const passwordField = page.getByPlaceholder(/gallery password/i);
|
||||
await passwordField.fill(GALLERY_PASSWORD);
|
||||
await page.getByRole('button', { name: /View Gallery/i }).click();
|
||||
|
||||
// Wait for photos grid to appear
|
||||
const tiles = page.locator('.relative.group');
|
||||
await expect(tiles.first()).toBeVisible({ timeout: 20000 });
|
||||
|
||||
// Open lightbox to ensure media renders
|
||||
await tiles.first().hover();
|
||||
await tiles.first().getByRole('button', { name: /View full size/i }).click();
|
||||
await expect(page.getByRole('button', { name: /Close/i })).toBeVisible();
|
||||
});
|
||||
@@ -0,0 +1,226 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
import type { Page } from '@playwright/test';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
const ADMIN_EMAIL = process.env.ADMIN_EMAIL || 'admin@example.com';
|
||||
const ADMIN_PASSWORD = process.env.ADMIN_PASSWORD || 'Admin!234';
|
||||
const GALLERY_PASSWORD = process.env.GALLERY_PASSWORD || 'PlaywrightGallery123!';
|
||||
|
||||
interface GallerySetupResult {
|
||||
shareLink: string;
|
||||
slug: string;
|
||||
allPhotosData: {
|
||||
event: any;
|
||||
categories?: any;
|
||||
photos: Array<{ id: number; filename: string; comment_count?: number }>;
|
||||
};
|
||||
}
|
||||
|
||||
async function createGalleryWithModeratedComments(page: Page): Promise<GallerySetupResult> {
|
||||
const loginResponse = await page.request.post('/api/auth/admin/login', {
|
||||
data: {
|
||||
username: ADMIN_EMAIL,
|
||||
password: ADMIN_PASSWORD,
|
||||
},
|
||||
failOnStatusCode: false,
|
||||
});
|
||||
expect(loginResponse.ok()).toBeTruthy();
|
||||
const { token } = await loginResponse.json();
|
||||
expect(token).toBeTruthy();
|
||||
|
||||
const eventName = `Playwright Feedback Filter ${Date.now()}`;
|
||||
const eventDate = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)
|
||||
.toISOString()
|
||||
.slice(0, 10);
|
||||
|
||||
const createResponse = await page.request.post('/api/admin/events', {
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
data: {
|
||||
event_type: 'wedding',
|
||||
event_name: eventName,
|
||||
event_date: eventDate,
|
||||
host_name: 'Playwright Host',
|
||||
host_email: 'host@example.com',
|
||||
admin_email: ADMIN_EMAIL,
|
||||
password: GALLERY_PASSWORD,
|
||||
expiration_days: 30,
|
||||
allow_user_uploads: false,
|
||||
allow_downloads: true,
|
||||
disable_right_click: false,
|
||||
watermark_downloads: false,
|
||||
feedback_enabled: true,
|
||||
allow_ratings: true,
|
||||
allow_likes: true,
|
||||
allow_comments: true,
|
||||
allow_favorites: true,
|
||||
require_name_email: false,
|
||||
moderate_comments: true,
|
||||
show_feedback_to_guests: true,
|
||||
},
|
||||
failOnStatusCode: false,
|
||||
});
|
||||
|
||||
expect(createResponse.ok()).toBeTruthy();
|
||||
const createdEvent = await createResponse.json();
|
||||
expect(createdEvent?.id).toBeTruthy();
|
||||
|
||||
const imagePaths = ['img1.png', 'img2.png'];
|
||||
const photoIds: number[] = [];
|
||||
|
||||
for (const file of imagePaths) {
|
||||
const imagePath = path.join(process.cwd(), 'test-assets', file);
|
||||
const buffer = fs.readFileSync(imagePath);
|
||||
const uploadResponse = await page.request.post(
|
||||
`/api/admin/events/${createdEvent.id}/upload`,
|
||||
{
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
multipart: {
|
||||
photos: {
|
||||
name: path.basename(imagePath),
|
||||
mimeType: 'image/png',
|
||||
buffer,
|
||||
},
|
||||
category_id: 'individual',
|
||||
},
|
||||
failOnStatusCode: false,
|
||||
}
|
||||
);
|
||||
expect(uploadResponse.ok()).toBeTruthy();
|
||||
const uploadJson = await uploadResponse.json();
|
||||
const uploaded = uploadJson?.photos?.[0];
|
||||
expect(uploaded?.id).toBeTruthy();
|
||||
photoIds.push(uploaded.id);
|
||||
}
|
||||
|
||||
expect(photoIds.length).toBeGreaterThanOrEqual(2);
|
||||
|
||||
const galleryAuthResponse = await page.request.post('/api/auth/gallery/verify', {
|
||||
data: {
|
||||
slug: createdEvent.slug,
|
||||
password: GALLERY_PASSWORD,
|
||||
},
|
||||
failOnStatusCode: false,
|
||||
});
|
||||
expect(galleryAuthResponse.ok()).toBeTruthy();
|
||||
const { token: galleryToken } = await galleryAuthResponse.json();
|
||||
expect(galleryToken).toBeTruthy();
|
||||
|
||||
// Submit an approved comment (after moderation)
|
||||
const approvedCommentResponse = await page.request.post(
|
||||
`/api/gallery/${createdEvent.slug}/photos/${photoIds[0]}/feedback`,
|
||||
{
|
||||
headers: {
|
||||
Authorization: `Bearer ${galleryToken}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
data: {
|
||||
feedback_type: 'comment',
|
||||
comment_text: 'Approved comment',
|
||||
guest_name: 'Approved Guest',
|
||||
guest_email: 'approved@example.com',
|
||||
},
|
||||
failOnStatusCode: false,
|
||||
}
|
||||
);
|
||||
expect(approvedCommentResponse.ok()).toBeTruthy();
|
||||
const approvedComment = await approvedCommentResponse.json();
|
||||
expect(approvedComment?.id).toBeTruthy();
|
||||
|
||||
const approveModeration = await page.request.put(
|
||||
`/api/admin/feedback/feedback/${approvedComment.id}/approve`,
|
||||
{
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
failOnStatusCode: false,
|
||||
}
|
||||
);
|
||||
expect(approveModeration.ok()).toBeTruthy();
|
||||
|
||||
// Submit a second comment that remains pending
|
||||
const pendingCommentResponse = await page.request.post(
|
||||
`/api/gallery/${createdEvent.slug}/photos/${photoIds[1]}/feedback`,
|
||||
{
|
||||
headers: {
|
||||
Authorization: `Bearer ${galleryToken}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
data: {
|
||||
feedback_type: 'comment',
|
||||
comment_text: 'Pending comment',
|
||||
guest_name: 'Pending Guest',
|
||||
guest_email: 'pending@example.com',
|
||||
},
|
||||
failOnStatusCode: false,
|
||||
}
|
||||
);
|
||||
expect(pendingCommentResponse.ok()).toBeTruthy();
|
||||
|
||||
const allPhotosResponse = await page.request.get(`/api/gallery/${createdEvent.slug}/photos`, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${galleryToken}`,
|
||||
},
|
||||
failOnStatusCode: false,
|
||||
});
|
||||
expect(allPhotosResponse.ok()).toBeTruthy();
|
||||
const allPhotosData = await allPhotosResponse.json();
|
||||
expect(Array.isArray(allPhotosData?.photos)).toBeTruthy();
|
||||
|
||||
return {
|
||||
shareLink: createdEvent.share_link,
|
||||
slug: createdEvent.slug,
|
||||
allPhotosData,
|
||||
};
|
||||
}
|
||||
|
||||
test.describe('Gallery feedback filter', () => {
|
||||
test('Comment filter hides photos without approved comments', async ({ page }) => {
|
||||
const { shareLink, slug, allPhotosData } = await createGalleryWithModeratedComments(page);
|
||||
|
||||
const approvedPhotos = allPhotosData.photos.filter((photo) => (photo.comment_count || 0) > 0);
|
||||
expect(approvedPhotos.length).toBeGreaterThan(0);
|
||||
|
||||
await page.route(`**/api/gallery/${slug}/photos**`, async (route) => {
|
||||
const url = new URL(route.request().url());
|
||||
if (url.searchParams.get('filter') === 'commented') {
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(allPhotosData),
|
||||
});
|
||||
await page.unroute(`**/api/gallery/${slug}/photos**`);
|
||||
} else {
|
||||
await route.continue();
|
||||
}
|
||||
});
|
||||
|
||||
await page.goto(shareLink);
|
||||
await page.waitForLoadState('domcontentloaded');
|
||||
|
||||
const passwordField = page.getByPlaceholder(/gallery password/i).first();
|
||||
if (await passwordField.count()) {
|
||||
await passwordField.fill(GALLERY_PASSWORD);
|
||||
await page.getByRole('button', { name: /View Gallery/i }).click();
|
||||
}
|
||||
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
const tiles = page.locator('.relative.group');
|
||||
await expect(tiles.first()).toBeVisible({ timeout: 20000 });
|
||||
await expect(tiles).toHaveCount(allPhotosData.photos.length);
|
||||
|
||||
await page.getByRole('button', { name: /Commented/i }).click();
|
||||
|
||||
await expect(tiles).toHaveCount(approvedPhotos.length, { timeout: 20000 });
|
||||
|
||||
for (const pending of allPhotosData.photos.filter((photo) => (photo.comment_count || 0) === 0)) {
|
||||
await expect(page.getByAltText(pending.filename)).not.toBeVisible({ timeout: 1000 });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,180 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
const ADMIN_EMAIL = process.env.ADMIN_EMAIL || 'admin@example.com';
|
||||
const ADMIN_PASSWORD = process.env.ADMIN_PASSWORD || 'Admin!234';
|
||||
const GALLERY_PASSWORD = process.env.GALLERY_PASSWORD || 'PlaywrightGallery123!';
|
||||
|
||||
async function ensureGalleryWithPhotos(page) {
|
||||
const loginResponse = await page.request.post('/api/auth/admin/login', {
|
||||
data: {
|
||||
username: ADMIN_EMAIL,
|
||||
password: ADMIN_PASSWORD,
|
||||
},
|
||||
failOnStatusCode: false,
|
||||
});
|
||||
expect(loginResponse.ok()).toBeTruthy();
|
||||
const { token } = await loginResponse.json();
|
||||
expect(token).toBeTruthy();
|
||||
|
||||
const eventName = `Playwright MCP ${Date.now()}`;
|
||||
const eventDate = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)
|
||||
.toISOString()
|
||||
.slice(0, 10);
|
||||
|
||||
const createResponse = await page.request.post('/api/admin/events', {
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
data: {
|
||||
event_type: 'wedding',
|
||||
event_name: eventName,
|
||||
event_date: eventDate,
|
||||
host_name: 'Playwright Host',
|
||||
host_email: 'host@example.com',
|
||||
admin_email: ADMIN_EMAIL,
|
||||
password: GALLERY_PASSWORD,
|
||||
expiration_days: 90,
|
||||
allow_user_uploads: false,
|
||||
allow_downloads: true,
|
||||
disable_right_click: false,
|
||||
watermark_downloads: false,
|
||||
feedback_enabled: true,
|
||||
allow_ratings: true,
|
||||
allow_likes: true,
|
||||
allow_comments: true,
|
||||
allow_favorites: true,
|
||||
require_name_email: false,
|
||||
moderate_comments: false,
|
||||
show_feedback_to_guests: true,
|
||||
},
|
||||
failOnStatusCode: false,
|
||||
});
|
||||
|
||||
expect(createResponse.ok()).toBeTruthy();
|
||||
const createdEvent = await createResponse.json();
|
||||
expect(createdEvent?.id).toBeTruthy();
|
||||
|
||||
const imagePaths = ['img1.png', 'img2.png'].map((file) =>
|
||||
path.join(process.cwd(), 'test-assets', file)
|
||||
);
|
||||
|
||||
for (const imagePath of imagePaths) {
|
||||
const buffer = fs.readFileSync(imagePath);
|
||||
const uploadResponse = await page.request.post(
|
||||
`/api/admin/events/${createdEvent.id}/upload`,
|
||||
{
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
multipart: {
|
||||
photos: {
|
||||
name: path.basename(imagePath),
|
||||
mimeType: 'image/png',
|
||||
buffer,
|
||||
},
|
||||
category_id: 'individual',
|
||||
},
|
||||
failOnStatusCode: false,
|
||||
}
|
||||
);
|
||||
expect(uploadResponse.ok()).toBeTruthy();
|
||||
}
|
||||
|
||||
return {
|
||||
shareLink: createdEvent.share_link,
|
||||
slug: createdEvent.slug,
|
||||
};
|
||||
}
|
||||
|
||||
test.describe('Gallery grid tile quick actions', () => {
|
||||
test('Each tile: open, download, comment, like with immediate UI', async ({ page }) => {
|
||||
const { shareLink } = await ensureGalleryWithPhotos(page);
|
||||
|
||||
await page.goto(shareLink);
|
||||
const gallery = page;
|
||||
await gallery.waitForLoadState('domcontentloaded');
|
||||
await gallery.waitForURL(/\/gallery\//);
|
||||
|
||||
const passwordField = gallery.getByPlaceholder(/gallery password/i).first();
|
||||
if (await passwordField.count()) {
|
||||
await passwordField.fill(GALLERY_PASSWORD);
|
||||
await gallery.getByRole('button', { name: /View Gallery/i }).click();
|
||||
await gallery.waitForLoadState('networkidle');
|
||||
}
|
||||
|
||||
// Ensure grid tiles rendered
|
||||
const tiles = gallery.locator('.relative.group');
|
||||
await expect(tiles.first()).toBeVisible({ timeout: 20000 });
|
||||
|
||||
const tileCount = await tiles.count();
|
||||
expect(tileCount).toBeGreaterThan(0);
|
||||
|
||||
// Limit to a few tiles to keep test time sensible
|
||||
const N = Math.min(tileCount, 3);
|
||||
for (let i = 0; i < N; i++) {
|
||||
const tile = tiles.nth(i);
|
||||
await tile.scrollIntoViewIfNeeded();
|
||||
// On desktop, actions show on hover
|
||||
await tile.hover({ force: true });
|
||||
|
||||
// Actions should be present
|
||||
const openBtn = tile.getByRole('button', { name: /View full size/i });
|
||||
await expect(openBtn).toBeVisible();
|
||||
|
||||
const likeBtn = tile.getByRole('button', { name: /Like photo/i }).first();
|
||||
await expect(likeBtn).toBeVisible();
|
||||
|
||||
const commentBtn = tile.getByRole('button', { name: /Comment on photo|Comment/i }).first();
|
||||
await expect(commentBtn).toBeVisible();
|
||||
|
||||
const downloadBtn = tile.getByRole('button', { name: /Download photo/i }).first();
|
||||
await expect(downloadBtn).toBeVisible();
|
||||
|
||||
// Like should toggle to red and indicator appear immediately
|
||||
const pressedBefore = await likeBtn.getAttribute('aria-pressed');
|
||||
await likeBtn.click();
|
||||
await expect.poll(async () => (await likeBtn.getAttribute('aria-pressed')) || '').toContain('true');
|
||||
// Feedback indicator (title="Liked") should appear on the tile
|
||||
await expect(tile.locator('[title="Liked"]')).toBeVisible();
|
||||
|
||||
// Open lightbox
|
||||
await openBtn.click();
|
||||
const closeLightboxBtn = gallery.getByRole('button', { name: /^Close$/i }).first();
|
||||
await expect(closeLightboxBtn).toBeVisible();
|
||||
// Close again to continue
|
||||
await closeLightboxBtn.click();
|
||||
|
||||
// Comment quick action should open lightbox with feedback panel visible
|
||||
await tile.hover({ force: true });
|
||||
await commentBtn.click();
|
||||
await expect(gallery.getByRole('button', { name: /Toggle feedback/ })).toBeVisible();
|
||||
|
||||
// Ensure feedback panel is visible or open it
|
||||
const feedbackHeading = gallery.getByRole('heading', { name: /Photo Feedback/i });
|
||||
if (!(await feedbackHeading.isVisible())) {
|
||||
await gallery.getByRole('button', { name: /Toggle feedback/ }).click();
|
||||
}
|
||||
await expect(feedbackHeading).toBeVisible();
|
||||
|
||||
// Comments quick action should surface the feedback tools
|
||||
const addCommentBtn = gallery.getByRole('button', { name: /Add Comment|Add comment/i });
|
||||
await expect(addCommentBtn).toBeVisible();
|
||||
await addCommentBtn.click();
|
||||
// Allow UI to react without requiring text entry
|
||||
await gallery.waitForTimeout(250);
|
||||
|
||||
// Close lightbox to continue (we do not submit to keep test idempotent)
|
||||
await closeLightboxBtn.click();
|
||||
|
||||
// Download from tile should trigger a browser download event
|
||||
await tile.hover({ force: true });
|
||||
const downloadPromise = gallery.waitForEvent('download');
|
||||
await downloadBtn.click();
|
||||
const download = await downloadPromise;
|
||||
expect((await download.path()) !== null).toBeTruthy();
|
||||
}
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user